1

I have to write a test file like this:

import unittest

from mylibrary import some_crazy_func

class TestSomething(unittest.TestCase):
    def test_some_crazy_func_that_needs_io_open(self):
        # Opens file
        # Calls function
        # assert outputs

But I'm unsure where is the "pythonic location" where I should import the library (let's say io).

Should it be at the top:

import io
import unittest

from mylibrary import some_crazy_func

class TestSomething(unittest.TestCase):
    def test_some_crazy_func_that_needs_io_open(self):
         expected = ['abc', 'def', 'xyz']
         with io.open('somestaticfile.txt', 'r') as fin:
             outputs = [some_crazy_func(line) for line in fin]
         assert outputs == expected

Or within the TestCase's function:

import unittest

from mylibrary import some_crazy_func

class TestSomething(unittest.TestCase):
    def test_some_crazy_func_that_needs_io_open(self):
         import io
         expected = ['abc', 'def', 'xyz']
         with io.open('somestaticfile.txt', 'r') as fin:
             outputs = [some_crazy_func(line) for line in fin]
         assert outputs == expected

Or is it before the TestCase function and at the object initialization:

import unittest

from mylibrary import some_crazy_func

class TestSomething(unittest.TestCase):
    import io
    def test_some_crazy_func_that_needs_io_open(self):
         expected = ['abc', 'def', 'xyz']
         with io.open('somestaticfile.txt', 'r') as fin:
             outputs = [some_crazy_func(line) for line in fin]
         assert outputs == expected
alvas
  • 115,346
  • 109
  • 446
  • 738
  • I can't say this is the best way, but I asked a similar question years ago and this how I went about importing for unit testing http://stackoverflow.com/questions/34689852/is-this-a-proper-way-to-test-stdout-with-python-3-unittest – tsumnia Oct 26 '16 at 02:47
  • That is, if the import is dependent on a specific test case, importlib might be the route you'd like to take – tsumnia Oct 26 '16 at 02:49

1 Answers1

0

See PEP8: https://www.python.org/dev/peps/pep-0008/#id23

It states,

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

coder.in.me
  • 1,048
  • 9
  • 19
  • Even in unittests? Imagine how loaded the `sys.path` would be if test is huge. – alvas Oct 26 '16 at 02:36
  • I always wondered the rationale for this PEP8 guideline. In your example at least, testing modules are separated from functional modules. So it doesn't matter if you put it on top of file or elsewhere. – coder.in.me Oct 26 '16 at 02:46