【发布时间】:2014-01-25 03:14:25
【问题描述】:
我有一个项目目录结构如下(我认为这很标准):
my_project
setup.py
mypkg
__init__.py
foo.py
tests
functional
test_f1.py
unit
test_u1.py
我正在使用 py.test 作为我的测试框架,并且我希望能够在 my_project 目录中运行 py.test tests 来运行我的测试。这确实有效,直到我尝试在测试中使用(例如)import mypkg 导入我的应用程序代码。那时,我收到错误“没有名为 mypkg 的模块”。经过一番调查,似乎py.test 使用sys.path 中的测试文件目录运行测试,但不是运行py.test 的目录。
为了解决这个问题,我在我的tests 目录中添加了一个conftest.py 文件,其中包含以下代码:
import sys, os
# Make sure that the application source directory (this directory's parent) is
# on sys.path.
here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, here)
这似乎可行,但它是确保测试看到应用程序代码的好方法吗?有没有更好的方法来实现这一点,还是我在项目结构上做错了什么?
我查看了一些使用py.test(例如pip)的其他项目,但我看不到执行此类操作的代码,但运行py.test tests 似乎在那里工作。我不知道为什么,但我担心他们可能会以更简单的方式获得相同的结果。
我查看了py.test 文档,但我看不到对此问题的解释或推荐的解决方法。
【问题讨论】:
标签: python unit-testing pytest