限制 pytest 中要执行的测试用例数量

Jay*_*shi 3 python pytest

一点背景

  • 我正在使用 Jenkins 执行我的测试用例,我现在正在使用 Jenkins 进行一些 POC。
  • 而且,就我而言,有 500 多个测试用例,需要一个小时才能执行。
  • 我只想执行一个测试用例,只是为了知道我在执行 Jenkins POC 时没有犯任何错误。

有没有办法限制要执行的测试用例的数量?就像是..

  pytest -vv --limit 1
Run Code Online (Sandbox Code Playgroud)

或者

使用conftest.py?

hoe*_*ing 6

您可以通过多种方式限制测试数量。例如,您可以通过将其全名作为参数传递来执行单个测试:

$ pytest tests/test_spam.py::TestEggs::test_bacon
Run Code Online (Sandbox Code Playgroud)

将仅运行module 中test_bacon类中的测试方法。TestEggstests/test_spam.py

如果您不知道确切的测试名称,可以通过执行来找到它

$ pytest --collect-only -q
Run Code Online (Sandbox Code Playgroud)

您可以组合这两个命令来执行有限数量的测试:

$ pytest -q --collect-only 2>&1 | head -n N | xargs pytest -sv
Run Code Online (Sandbox Code Playgroud)

将执行第一个N收集的测试。

--limit如果您愿意,您也可以自己实现该论证。例子:

def pytest_addoption(parser):
    parser.addoption('--limit', action='store', default=-1, type=int, help='tests limit')


def pytest_collection_modifyitems(session, config, items):
    limit = config.getoption('--limit')
    if limit >= 0:
        items[:] = items[:limit]
Run Code Online (Sandbox Code Playgroud)

现在上面的命令变得等于

$ pytest --limit N
Run Code Online (Sandbox Code Playgroud)