我有一个现有的上下文管理器,它是多个测试所必需的。与其在每个测试中编写一个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)这样的语句中是不被识别的。
发布于 2020-02-24 19:35:38
创建了一个简单的上下文管理器,将其用作工具,并在测试中调用该夹具。
注意:以这种方式使用上下文管理器的优点是,如果测试失败,退出将执行。但是,如果您在测试中直接调用上下文管理器,如果测试失败,则将不执行生成后语句。
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.stackoverflow
def test_checkficture(c):
assert c =="hello", 'failed'使用'python -m pytest -m stackoverflow -v -s‘的输出顺序--您可能有其他东西。我想这是我们想从上下文经理那里得到的。
called
https://stackoverflow.com/questions/60380704
复制相似问题