Kurt Peek
Kurt Peek

Reputation: 57411

How to use the setUp() method in Python's unittest

I'm trying to run the following script:

import unittest

class RandomDataGeneratorTest(unittest.TestCase):
    def setUp(self):
        import numpy

    def test_numpy_is_imported(self):
        pi = numpy.pi

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

However, I'm getting the following error/failure:

E
======================================================================
ERROR: test_numpy_is_imported (__main__.RandomDataGeneratorTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/kurt/dev/clones/ipercron-compose/controller/random_data_tester.py", line 9, in test_numpy_is_imported
    pi = numpy.pi
NameError: global name 'numpy' is not defined

----------------------------------------------------------------------
Ran 1 test in 0.100s

FAILED (errors=1)

As I understand from https://docs.python.org/2/library/unittest.html#unittest.TestCase.setUp, the setUp() function sould be run before any test function, so I don't see why this error arises?

Upvotes: 2

Views: 1865

Answers (1)

RemcoGerlich
RemcoGerlich

Reputation: 31250

You are importing within a function, so the imported name only exists there.

Try with setting something, e.g. self.test = "somestring", and assert that it is set in the test method.

Upvotes: 2

Related Questions