标记 Pytest 夹具而不是使用该夹具的所有测试

Ted*_*ney 15 pytest

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

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

我已经能够禁用单个测试,但不能禁用用于多个测试的固定装置。

我的夹具代码如下所示:

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

一些测试具有以下一般形式:

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

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

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

有没有一种方法可以指定使用特定固定装置(在本例中为 postgres)的所有测试都可以标记为慢,而无需@pytest.mark.slow在每个测试上指定?

wim*_*wim 8

看来您已经在文档中找到了答案。订阅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")
Run Code Online (Sandbox Code Playgroud)

  • 当我继承了一个代码库并且试图找出为什么我的新函数“test_postgres_bla_bla_bla()”没有执行时,这种事情让我感到困惑。 (3认同)
  • 好答案。但我不会称其为黑客。[自动标记](https://docs.pytest.org/en/latest/example/markers.html#automatically-adding-markers-based-on-test-names) 在我看来,测试函数非常像它被设计用于。 (2认同)