Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaning up a database in django before every test method

Tags:

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.

like image 205
Marcin Avatar asked Jan 12 '09 07:01

Marcin


People also ask

What order Django tests are run?

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.

How do I test a Django project?

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.

How do I run tests PY in Django?

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.


1 Answers

Use django.test.TestCase not unittest.TestCase. And it works in all major versions of Django!

like image 125
Marcin Avatar answered Sep 16 '22 18:09

Marcin