2016-04-06 16 views
7

Sto iniziando con pytest. Ho configurato pytest, comunque non sono riuscito a trovare una risorsa sui test specifici di Django con pytest. Come posso testare un modello con pytest_django?Come testare un modello Django con pytest?

Ho già chiesto una domanda su unit testing,

how do I efficiently test this Django model?

Voglio sapere come gli stessi test possono essere scritti con py.test?

aggiungendo sotto il modello e le prove scritte in unittest.

il modello in prova è,

class User(AbstractBaseUser, PermissionsMixin): 
    username = models.CharField(max_length=25, unique=True, error_messages={ 
     'unique': 'The username is taken' 
    }) 
    first_name = models.CharField(max_length=60, blank=True, null=True) 
    last_name = models.CharField(max_length=60, blank=True, null=True) 
    email = models.EmailField(unique=True, db_index=True, error_messages={ 
     'unique': 'This email id is already registered!' 
    }) 

    is_active = models.BooleanField(default=True) 
    is_staff = models.BooleanField(default=False) 

    date_joined = models.DateTimeField(auto_now_add=True) 

    USERNAME_FIELD = 'email' 
    REQUIRED_FIELDS = ['username',] 


    objects = UserManager() 

    def get_full_name(self): 
     return ' '.join([self.first_name, self.last_name]) 

    def get_short_name(self): 
     return self.email 

    def __unicode__(self): 
     return self.username 

e la unittest scritta,

class SettingsTest(TestCase):  
    def test_account_is_configured(self): 
     self.assertTrue('accounts' in INSTALLED_APPS) 
     self.assertTrue('accounts.User' == AUTH_USER_MODEL) 


class UserTest(TestCase): 
    def setUp(self): 
     self.username = "testuser" 
     self.email = "[email protected]" 
     self.first_name = "Test" 
     self.last_name = "User" 
     self.password = "z" 

     self.test_user = User.objects.create_user(
      username=self.username, 
      email=self.email, 
      first_name=self.first_name, 
      last_name=self.last_name 
     ) 

    def test_create_user(self): 
     self.assertIsInstance(self.test_user, User) 

    def test_default_user_is_active(self): 
     self.assertTrue(self.test_user.is_active) 

    def test_default_user_is_staff(self): 
     self.assertFalse(self.test_user.is_staff) 

    def test_default_user_is_superuser(self): 
     self.assertFalse(self.test_user.is_superuser) 

    def test_get_full_name(self): 
     self.assertEqual('Test User', self.test_user.get_full_name()) 

    def test_get_short_name(self): 
     self.assertEqual(self.email, self.test_user.get_short_name()) 

    def test_unicode(self): 
     self.assertEqual(self.username, self.test_user.__unicode__()) 

Grazie per qualsiasi ingresso.

risposta

1

pytest ha il supporto per l'esecuzione di prove di Python stile unittest.py. È pensato per sfruttare i progetti esistenti in stile unittest per utilizzare le funzionalità pytest. Concretamente, pytest raccoglierà automaticamente sottoclassi unittest.TestCase e i loro metodi di test nei file di test. Invocherà i tipici metodi di setup/teardown e in genere cercherò di creare suite di test scritte per essere eseguite su unittest, e di eseguire anche pytest.

I test indicati possono essere testati con py.test senza alcuna modifica, tuttavia py.test rende i test più pietosi.

class SettingsTest(TestCase):  
    def test_account_is_configured(self): 
     assert 'accounts' in INSTALLED_APPS 
     assert 'accounts.User' == AUTH_USER_MODEL 


class UserTest(TestCase): 
    def setUp(self): 
     self.username = "testuser" 
     self.email = "[email protected]stbase.com" 
     self.first_name = "Test" 
     self.last_name = "User" 
     self.password = "z" 

     self.test_user = User.objects.create_user(
      username=self.username, 
      email=self.email, 
      first_name=self.first_name, 
      last_name=self.last_name 
     ) 

    def test_create_user(self): 
     assert isinstance(self.test_user, User) 

    def test_default_user_is_active(self): 
     assert self.test_user.is_active 

    def test_default_user_is_staff(self): 
     assert not self.test_user.is_staff 

    def test_default_user_is_superuser(self): 
     assert not self.test_user.is_superuser 

    def test_get_full_name(self): 
     assert self.test_user.get_full_name() == 'Test User' 

    def test_get_short_name(self): 
     assert self.test_user.get_short_name() == self.email 

    def test_unicode(self): 
     assert self.test_user.__unicode__() == self.username 

come detto @Sid, è possibile utilizzare il @pytest.mark.django_db marcatore (decoratore) per accedere al database durante l'esecuzione di un test senza utilizzare django.test.TestCase,

4

È possibile utilizzare questo plugin che si integra con pytest Django: https://pytest-django.readthedocs.org/en/latest/tutorial.html

La configurazione e le modifiche ai pytest.ini sono descritte qui: http://www.johnmcostaiii.net/2013/django-projects-to-django-apps-converting-the-unit-tests/

Troverete il vostro esempio qui a partire dalla slitta 57. Questo banco sarà utile per testare le viste, nonché i modelli e le impostazioni specifiche per i modelli di test: https://speakerdeck.com/pelme/testing-django-applications-with-py-dot-test-europython-2013

In particolare, guardare @ pytest.mark.django_db helper docu menzionato qui: http://pytest-django.readthedocs.org/en/latest/helpers.html

Un esempio per consentire l'accesso db in un test menzionato anche nel deck qui sopra viene copiato qui. Senza mark.django_db il test fallirebbe.

import pytest 
@pytest.mark.django_db 
def test_user_count(): 
    assert User.objects.count() == 0 
Problemi correlati