Search code examples
djangodjango-testing

In Django how can I preserve the database state after a test function?


Suppose I have 3 test functions in my testcase Class. test1 does A before all the asserts statements and test2 does AB and test3 does ABC.

A, B, C all mean some database creations. Based on the mechanism of Django TestCase, for each test function it will create a new database. However, in my case test3 depends on the data state of test2 and test2 depends on the state of test1.

I have several questions:

  1. Is there an elegant way to deal with this kind of test problem? (I know fixtures can be useful. But I want to maintain the data dynamically created in the previous test functions)

  2. I strongly believe unittests should be independent. How do you deal with the inter-relation tests in the layer of database in Django?


Solution

  • Here you are trying to use the previous test cases in order to write your next test case. In such a situation you can define the basic functionality in the setUp() function. Then in the test cases accordingly use the setUp. The setUp function is called at the start of each test case.