首页 文章

如何模拟pytest.fixture装饰?

提问于
浏览
0

我想为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: <lambda>() got an unexpected keyword argument 'scope'

如果我 remove the lambda function ,我正在 E AssertionError: assert <MagicMock name='fixture()()()' id='4443565456'> == '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'

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

1 回答

  • 0

    @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收集夹具 .

    我不确定你是否正在咆哮着正确的树,无论你想要完成什么 . 如果要更改夹具在某些上下文中具有的值,可以使用类和子类来覆盖父夹具 . 如果您正在尝试查看是否使用了夹具,则创建新类并使用断言覆盖夹具可能很有用 .

相关问题