Search code examples
djangounit-testingabstract-classtestcase

Stop abstract django.test TestCase class from running test also


I am creating Django unit tests, and have some very similar models with repeated functionality. There are some differences however, so I created an abstract BaseTestCase class that other TestCase classes inherit from. It seems to be working fine except for the fact that when the TestCases that inherit from the BaseTestCase class are done running their tests, Django will still try to run the BaseTestCase classes tests as well. Shouldn't Django not want to run the tests on the abstract BaseTestCase? Is there some type of configuration I'm missing to ensure this doesn't happen?

Test Case Layout

class BaseTestCase(SetupTestCase):
    api = ""

    def test_obj_list(self):
        response = self.client.get(self.api)

        self.assertTrue(response.status_code == 200)

    def test_obj_create(self):
        pass

    def test_obj_retrieve(self):
        pass

    def test_obj_update(self):
        pass

    def test_obj_delete(self):
        pass

    class Meta:
        abstract = True

class ChildTestCaseOne(BaseTestCase):
    api = "/api/v0.1/path_one/"

class ChildTestCaseTwo(BaseTestCase):
    api = "/api/v0.1/path_two/"

class ChildTestCaseThree(BaseTestCase):
    api = "/api/v0.1/path_three/"

class ChildTestCaseFour(BaseTestCase):
    api = "/api/v0.1/path_four/"

class ChildTestCaseFive(BaseTestCase):
    api = "/api/v0.1/path_five/"

This should run 25 Tests, five tests for five test cases, but it runs 30. After it runs the 5 tests for each child class, it runs the 5 tests for the base test case as well.


Solution

  • What about multiple inheritance?

    from django.test import TestCase
    
    class BaseTestCase:
        # ...
    
    class ChildTestCaseN(BaseTestCase, TestCase):
        # ...
    

    I couldn't find anything about abstract test cases in Django. Where did you get that SetupTestCase class from?