默认情况下排除某些测试

2024-04-29 21:26:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望配置pytest,使其在默认情况下排除一些测试;但是,通过一些命令行选项可以很容易地再次包含它们。我只找到了-k,我的印象是这允许复杂的规范,但不确定如何满足我的特定需求

排除应该是源文件或配置文件的一部分(它是永久性的——考虑一下长时间运行的测试,这些测试应该只作为有意识的选择包括在内,当然永远不会包含在构建管道中……)

附加问题:如果不可能,我将如何使用-k排除特定测试?同样,我在文档中看到了关于使用not作为关键字的提示,但这似乎对我不起作用。也就是说,-k "not longrunning"给出了一个关于无法找到文件“notrunning”的错误,但没有排除任何内容


Tags: 文件命令行文档规范管道pytest配置文件选项
3条回答

目标:默认情况下跳过标记为@pytest.mark.integration的测试

conftest.py

import pytest

# function executed right after test items collected but before test run
def pytest_collection_modifyitems(config, items):
    if not config.getoption('-m'):
        skip_me = pytest.mark.skip(reason="use `-m integration` to run this test")
        for item in items:
            if "integration" in item.keywords:
                item.add_marker(skip_me)

pytest.ini

[pytest]
markers =
    integration: integration test that requires environment

现在,除非使用

pytest -m integration

您可以使用pytest标记一些测试,并使用-k arg跳过或包含它们

例如,考虑以下测试,

import pytest

def test_a():
    assert True

@pytest.mark.never_run
def test_b():
    assert True


def test_c():
    assert True
    
@pytest.mark.never_run
def test_d():
    assert True

您可以像这样运行pytest来运行所有测试

pytest

要跳过标记的测试,可以像这样运行pytest

pytest -m "not never_run"

如果要单独运行标记的测试

pytest -m "never_run"

我过去所做的是为这些测试创建自定义标记,这样我就可以使用运行测试的-m命令行标志排除它们。例如,在pytest.ini文件中放置以下内容:

[pytest]
markers =
    longrunning: marks a test as longrunning

然后我们只需要用这个标记来标记长期运行的测试

@pytest.mark.longrunning
def test_my_long_test():
    time.sleep(100000)

然后,当我们运行测试时,我们将执行pytest -m "not longrunning" tests/以排除它们,并pytest tests以按预期运行所有内容

相关问题 更多 >