Search code examples
djangodjango-testing

setUp function being called multiple times in django TestCase


I am using django unit tests for the first time. Following is a sized down version of my code.

My assumption was that setUp function would be called once for each TestCase class. But when I run the python manage.py test command, setUp function is called once for each of the test function.

Am I doing something wrong or is there something wrong in my assumption?

class SampleTest(TestCase):
    """
        This class assumes an archiver setup with
            add available at localhost:9101
            query available at localhost:9105
    """

    def __init__(self, *args, **kwargs):
        self.init_var = False
        super(SampleTest, self).__init__(*args, **kwargs)

    def setUp(self):
        """"""
        print "setup called"
        self.init_var = True


    def test_1(self):
        print "Test 1", self.init_var

    def test_2(self):
        print "Test 2", self.init_var

Solution

  • Yes, your assumption is wrong. Each test inside a test case should be independent; so setUp (and tearDown) is called once for each of them.

    If you really need something to be only done once for the whole class, use setUpClass; but note that you shouldn't be doing things like setting up data there.