默认跳过测试,除非 py.test 中存在命令行参数

Default skip test unless command line parameter present in py.test

我有一个很长的 运行 测试,持续 2 天,我不想将其包括在常规测试中 运行。我也不想键入命令行参数,那样会在每个常规测试 运行 中取消 select 它和其他测试。当我真正需要它时,我更愿意 select 默认 deselected 测试。我尝试将测试从 test_longrun 重命名为 longrun 并使用命令

py.test mytests.py::longrun

但这不起作用。

尝试将您的测试装饰成 @pytest.mark.longrun

在你的conftest.py

def pytest_addoption(parser):
    parser.addoption('--longrun', action='store_true', dest="longrun",
                 default=False, help="enable longrundecorated tests")

def pytest_configure(config):
    if not config.option.longrun:
        setattr(config.option, 'markexpr', 'not longrun')

除了上面的 pytest_configure 解决方案,我找到了 pytest.mark.skipif

您需要将 pytest_addoption() 放入 conftest.py

def pytest_addoption(parser):
    parser.addoption('--longrun', action='store_true', dest="longrun",
                 default=False, help="enable longrundecorated tests")

而你在测试文件中使用skipif

import pytest

longrun = pytest.mark.skipif("not config.getoption('longrun')")

def test_usual(request):
    assert False, 'usual test failed'

@longrun
def test_longrun(request):
    assert False, 'longrun failed'

在命令行中

py.test

不会执行test_longrun(),但是

py.test --longrun

也会执行test_longrun().

这种方式略有不同。

@pytest.mark.longrun装饰你的测试:

@pytest.mark.longrun
def test_something():
    ...

此时您可以 运行 除了使用 -m 'not longrun'

标记的测试之外的所有内容
$ pytest -m 'not longrun'

或者如果您只想 运行 longrun 标记的测试,

$ pytest -m 'longrun'

但是,要使 -m 'not longrun' 默认 ,在 pytest.ini 中,将其添加到 addopts:

[pytest]
addopts =  
    -m 'not longrun'
    ...

如果你想运行所有的测试,你可以做

$ pytest -m 'longrun or not longrun'