首页 > 解决方案 > pytest - 如何知道选择了哪些标记

问题描述

pytest 有什么方法可以知道从命令行选择了哪些标记?

我有一些标记为“慢”的测试需要大量处理。我只想在激活标记缓慢的情况下处理治疗。

heavy_var = None

def setup_module(module):
    global heavy_var

    # Need help here!?
    if markers["slow"]:
        heavy_var = treatment()


def test_simple():
    pass


@pytest.mark.slow():
def test_slow():
    assert heavy_var.x == "..."

我怎么知道是否选择了慢速标记?当我调用 pytest 时-m not slow markers["slow"]将为 False,否则为 True。

标签: pythonpython-3.xpytest

解决方案


如果仅在选择了标记为的测试时才需要运行某些代码slow,则可以通过在模块范围的夹具中过滤测试项来替换setup_module. 例子:

@pytest.fixture(scope='module', autouse=True)
def init_heavy_var(request):
    for item in request.session.items:
        if item.get_closest_marker('slow') is not None:
            # found a test marked with the 'slow' marker, invoke heavy lifting
            heavy_var = treatment()
            break

推荐阅读