DeltaIV
DeltaIV

Reputation: 5646

Writing unit tests: can I import all modules I need just once at class level, or do I have to import them again in each test?

I'm trying to write unit tests for some code using unittest:

https://docs.python.org/3/library/unittest.html

Suppose that each of the tests I'm writing needs to import the math, os and datetime module. Right now I'm importing them in each of the tests I'm writing:

#...code for which I'm writing the unit tests...
import unittest

class TestMyCode(unittest.TestCase):

    def test_method_1(self):
        # unit test for method 1
        import math
        import os
        import datetime
        .
        .

    def test_method_2(self):
        # unit test for method 2
        import math
        import os
        import datetime
        .
        .

if __name__ == "__main__":
    unittest.main()

To avoid code duplication, isn't it possible to just import them once at class level? This:

#...code for which I'm writing the unit tests...
import unittest

class TestMyCode(unittest.TestCase):

    import math
    import os
    import datetime

    def test_method_1(self):
        # unit test for method 1
        .
        .

    def test_method_2(self):
        # unit test for method 2
        .
        .

if __name__ == "__main__":
    unittest.main()

results in the error

NameError: name 'math' is not defined

So it's clearly not the right approach.

EDIT just for clarity, both the code for which I'm writing the unit tests (which is composed of just two methods, actually) and the (two) unit tests are in the same module, let's call it MyCode.py.

Upvotes: 0

Views: 833

Answers (1)

portusato
portusato

Reputation: 46

Given that the duplicated code you want to get rid of consists of imports, I completely agree with BrenBarn's response, because you don't need to import a module multiple times. For the general case where you want to run the same code before or after every test in a class you should use the setUp() and tearDown() methods of class unittest.TestCase.

Upvotes: 1

Related Questions