mardi 25 août 2015

A DRY way or writing similar unit tests in python

I have some similar unit tests in python. There are so similar that only one argument is changing.

class TestProcessCreateAgencyOfferAndDispatch(TestCase):
    def test_typeA(self):
        self.assertTrue(foo(bar=TYPE_A))

    def test_typeB(self):
        self.assertTrue(foo(bar=TYPE_B))

    def test_typeC(self):
        self.assertTrue(foo(bar=TYPE_C))

    ...

Obviously this is not very DRY, and if you have even 4-5 different options the code is going to be very repetitive

Now I could do something like this

class TestProcessCreateAgencyOfferAndDispatch(TestCase):
    BAR_TYPES = (
        TYPE_A,
        TYPE_B,
        TYPE_C,
        ...
    )

    def _foo_test(self, bar_type):
        self.assertTrue(foo(bar=bar_type))

    def test_foo_bar_type(self):
        for bar_type in BAR_TYPES:
            _foo_test(bar=bar_type))

Which works, however when an exception gets raised, how will I know whether _foo_test failed with argument TYPE_A, TYPE_B or TYPE_C ?

Perhaps there is a better way of structuring these very similar tests?

Aucun commentaire:

Enregistrer un commentaire