Py.Test 为所有测试添加标记

Py.Test add marker to all tests

我正在使用 python asyncio 和 pytest-aysncio,这意味着我所有的测试看起来像:

@pytest.mark.asyncio
async def test_my_func():
    result = await my_func()
    assert result == expected

这很好用,但我宁愿不必为了让它们工作而装饰每个函数。 pytest中有没有办法将这个标记添加到每个测试函数?

您可以将 pytest_collection_modifyitems 挂钩添加到您的 conftest.py:

def pytest_collection_modifyitems(items):
    for item in items:
        item.add_marker('asyncio')

或者要按文件方式执行此操作,您可以在该文件中全局设置 pytestmark = pytest.mark.asyncio

如果您使用的是 pytest-asyncio>=0.17,您可以将以下内容放入 pytest.ini

[pytest]
asyncio_mode=auto

这消除了标记每个测试的需要;只需用 async def 声明测试函数就足够了。