如何在pytest下测试单个文件

189
您如何在pytest中测试单个文件?我只找到了忽略选项,但文档中没有“仅测试此文件”选项。
最好使用命令行运行而不是setup.cfg,因为我想在IDE中运行不同的文件测试。整个套件太慢了。
3个回答

229
< p >只需使用文件路径运行< code >pytest< p >类似于以下形式
pytest tests/test_file.py

使用::语法在测试文件中运行特定的测试:

pytest test_mod.py::test_func

在这里,test_func可以是一个测试方法或类(例如:pytest test_mod.py::TestClass)。

了解更多方法和细节,请参阅文档中的"指定要运行的测试"


5
好的,这似乎就是Pycharm正在做的事情,但它仍在运行整个测试套件。在命令行上运行py.test会出现段错误的原因。我想这超出了最初问题的范围,所以如果我能让它正常工作,我将接受你的答案。 - simonzack
7
显然,如果在setup.cfg中加入路径,addopts会出现问题。 - simonzack
1
@simonzack,我猜你想从文件中运行一个单独的测试用例。 试试这个命令:py.test test_basic.py -k test_first 其中test_first是在我的test_basic.py文件中存在的一个测试用例。 - Anurag Sinha
使用::语法在测试文件中运行单个测试,例如:pytest tests/test_models.py::TestMyModelTestMyModel是包含一部分测试的类。 - FisNaN

106

这很简单:

$ pytest -v /path/to/test_file.py

-v 标记用于增加详细程度。如果您想在该文件中运行特定测试:

$ pytest -v /path/to/test_file.py::test_name

如果您想运行名称符合特定模式的测试,则可以使用:

$ pytest -v -k "pattern_one or pattern_two" /path/to/test_file.py

您还可以选择标记测试,因此可以使用-m标志运行一组已标记的测试。

test_file.py

def test_number_one():
    """Docstring"""
    assert 1 == 1


@pytest.mark.run_these_please
def test_number_two():
    """Docstring"""
    assert [1] == [1]

运行标记为run_these_please的测试:

$ pytest -v -m run_these_please /path/to/test_file.py

3
对于path/to/test.py::test_method,我得到了错误信息:
ERROR: 找不到:/home/namgivu/NN/code/myproject/tests/models/test_bill.py::test_generate_for_today_normal_cycle (在任何一个[<Module 'tests/models/test_bill.py'>]中都没有名为'/home/namgivu/NN/code/myproject/tests/models/test_bill.py::test_generate_for_today_normal_cycle'的名称)。
- Nam G VU
1
参数化测试怎么办,带有ID? -k my_test[a test id here] 无法工作,到目前为止我最好的解决方法是 -k "my_test and a and test and id and here" 这几乎不是一个友好的格式。 - Paul D Smith
1
这个例子中给出的示例(特别是混合路径和节点选择语法的示例)应该被添加到pytest文档中,因为在我看来它并不明显。 - cjauvin

27

这对我有用:

python -m pytest -k some_test_file.py

这也适用于单个测试函数:

python -m pytest -k test_about_something

1
这个 pytest directory_to_tests/some_test_file.py 对我来说不起作用。我使用的是Windows Python 3.8.2和Pytest 6.0.1。 - minghua
4
我建议不要使用“-k”选项,因为pytest会尝试搜索该函数。假设你的项目中有10000个测试,最好只指定路径和函数名称,例如“pytest path/path/.../path.py::function_name”。请注意保持翻译内容的原意并使其更加通俗易懂。 - alexzander

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接