pytest支持“默认”标记吗?

2024-09-28 05:21:02 发布

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

我使用pytest测试嵌入式系统的python模型。要测试的功能因平台而异。(我在这里使用的“平台”是指嵌入式系统类型,而不是操作系统类型)。在

组织测试的最直接的方法是根据平台类型将它们分配到目录中。在

/platform1
/platform2
/etc.

pytest/平台1

这很快就变得很难支持,因为许多功能跨平台重叠。我把我的测试移到一个目录中,每个功能区的测试都分配给一个文件名(test_功能性a.py例如)。 然后我使用pytest标记来指示文件中的哪些测试应用于给定的平台。在

^{pr2}$

虽然我喜欢让'conftest'自动检测平台类型并只运行适当的测试,但我已经让自己指定在命令行上运行哪些测试。在

pytest-m“(平台1或所有平台)”

问题:(终于!)在

有没有一种方法可以简化事情,让pytest在默认情况下运行所有未标记的测试,以及通过命令行上的'-m'另外传递的所有测试?在

例如: pytest-m“平台1”

将运行标记为@pytest.mark.platform1以及所有标记的测试@pytest.mark.all\u平台甚至所有的测试都没有@pytest.mark完全?在

考虑到大量的共享功能,可以将@pytest.mark.all\u平台电话会有很大的帮助。在


Tags: 方法命令行标记模型功能目录类型pytest
2条回答

让我们解决全部问题。我想你可以把conftest.py文件与您的测试,它将注意跳过所有不匹配的测试(未标记的测试将始终匹配,因此永远不会被跳过)。我在这里使用系统平台但我相信你有不同的方法来计算你的平台价值。在

# content of conftest.py
#
import sys
import pytest

ALL = set("osx linux2 win32".split())

def pytest_runtest_setup(item):
    if isinstance(item, item.Function):
        plat = sys.platform
        if not hasattr(item.obj, plat):
            if ALL.intersection(set(item.obj.__dict__)):
                pytest.skip("cannot run on platform %s" %(plat))

你可以这样标记你的测试:

^{pr2}$

如果你跑的话:

$ py.test -rs

然后,您可以运行它,并将看到至少两个测试被跳过,并且始终如此 至少执行一个测试:

然后您将看到两个被跳过的测试和两个按预期执行的测试:

$ py.test -rs # this option reports skip reasons
=========================== test session starts ============================
platform linux2   Python 2.7.3   pytest-2.2.5.dev1
collecting ... collected 4 items

test_plat.py s.s.
========================= short test summary info ==========================
SKIP [2] /home/hpk/tmp/doc-exec-222/conftest.py:12: cannot run on platform linux2

=================== 2 passed, 2 skipped in 0.01 seconds ====================

请注意,如果通过标记命令行选项指定平台,如下所示:

$ py.test -m linux2
=========================== test session starts ============================
platform linux2   Python 2.7.3   pytest-2.2.5.dev1
collecting ... collected 4 items

test_plat.py .

=================== 3 tests deselected by "-m 'linux2'" ====================
================== 1 passed, 3 deselected in 0.01 seconds ==================

然后将不运行未标记的测试。因此,这是一种将运行限制为特定测试的方法。在

参加聚会很晚了,但我刚刚解决了一个类似的问题,在所有未标记的测试中添加了一个默认标记。在

作为问题的直接答案:您可以让未标记的测试始终运行,并且只包括通过-m选项指定的标记测试,方法是将以下内容添加到conftest.py在

def pytest_collection_modifyitems(items, config):
    # add `always_run` marker to all unmarked items
    for item in items:
        if not any(item.iter_markers()):
            item.add_marker("always_run")
    # Ensure the `always_run` marker is always selected for
    markexpr = config.getoption("markexpr", 'False')
    config.option.markexpr = f"always_run or ({markexpr})"

相关问题 更多 >

    热门问题