首页 > 解决方案 > 标记一个 Pytest 夹具而不是使用该夹具的所有测试

问题描述

有没有办法在 PyTest 夹具中定义标记?

-m "not slow"当我在 pytest 中指定时,我试图禁用慢速测试。

我已经能够禁用单个测试,但不能禁用用于多个测试的夹具。

我的夹具代码如下所示:

@pytest.fixture()
@pytest.mark.slow
def postgres():
    # get a postgres connection (or something else that uses a slow resource)
    yield conn 

并且有几个测试具有这种一般形式:

def test_run_my_query(postgres):
    # Use my postgres connection to insert test data, then run a test
    assert ...

我在https://docs.pytest.org/en/latest/mark.html更新链接)中找到了以下评论:

“标记只能应用于测试,对夹具没有影响。” 这个评论的原因是夹具本质上是函数调用并且标记只能在编译时指定?

有没有办法指定使用特定夹具(在这种情况下为 postgres)的所有测试都可以标记为慢而不@pytest.mark.slow在每个测试上指定?

标签: pytest

解决方案


看来您已经在文档中找到了答案。订阅https://github.com/pytest-dev/pytest/issues/1368观看此功能,可能会在以后的 pytest 版本中添加。

现在,你可以做一个解决方法:

# in conftest.py

def pytest_collection_modifyitems(items):
    for item in items:
        if 'postgres' in getattr(item, 'fixturenames', ()):
            item.add_marker("slow")

推荐阅读