繁体   English   中英

如何在 pytest 中仅运行未标记的测试

[英]How to run only unmarked tests in pytest

我的 python 测试代码中有几个标记:

@pytest.mark.slowtest
@pytest.mark.webtest
@pytest.mark.stagingtest

我可以使用例如pytest -m slowtest有选择地使用标记运行测试

如何在不求助于pytest -m "not (slowtest or webtest or stagingtest)"情况下运行未标记的测试?

您可以想象,我们将来可能会使用其他标记......

我发现另一个有用的选项是使用pytest.ini添加默认选项。 我们明确地写出要跳过的标记。 它需要对 pytest.ini 中跳过的标记列表进行pytest.ini 换句话说,不是 OP 要求的 100%,但这是我在寻找默认标记时发现的最好的 SO 问题。 希望这可以帮助其他人。

文档


addopts

    Add the specified OPTS to the set of command line arguments as if they had been specified by the user. Example: if you have this ini file content:

    # content of pytest.ini
    [pytest]
    addopts = --maxfail=2 -rf  # exit after 2 failures, report fail info

    issuing pytest test_hello.py actually means:

    pytest --maxfail=2 -rf test_hello.py

    Default is to add no options.

我添加到我的 pytest.ini 中的内容

[pytest]
addopts = -m "not slow"
markers =
    slow: marks tests as slow (deselect with '-m "not slow"')

使用它

﮸$ grep 'mark.slow' tests/*.py | wc -l
3

$ pytest -s
======================================================= test session starts ========================================================
platform linux -- Python 3.8.2, pytest-6.0.1, py-1.9.0, pluggy-0.13.1
rootdir: /tests, configfile: pytest.ini
collected 66 items / 3 deselected / 63 selected                                                                                    

../tests/test_app.py ...............................................................

================================================= 63 passed, 3 deselected in 8.70s =================================================

您可以在顶级 conftest.py 中使用以下代码片段。

def pytest_runtest_setup(item):
    envmarker = item.get_marker()
    if envmarker:
        pytest.skip("Skipping as the test has a marker")

请记住,参数化也是一个标记。 如果您正在使用参数化,您可以在 envmarker 中检查并有条件地跳过。

pytest-unmarked 插件旨在实现这一点。

PyPi 与项目主页的链接已损坏。 这是正确的链接https://github.com/alyssabarela/pytest-unmarked

有关使用插件的更多信息,请访问https://docs.pytest.org/en/latest/plugins.html

将以下内容添加到您的 conftest 将通过向所有未标记的测试添加特定标记来为您解决此问题,这样您就可以运行类似pytest -m unmarked

def pytest_collection_modifyitems(items, config):
    for item in items:
        if not any(item.iter_markers()):
            item.add_marker("unmarked")

这比 pytest-unmarked 的优势在于您仍然可以指定其他标记,例如pytest -m 'webtest or unmarked' pytest-unmarked 看起来也没有维护并发出警告。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM