Dark Light
Dark Light

Reputation: 1250

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

Upvotes: 2

Views: 3642

Answers (3)

Dadou
Dadou

Reputation: 195

This is because setUp is called each time a test case is called. If you want to call it only one time, you have to use setUpClass with the @classmethod decorator, like following:

class SampleTest(TestCase):

    @classmethod
    def setUpClass(cls):
        super(SampleTest, cls).setUpClass()
        # your code

Upvotes: 5

Josh
Josh

Reputation: 13516

I've always been a little frustrated with this myself. There is often set up that needs to be done that all tests will rely on. If you're modifying the data that you created during that setup, though, you could really mess yourself up. If you're absolutely certain this is what you want to do, you can use the following as a base class instead of the standard Test Case. Then, instead of using setUp to set up the test, use either before_running_all_tests or before_running_each_test depending on what you need to do.

class TestCasePlus(TestCase):
    _one_time_setup_complete = False

    def before_running_all_tests(self):
        pass

    def before_running_each_test(self):
        pass

    def setUp(self):
        if not self._one_time_setup_complete:
            self.before_running_all_tests()
        self.before_running_each_test()

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599698

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.

Upvotes: 2

Related Questions