Search code examples
djangounit-testingdjango-rest-frameworkdjango-unittest

Django DRF APITestCase chain test cases


For example I want to write several tests cases like this

class Test(APITestCase):
    def setUp(self):
        ....some payloads

    def test_create_user(self):
        ....create the object using payload from setUp

    def test_update_user(self):
        ....update the object created in above test case

In the example above, the test_update_user failed because let's say cannot find the user object. Therefore, for that test case to work, I have to create the user instead test_update_user again.

One possible solution, I found is to run create user in setUp. However, I would like to know if there is a way to chain test cases to run one after another without deleting the object created from previous test case.


Solution

  • Rest framework tests include helper classes that extend Django's existing test framework and improve support for making API requests. Therefore all tests for DRF calls are executed with Django's built in test framework.

    An important principle of unit-testing is that each test should be independent of all others. If in your case the code in test_create_user must come before test_update_user, then you could combine both into one test:

    def test_create_and_update_user(self):
            ....create and update user
    

    Tests in Django are executed in a parallell manner to minimize the time it takes to run all tests. As you said above if you want to share code between tests one has to set it up in the setUp method

    def setUp(self):
        pass