Home > front end >  django: repeat testcase with different fixtures
django: repeat testcase with different fixtures

Time:12-16

I have a Django TestCase, all of whose tests I'd like to run for two different sets of data (in this case, the Bike object whose colour can be red or blue).

Whether that's through loading different fixtures, or the same fixtures and manipulating the colour, I have no preference.

See below example:

class TestBike(TestCase):
    fixtures = [
        "testfiles/data/blue_bike.json",
    ]

    def setUp(self, *args, **kwargs):
        self.bike = Bike.objects.get(color="blue")

        run_expensive_commands(self.bike)

    def test_bike_1(self):
        # one of many tests

    def test_bike_2(self):
        # second of many tests

One way I considered was using the parameterized package, but then I'd have to parameterize each test, and call a prepare() function from each test. Sounds like a whole lot of redundancy.

Another is to multiple-inherit the test with different fixtures. Also a bit too verbose for my liking.

CodePudding user response:

Did you consider to parameterize on class level, i.e. via class attribute?

class TestBikeBase:
    COLOR = ""  # Override in derived class.

    def setUp(self, *args, **kwargs):
        self.bike = Bike.objects.get(color=self.COLOR)

        run_expensive_commands(self.bike)

    def test_bike_1(self):
        # one of many tests

    def test_bike_2(self):
        # second of many tests


class TestRedBike(TestBikeBase, TestCase):
    COLOR = "red"


class TestBlueBike(TestBikeBase, TestCase):
    COLOR = "blue" 
  • Related