2012-06-14 9 views
5

Mam kilka testów jednostkowych, które napisałem, aby przetestować moją aplikację Django. W szczególności jeden pakiet testowy ma wiele funkcji w swojej funkcji setUp(). Celem tego kodu jest utworzenie danych testowych dla bazy danych. (Tak, wiem o urządzeniach i zdecydowałem, że nie używam ich w tym przypadku). Po uruchomieniu pakietu testów jednostkowych uruchamiany jest pierwszy test, ale pozostałe testy w pakiecie kończą się niepowodzeniem. Komunikat o wszystkich błędach jest taki sam: wspomina, że ​​lokalizacja błędu to "self.database_object.save()", a przyczyną jest "IntegrityError: nazwa kolumny nie jest unikalna". Domyślam się, że Django nie wyłapuje poprawnie bazy danych po każdym teście.Baza danych testów jednostkowych Django nie została zerwana?

Wcześniej dzisiaj działało, ale domyślam się, że trochę go pomieszałem. Jakieś pomysły na to, dlaczego Django nie wyłapuje poprawnie bazy danych po każdym teście?

Odpowiedz

8

Czy używasz TestCase lub TransactionTestCase dla swojej klasy bazowej? Czasami takie zachowanie jest związane z optymalizacją, którą Django robi dla TestCase na korzyść TransactionTestCase. Oto różnica:

https://docs.djangoproject.com/en/dev/topics/testing/?from=olddocs#django.test.TransactionTestCase

class TransactionTestCase

Django TestCase classes make use of database transaction facilities, if available, to speed up the process of resetting the database to a known state at the beginning of each test. A consequence of this, however, is that the effects of transaction commit and rollback cannot be tested by a Django TestCase class. If your test requires testing of such transactional behavior, you should use a Django TransactionTestCase.

TransactionTestCase and TestCase are identical except for the manner in which the database is reset to a known state and the ability for test code to test the effects of commit and rollback. A TransactionTestCase resets the database before the test runs by truncating all tables and reloading initial data. A TransactionTestCase may call commit and rollback and observe the effects of these calls on the database.

A TestCase, on the other hand, does not truncate tables and reload initial data at the beginning of a test. Instead, it encloses the test code in a database transaction that is rolled back at the end of the test. It also prevents the code under test from issuing any commit or rollback operations on the database, to ensure that the rollback at the end of the test restores the database to its initial state. In order to guarantee that all TestCase code starts with a clean database, the Django test runner runs all TestCase tests first, before any other tests (e.g. doctests) that may alter the database without restoring it to its original state.

+0

To było na miejscu. Dziękuję bardzo Tisho! –

Powiązane problemy