测试如何知道选择了哪些标记

2024-04-20 06:04:54 发布

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

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 == "..."

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


Tags: 方法命令行标记testnonepytestvardef
1条回答
网友
1楼 · 发布于 2024-04-20 06:04:54

如果仅当选择了标有slow的测试时才需要运行某些代码,那么可以通过过滤模块范围内的fixture(替换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

相关问题 更多 >