Russ Bateman
Russ Bateman

Reputation: 18643

How do unit tests import the modules they test?

(New to Python, old Java guy.) I have followed the recommendations for Python project set-up (as detailed here: What is the best project structure for a Python application?).

My structure is then:

artman
`-- artman
    +-- artman.py
    +-- util.py
    `-- test
        `-- util_test.py

...and my test code attempts unsuccessfully to import what's inside util.py that it's going to test:

import unittest
import util        # <------ Unresolved import: util

class UtilTest( unittest.TestCase ):
    def testLookForArtmanRoot( self ):
        util.lookForArtmanRoot( "." )

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()

I'm sure this is a simple, newbie Python mistake, but despite Googling I don't know if I must amend PYTHONPATH or employ some other solution.

Upvotes: 2

Views: 203

Answers (1)

unutbu
unutbu

Reputation: 879421

Although it is not strictly necessary, I would disambiguate the directory/package/module structure so as you learn, the purpose of every step will be clear.

artman_dir
`-- artman_pkg
    +-- __init__.py
    +-- artman.py
    +-- util.py
    +-- test
        `-- util_test.py
  • Add artman_dir to your PYTHONPATH.
  • Add an empty file called __init__.py to artman_pkg.

These two steps together allow you to

import artman_pkg

from any python script.

Then you can import util in util_test.py using an absolute import:

import artman_pkg.util as util

and the rest of the code can remain unchanged.

Upvotes: 3

Related Questions