假设我正在编写一个测试。显然它正在测试我的应用程序,所以我需要以某种方式将应用程序包导入到测试脚本中。目录结构是这样的:
root/
app/
__init__.py
somemodule.py
tests/
my_test.py
然后我像这样运行测试:
cd tests
py.test # runs all the tests in the current directory
问题是:我应该如何在我的测试模块中导入应用程序模块?
在 my_test.py 中,我尝试执行 from .. import app。这给我一个错误 Parent module '' not loaded, cannot perform relative import.
完成此任务的标准方法是什么?
编辑:请注意,我编辑了问题以专门引用 py.test 工具。
请您参考如下方法:
您应该能够通过正确配置 py.test 使其运行。
将您的模块添加到您的 app/__init__.py 下一行
from .somemodule import MyClass # or whatever ur class is called
在您的主 文件夹中创建一个名为conftest.py 的文件。您可以将其留空,但 py.test 使用它来查找项目路径。在里面你可以运行一些 py.test 初始化,比如添加 fixtures .
在您的 my_test.py 中,您现在可以调用
from app import MyClass
现在您终于可以从您的主文件夹:
py.test tests/test.py
这对我有用。我认为 py.test 有一种包含模块的方法,因为没有它你可能无法实现相同的目的。至少如果我不使用 py.test,我会坚持修改我的 PYTHONPATH 以指向我的应用程序路径。
编辑:
只是为了澄清 py.test 操纵测试 session 的 sys.path 以包含根目录。 Py.test 通过使用 conftest.py 文件来识别根路径。然后将根路径添加到系统路径并用于测试。
你确实能跑:
py.test tests/test.py
这也行:
cd..
py.test rootTest/tests/test.py
