Last Updated: February 25, 2016
·
208
· lukeaus

Be careful with test names in Python

A quick note to say that lazy copying can get you in trouble. Make sure all your test names are different in the same test class otherwise each test won't be reported independently.

from unit test import TestCase


class TestFoo(TestCase):

    def test_somethingA(self):
        self.assertEqual(1, 2)

    def test_somethingB(self):
        self.assertEqual(1, 3)

    def test_somethingA(self):
        self.assertEqual(1, 4)

Python will only report that you have 2 failing tests, even though there are 3 failing tests, as the name test_somethingA is repeated twice (even though the test code itself is actually different).

As @owais correctly points out, this happens if you redefine a class method within the one class, or even if you redefine a function within the same module.

Its especially important to keep a lookout for when testing as repeating tests with minor changes tends to be a frequent occurrence when writing unit tests and also system/integration tests.

2 Responses
Add your response

It has got nothing to do with django. You are simply overwriting test_somethingA by declaring it again in the same class. When you add another method with the same name to the same class, the previous one is overwritten and stop existing. It is the same as doing so outside a class.

over 1 year ago ·

@owais Indeed! I updated the post as per your comments. Thanks.

over 1 year ago ·