【问题标题】:How to mock pytest.fixture decorator?如何模拟 pytest.fixture 装饰器?
【发布时间】:2018-03-19 04:34:29
【问题描述】:

我想为 conftest.py 中的 pytest 固定装置编写单元测试
如何模拟装饰器 pytest.fixture?

Conftest.py

import pytest 

@pytest.fixture(scope="session", autouse="True")
def get_ip(dict_obj):
    """Assume some functionality"""
    return dict_obj.get('ip')


@pytest.fixture(scope="class")
def get_server(create_obj):
    """Assume some functionality"""
    pass

test_conftest.py

mock_fixture = patch('pytest.fixture', lambda x : x).start()
from tests.conftest import get_ip  


class TestConftestTests:

    def test_mgmt_ip(self):
        assert mgmt_ip({"ip": "10.192.174.15"}) == "10.192.174.15"

 E   TypeError: <lambda>() got an unexpected keyword argument 'scope' 

当我在导入要测试的函数之前尝试在测试模块的开头 mock pytest.fixture 时,出现错误 - E TypeError: &lt;lambda&gt;() got an unexpected keyword argument 'scope'

如果我删除 lambda 函数,我会收到 E AssertionError: assert &lt;MagicMock name='fixture()()()' id='4443565456'&gt; == '10.192.174.15'

test_conftest.py

patch('pytest.fixture').start()
from tests.conftest import get_ip  


class TestConftestTests:

    def test_mgmt_ip(self):
        assert mgmt_ip({"ip": "10.192.174.15"}) == "10.192.174.15"

E       AssertionError: assert <MagicMock name='fixture()()()' id='4443565456'> == '10.192.174.15' 

有人可以帮我解决这个错误吗?谢谢!

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    @pytest.fixture(scope='session') 将使用 kwarg scope 调用您的 lambda x: x。涵盖 pytest.fixture 的 no-args 和 some-args 版本的模拟可能是:

    pytest_fixture = lambda x=None, **kw: x if callable(x) else fixture
    

    但需要注意的是pytest.fixture 本身不会进行任何注册。它仅通过在其上设置_pytestfixturefunction 属性将该功能标记为固定装置;之后,pytest 会收集夹具。

    我不确定您是否正在为您可能想要完成的任何事情寻找正确的树。如果您想更改某个固定装置在某些上下文中的值,可以使用类和子类来覆盖父固定装置。如果您尝试查看是否使用了固定装置,则创建一个新类并用您的断言覆盖固定装置可能会很有用。

    【讨论】:

      猜你喜欢
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      • 2012-11-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 2013-07-19
      • 2013-11-17
      相关资源
      最近更新 更多