[Django]-Inherinting Django SetUpTestData method called for each child

2👍

As you have stated yourself and @brian-destura pointed out as well, your best option to share data between test classes would be implementing your own test runner.

The runner should inherit from django.test.runner.DiscoverRunner.
In that runner, you could override setup_test_environment() (docs) or setup_databases() (docs) depending on your needs.

👤finngu

0👍

Finngu’s suggestion absolutely works. However – a big reason to split tests is to make them run in individual DB transactions. By sharing the database setup you’re somewhat defeating the point.

To make independent tests that share a DB setup, you can just use subTest.

from django.test import TestCase
 

class TestSubTests(ParentClass):
    @classmethod
    def setUpTestData(cls):
        super(TestChild1, cls).setUpTestData()
        cls.parent_attr = "parent value"

    def test_subtests(self):
        
        with self.subTest("The first value"):
            child_attr = "child value 1"
            self.assertEqual(self.parent_attr, "parent value")
            self.assertEqual(self.child_attr, "child value 1")
 
        with self.subTest("The second value"):
            child_attr = "child value 2"
            self.assertEqual(self.parent_attr, "parent value")
            self.assertEqual(self.child_attr, "child value 2")

These subtests run independently – that means the test continues running if one subtest fails. This vs. the custom test runner is a decision that will boil down to details, but subtests are effective and sufficient in most cases. Read more on them i.e.: here.

Leave a comment