pytest如何找到要测试的文件?

How does pytest find files to test?

我知道 py.test 如何发现对 运行 的测试,但我不知道如何使测试引用包含要测试的代码的文件。

我的项目是这样的:

arith.py
tests/
    test_airth.py

在我的项目根目录中,我有文件 arith.py

def plus(x, y):
    return x + y

在文件tests/test_arith.py中我有

import arith
def test_plus():
    assert arith.plus(3, 5) == 8

当我运行,在项目根目录下,

pytest

它发现了我的测试文件,因为我遵循了测试发现规则。但是 pytest 回复

ImportError while importing test module tests/test_arith.py'

我运行 pytest来自项目根目录,为什么它不喜欢我的导入?它想在 tests 目录中找到我正在测试的文件!

如何正确设置导入,以便我在 tests/ 目录中的测试文件可以看到项目根目录中的被测文件? (pytest 文档中的示例似乎没有做任何特别的事情......也许测试与被测文件位于同一目录中?他们非常详细地描述了测试发现,但我一定错过了如何设置测试所以他们可以看到他们正在测试的代码。)

假设您有这样的布局(我就是这样做的):

.
├── myprogram
│   ├── __init__.py
│   ├── core.py
│   └── db.py
├── setup.py
└── tests
    ├── test_core.py
    └── test_db.py

你应该像这样调用 pytest:

py.test tests

我相当确定那是测试目录的 absolute/relative 路径。这也假设您已经在根目录中完成了类似 python -m pip install -e . 的操作。你在那里也有一个 .git.hg 文件夹:)

It's a little strange so much is needed. Surely there is a better way?

实际上最好的方法。我认为声明分发 Python 应用程序的最佳方式是作为 Python 包,最好是 wheel 没有争议。为此,您可能需要 setup.py.

通过安装您的包(最好在 venv/virtualenv 沙箱中),您可以确保您知道 install/run 您的 需要哪些包。如果您的包已安装,则意味着任何执行 import myprogram 的脚本(使用我的示例布局)都将能够导入您的包。这就是您将在测试套件中执行的操作。

那么你的测试发现就像告诉 pytest 在哪里找到它一样简单。