使用 py.test 时,如何使应用程序包可用于测试?

How can I make the application package available to the tests, when using py.test?

假设我正在编写测试。显然它正在测试我的应用程序,所以我需要以某种方式将应用程序包导入到测试脚本中。目录结构是这样的:

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

在您的 main 文件夹中创建一个名为 conftest.py 的文件。您可以将其留空,但 py.test 使用它来查找项目路径。在里面你可以 运行 一些 py.test 初始化,比如添加 fixtures.

在您的 my_test.py 中,您现在可以调用

from app import MyClass

现在,您终于可以从 main 文件夹中:

py.test tests/test.py

这对我有用。我认为 py.test 有一种包含模块的方法,因为没有它你可能无法实现相同的目的。至少如果我不使用 py.test 我会坚持修改我的 PYTHONPATH 以指向我的应用程序路径。

编辑:

只是为了澄清 py.test 操纵了测试会话的 sys.path 以包含根目录。 Py.test 使用 conftest.py 文件识别根路径。然后将根路径添加到系统路径并用于测试。

你确实可以运行:

py.test tests/test.py

这也行得通:

cd..
py.test rootTest/tests/test.py