sys.path including py.test rootdir to make tests import relative to project root

做~自己de王妃 提交于 2020-01-03 15:36:02

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/37282297/sys-path-including-py-test-rootdir-to-make-tests-import-relative-to-project-root

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!