2012-06-14 20 views
5

Ho alcuni test unitari che ho scritto per testare la mia applicazione Django. Una suite di test in particolare ha un sacco di codice nella sua funzione setUp(). Lo scopo di tale codice è di creare dati di test per il database. (Sì, so di infissi e ho scelto di non usarli in questo caso). Quando eseguo la suite di test delle unità, viene eseguito il primo test eseguito, ma il resto dei test nella suite non riesce. Il messaggio per tutti gli errori è lo stesso: indica che la posizione dell'errore è "self.database_object.save()" e che la causa è "IntegrityError: il nome della colonna non è univoco". Quindi, la mia ipotesi migliore è che Django non stia distruggendo il database correttamente dopo ogni test.Il database di test dell'unità Django non viene rimosso?

In precedenza oggi funzionava, ma suppongo che alcuni refactoring l'abbiano incasinato. Qualche idea sul perché Django non stia distruggendo correttamente il database dopo ogni test?

risposta

8

Usi TestCase o TransactionTestCase per la tua classe base? A volte questo comportamento è correlato all'ottimizzazione eseguita da Django per TestCase in favore di TransactionTestCase. Ecco la differenza:

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

Quella era perfetto. Grazie mille Tisho! –

Problemi correlati