【问题标题】:Marking a Pytest fixture instead of all the tests using the fixture标记一个 Pytest 夹具而不是使用该夹具的所有测试
【发布时间】:2020-02-17 22:11:44
【问题描述】:

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

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

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

我的夹具代码如下所示:

@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 (updated link) 中发现了以下评论:

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

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

【问题讨论】:

    标签: pytest


    【解决方案1】:

    您似乎已经在文档中找到了答案。订阅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")
    

    【讨论】:

    • 好答案。不过,我不会称其为 hack。 Automatically marking 测试功能在我看来非常像它的设计目的。
    • 如果你能标记一个灯具会更好.. 耸耸肩
    • 当我继承了一个代码库并且我试图弄清楚为什么我的新函数 test_postgres_bla_bla_bla() 没有执行时,这种事情让我陷入了困境。
    猜你喜欢
    • 1970-01-01
    • 2018-11-22
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    相关资源
    最近更新 更多