By default when Django runs against sqlite backend it creates a new in memory database for a test. That means for every class that derives from unittest.TestCase, I get a new database. Can this be changed so that it is cleared before every test method is run?
Example: I am testing a manager class that provides additional abstraction on top of Django persistent objects. The code looks more-less like that
class TestForManager(unittest.TestCase): def testAddingBlah(self): manager = Manager() self.assertEquals(manager.getBlahs(), 0) manager.addBlah(...) self.assertEquals(manager.getBlahs(), 1) def testAddingBlahInDifferentWay(self): manager = Manager() self.assertEquals(manager.getBlahs(), 0) manager.addBlahInDifferentWay(...) self.assertEquals(manager.getBlahs(), 1)
Now, the first assertion of second test fails, because the state of the database is preserved between test calls and there already is an instance of Blah
in the database.
Order in which tests are executedAll TestCase subclasses are run first. Then, all other Django-based tests (test cases based on SimpleTestCase , including TransactionTestCase ) are run with no particular ordering guaranteed nor enforced among them. Then any other unittest.
The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.
Open /catalog/tests/test_models.py.from django. test import TestCase # Create your tests here. Often you will add a test class for each model/view/form you want to test, with individual methods for testing specific functionality.
Use django.test.TestCase
not unittest.TestCase
. And it works in all major versions of Django!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With