codyc4321
codyc4321

Reputation: 9682

what is the order of setUp/tearDown in python unit tests?

I have a discrepancy in understand of the basic unittest methods in python. Given this test file below:

import unittest, sys


class TestStringMethods(unittest.TestCase):

    def setUp(self):
        self.mystring = "example string"

    def tearDown(self):
        del self.mystring

    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())

    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        with self.assertRaises(TypeError):
            s.split(2)

My understanding based on what I've read ("Methods named setUp in a TestCase are run, automatically, before every test method.", http://gettingstartedwithdjango.com/en/lessons/testing-microblog/#toc1, etc) I interpret the order of events like:

1. set up self.mystring
2. run test_upper
3. tear down self.mystring

4. set up self.mystring
5. run test_isupper
6. tear down self.mystring

7. set up self.mystring
8. run test_split
9. tear down self.mystring

My co-workers interpret the docs as saying unittest works as follows:

1. set up self.mystring
2. run test_upper
3. run test_isupper
4. run test_split
5. tear down self.mystring

this is a pretty important distinction, which one is right?

Upvotes: 3

Views: 3138

Answers (3)

Sean Pradhan
Sean Pradhan

Reputation: 101

Python Unittest Docs

You are right about setUp and tearDown, they run before and after each test method within that class. But your co-workers may have been thinking of setUpClass and tearDownClass, those would run once before any test methods in the class were executed and after all the test methods were done, respectively.

Upvotes: 4

Ocie Mitchell
Ocie Mitchell

Reputation: 1765

the methods setUpClass/tearDownClass can be used if you need to set up something once before all cases and tear it down after all cases. Most of the time though, you want the behavior you described so that the unit tests do not interfere with one another or depend on one another.

Upvotes: 2

Bill the Lizard
Bill the Lizard

Reputation: 405995

You're right. The setup and teardown methods are run before and after each test case. This ensures that each test is run in isolation, so the order of tests doesn't matter. Objects created during setup that are changed during one test are re-created for each test, so the tests don't effect each other.

Upvotes: 4

Related Questions