4

I'm having problems with pytest not including my projects rootdir in sys.path list. Instead it is including the directory where the tests are located by default.

Here is my project structure.

proj/
  setup.py
  mypackage/
    __init__.py
    a.py
    tests/
      test_a.py

when running pytest with

py.test proj/mypackage/tests

it inserts proj/mypackage/tests into sys.path which is not good because now I cannot import a since its not relative to the tests directory.

I've noticed that py.test detects a rootdir, this is recognized as the root of my project which is the proj directory. This is what I want in sys.path during tests so all my code is relative to that directory. How do I ensure py.test includes (...)/proj/ in sys.path so that I can import mypackage.a in test_a.py.

jack sexton
  • 1,227
  • 1
  • 9
  • 28

1 Answers1

5

I use a conftest.py that appends the package path (relative to the conftest.py file) to sys.path so the package can be imported. Something like this:

# contents of conftest.py
import sys
from os.path import abspath, dirname
package_path = abspath(dirname(dirname(__file__)))
sys.path.insert(0, package_path)

You would then put this file in the tests directory. The conftest.py file will get run before any thing else by default, so the other tests will be able to import mypackage.

Another, probably better, approach is to add a setup.py and follow the advice given here.

stason
  • 5,409
  • 4
  • 34
  • 48
derchambers
  • 904
  • 13
  • 19