pytest下如何测试单个文件

How to test single file under pytest

如何在pytest中测试单个文件?我只能在文档中找到忽略选项而没有 "test this file only" 选项。

这最好在命令行而不是 setup.cfg 上工作,因为我想 运行 在 ide 中测试不同的文件。整个套件耗时太长。

只需 运行 pytest 和文件路径

类似

pytest tests/test_file.py

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

pytest test_mod.py::test_func

这里test_func可以是测试方法,也可以是class(例如:pytest test_mod.py::TestClass)。

有关更多方法和详细信息,请参阅文档中的 "Specifying which tests to run"

这很简单:

$ 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

这对我有用:

python -m pytest -k some_test_file.py

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

python -m pytest -k test_about_something