【问题标题】:AttributeError: 'function' object has no attribute in Pytest MockAttributeError:“函数”对象在 Pytest Mock 中没有属性
【发布时间】:2019-10-06 16:15:58
【问题描述】:

我正在尝试测试我的函数是否在测试中被调用,但我得到:

AttributeError: 'function' object has no attribute 'assert_called_once'

我没有嘲笑这个正确的,所以请你帮我找出为什么我的模拟在这种情况下不起作用。我有正确的方法来模拟这个函数。

我已经尝试过这个 -> create_autospec 来解决 AttributeError,但没有运气。

代码示例:

class MyClass:
    def __init__(self):
        self._data = {}

    def a(self, value):
        self._data = value

@pytest.fixture
def my_fixture():
    return MyClass()

@pytest.mark.asyncio
async def test_random_function(my_fixture, mocker):
    s = mocker.patch('path.module.a',
                              my_fixture.a)

    await random_function()
    s.assert_called_once()

【问题讨论】:

    标签: python unit-testing mocking pytest attributeerror


    【解决方案1】:

    您的测试函数中的my_fixture.aMyClass.a 函数,它显然没有assert_called_once。这是unittest.mock.Mockunittest.mock.MagicMock 中的method。我不知道你为什么要用你自己的对象修补path.module.a,但我认为你很难获得MagicMock 提供的相同功能。在您的示例中,我将简单地使用以下内容。

    @pytest.mark.asyncio
    async def test_random_function(my_fixture, mocker):
        s = mocker.patch('path.module.a')
    
        await random_function()
        s.assert_called_once()
    

    【讨论】:

      猜你喜欢
      • 2022-01-14
      • 2019-05-10
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      • 2017-08-14
      相关资源
      最近更新 更多