1

What is best-practice for importing classes or functions to into a unittest test module?

Suppose, I've the following common package in my project root, and I'd like to test common/utils.py in common/tests/test_utils.py:

common
├── __init__.py
├── tests
│   ├── __init__.py
│   └── test_utils.py
└── utils.py

Should I import classes or functions at the top-level of the test module, or inside the the individual test cases (see below)?

import unittest


class TestUtils(unittest.TestCase):

    def test_object_factory(self):
        from ..utils import object_factory
        object_factory = _(foo=1, bar='bar', baz={'a': 1, 'b': (2, 3)})
        self.assertTrue(hasattr(o, 'foo'))
        self.assertEqual(o.foo, 1)
        self.assertTrue(hasattr(o, 'bar'))
        self.assertEqual(o.bar, 'bar')
        self.assertTrue(hasattr(o, 'baz'))
        self.assertEqual(o.baz, {'a': 1, 'b': (2, 3)})
hoefling
  • 59,418
  • 12
  • 147
  • 194
Shuzheng
  • 11,288
  • 20
  • 88
  • 186
  • I would say absolute imports are usually the better way, and this case is no different - see the more general [question about absolute vs relative imports](https://stackoverflow.com/questions/4209641/absolute-vs-explicit-relative-import-of-python-module). – MrBean Bremen May 27 '20 at 11:59
  • What do you mens by absolute import? I have to import relative to the `tests` package using `..`? – Shuzheng May 27 '20 at 12:45
  • Absolute import would be `from common.utils import ...`, or `from project.common.utils import ...`, depending on your project root, relative is what you do (`from ..utils import ...`). I thought your question was related to this, maybe I misunderstood? – MrBean Bremen May 27 '20 at 13:50
  • @MrBeanBremen - I wanted to know whether it’s good practice to place the import inside the test case `test_object_factory` or outside at the top-level. – Shuzheng May 27 '20 at 18:02
  • Ah, you mean local vs global import - sorry, I got this wrong. Generally, I would always [prefer global imports](https://stackoverflow.com/questions/9614051/import-at-module-level-or-at-function-level), the same goes for test code. Local imports are sometimes needed to avoid cyclic references or side effects, but apart from that I would not use them. – MrBean Bremen May 27 '20 at 18:13

0 Answers0