我使用 pytest 编写测试。我需要在一些测试之前和之后做某些事情。如果标有
some_fixture
,如何自动将some_marker
设置为测试功能?
为了实现这一点,我编写了一个上下文管理器+固定装置。
# conftest.py
class ContextManager:
def __init__(self, some_args):
self.some_args = some_args
def __enter__(self):
pass # do something
def __exit__(self, exc_type, exc_val, exc_tb):
pass # do something
@pytest.fixture
def some_fixture(request):
some_args = request.node.get_closest_marker("some_marker").kwargs.get("some_args")
with ContextManager(some_args):
yield
def pytest_configure(config):
config.addinivalue_line("markers", "some_marker(some_args): ...")
但这很不方便,因为我需要不断指定夹具。
# module_test.py
@pytest.mark.some_marker(some_args=[...])
def test_function(some_fixture):
pass
如果您不想手动添加灯具名称,可以在物品收集过程中添加。您可以通过
Function.fixturenames
访问和更改项目的夹具名称(由于某种原因,未在 Function 的文档中列出,但在其他地方提到过,所以我猜它是 API 的一部分):
conftest.py
def pytest_collection_modifyitems(items):
for item in items:
if item.get_closest_marker("some_marker"):
item.fixturenames.append("some_fixture")
module_test.py
@pytest.mark.some_marker(some_args=[...])
def test_function():
pass
只要您不需要在测试中按名称访问夹具,这应该可以工作。