Python 如何在pytest下测试单个文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34833327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:35:13  来源:igfitidea点击:

How to test single file under pytest

pythonpytest

提问by simonzack

How do you test a single file in pytest? I could only find ignore options and no "test this file only" option in the docs.

你如何在pytest中测试单个文件?我只能在文档中找到忽略选项,而没有“仅测试此文件”选项。

Preferably this would work on the command line instead of setup.cfg, as I would like to run different file tests in the ide. The entire suite takes too long.

最好这可以在命令行而不是setup.cfg,因为我想在 ide 中运行不同的文件测试。整个套房时间太长了。

采纳答案by Bryant

simply run pytestwith the path to the file

只需pytest使用文件路径运行

something like

就像是

pytest tests/unit/some_test_file.py

pytest tests/unit/some_test_file.py

回答by lmiguelvargasf

This is pretty simple:

这很简单:

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

The -vflag is to increase verbosity. If you want to run a specific test within that file:

-v标志是增加冗长。如果要在该文件中运行特定测试:

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

If you want to run test which names follow a patter you can use:

如果要运行测试哪些名称遵循模式,可以使用:

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

You also have the option of marking tests, so you can use the -mflag to run a subset of marked tests.

您还可以选择标记测试,因此您可以使用该-m标志来运行标记测试的子集。

test_file.py

测试文件.py

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


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

To run test marked with run_these_please:

运行带有标记的测试run_these_please

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

回答by JonDoe297

This worked for me:

这对我有用:

python -m pytest -k some_test_file.py

This works for individual test functions too:

这也适用于单个测试功能:

python -m pytest -k test_about_something