将现有的上下文管理器重用为 pytest fixture
Reuse an existing context manager as a pytest fixture
我有多个测试需要的现有上下文管理器。与其在每个测试中编写一个 with
块,我认为最好用这个上下文管理器制作一个夹具,并用 @pytest.mark.usefixtures("my_fixture")
.
装饰测试
我可以将上下文管理器重新实现为固定装置,但这似乎是重复代码。所以我想在新夹具中引用原始上下文管理器。
这是我的:
import my_context_manager
@pytest.fixture
def my_fixture(arg1, arg2):
with my_context_manager(arg1, arg2) as c:
yield c
这是将现有上下文管理器转换为固定装置的合适方法吗?
我应该提一下,我知道 contextlib.ContextDecorator
编写了一个可以用作装饰器的上下文管理器。但是我的上下文管理器需要参数,并且当它们在 @my_context_decorator(arg1, arg2)
.
这样的语句中时无法识别这些参数
创建了一个简单的上下文管理器,将其用作夹具并在测试中调用该夹具。
Note: Advantage of using context manager this way is if the test fails
still exit will execute. However, if you directly call context
manager in test and if test failed post-yield statements will not
execute.
createcontextmanager.py
class ContextManager():
def __init__(self):
print('init method called')
def __enter__(self):
print('enter method called')
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
print('exit method called')
test_checkcontextmanagerwithfixture.py
import pytest
import createContextManager as ccm
@pytest.fixture(name ="c")
def check():
with ccm.ContextManager() as cm:
yield "hello"
@pytest.mark.Whosebug
def test_checkficture(c):
assert c =="hello", 'failed'
使用 'python -m pytest -m Whosebug -v -s' 的输出顺序您可能还有其他东西。我想这就是我们想要的上下文管理器。
- init 方法调用
- 输入调用的方法
- 通过
- 调用了退出方法
我有多个测试需要的现有上下文管理器。与其在每个测试中编写一个 with
块,我认为最好用这个上下文管理器制作一个夹具,并用 @pytest.mark.usefixtures("my_fixture")
.
我可以将上下文管理器重新实现为固定装置,但这似乎是重复代码。所以我想在新夹具中引用原始上下文管理器。
这是我的:
import my_context_manager
@pytest.fixture
def my_fixture(arg1, arg2):
with my_context_manager(arg1, arg2) as c:
yield c
这是将现有上下文管理器转换为固定装置的合适方法吗?
我应该提一下,我知道 contextlib.ContextDecorator
编写了一个可以用作装饰器的上下文管理器。但是我的上下文管理器需要参数,并且当它们在 @my_context_decorator(arg1, arg2)
.
创建了一个简单的上下文管理器,将其用作夹具并在测试中调用该夹具。
Note: Advantage of using context manager this way is if the test fails still exit will execute. However, if you directly call context manager in test and if test failed post-yield statements will not execute.
createcontextmanager.py
class ContextManager():
def __init__(self):
print('init method called')
def __enter__(self):
print('enter method called')
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
print('exit method called')
test_checkcontextmanagerwithfixture.py
import pytest
import createContextManager as ccm
@pytest.fixture(name ="c")
def check():
with ccm.ContextManager() as cm:
yield "hello"
@pytest.mark.Whosebug
def test_checkficture(c):
assert c =="hello", 'failed'
使用 'python -m pytest -m Whosebug -v -s' 的输出顺序您可能还有其他东西。我想这就是我们想要的上下文管理器。
- init 方法调用
- 输入调用的方法
- 通过
- 调用了退出方法