简体   繁体   中英

Running the same test on different model objects

I have three scenarios in my db that should give the same result when I call an endpoint:

Model1.objects.create(name="a")
assert requests.delete("endpoint?pk=a").response == 204

Model2.objects.create(name="a")
assert requests.delete("endpoint?pk=a").response == 204

Model1.objects.create(name="a")
Model2.objects.create(name="a")
assert requests.delete("endpoint?pk=a").response == 204

So basically the setup() part of the test is different, where I create the model objects, however the test itself is the same in each case. What is the best way to implement this? Can I just create a Base TestCase class which implements assert requests.delete("endpoint?pk=a").response == 204 and then inherit from it three times, creating the models in the setUpTestData() in each of the three classes?

It sounds like a use-case for parameterized testing. The basic idea is that you have a set of assertions you'd like to make about some set of items or objects. You write the test once, then let the parameterized testing logic run the test for each items.

To give a basic sketch in pseudocode, you might do something like:

@parameterized.parameters(['a', 'b', 'c'])
def test_example(test_letter):
    self.assertLen(test_letter, 1)
    self.assertIn(test_letter, {'a', 'b', 'c'})

You can see in this basic sketch that each of the parameters in the parameterized decorator gets passed into the test.

You can likely put your objects as parameters instead and share the core test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM