【问题标题】:Reuse an existing context manager as a pytest fixture重用现有的上下文管理器作为 pytest 夹具
【发布时间】:2020-02-24 17:02:20
【问题描述】:

我有多个测试所需的现有上下文管理器。与其在每个测试中编写 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) 这样的语句中时,它们无法识别。

【问题讨论】:

  • 我认为这是目前唯一可用的选项。我有我的实现相同的发布它作为答案,因为发布代码作为评论会搞砸。如果你不喜欢它,请忽略它。

标签: python pytest fixtures contextmanager


【解决方案1】:

创建了一个简单的上下文管理器,将其用作夹具并在测试中调用该夹具。

注意:以这种方式使用上下文管理器的好处是如果测试失败 exit 仍然会执行。但是,如果您直接调用上下文 测试中的经理,如果测试失败后屈服语句将不会 执行。

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'的输出顺序你可能有别的东西。我认为这是我们希望上下文管理器提供的。

  • 调用初始化方法
  • 输入方法调用
  • 通过
  • 退出方法调用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多