sys.path 包括 py.test rootdir 以使测试相对于项目根目录导入 [英] sys.path including py.test rootdir to make tests import relative to project root

查看:45
本文介绍了sys.path 包括 py.test rootdir 以使测试相对于项目根目录导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 pytest 时遇到问题,未将我的项目 rootdir 包含在 sys.path 列表中.相反,它包括默认情况下测试所在的目录.

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.

这是我的项目结构.

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

使用

py.test proj/mypackage/tests

它将 proj/mypackage/tests 插入到 sys.path 中,这并不好,因为现在我无法导入 a,因为它与测试目录无关.

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.

我注意到 py.test 检测到一个 rootdir,它被识别为我的项目的根目录,即 proj 目录.这是我在测试期间在 sys.path 中想要的,所以我的所有代码都是相对于该目录的.我如何确保 py.test 在 sys.path 中包含 (...)/proj/ 以便我可以在 test_a.py 中import mypackage.a.

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.

推荐答案

我使用 conftest.py 将包路径(相对于 conftest.py 文件)附加到 sys.path 以便可以导入包.像这样:

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)

然后您可以将此文件放在测试目录中.默认情况下,conftest.py 文件将在其他任何事情之前运行,因此其他测试将能够导入 mypackage.

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.

另一种可能更好的方法是添加 setup.py 并遵循给定的建议 这里.

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

这篇关于sys.path 包括 py.test rootdir 以使测试相对于项目根目录导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆