gpt4 book ai didi

python - 将 MagicMock return_value 实例方法可调用更改为 PropertyMock

转载 作者:太空宇宙 更新时间:2023-11-03 21:45:38 25 4
gpt4 key购买 nike

我正在尝试将 MagicMock 上的实例方法的可调用更改为 PropertyMock,因为这就是访问它的方式(Django 模型列)。但测试失败了

 _mock_self = <PropertyMock name='get().my_prop' id='4524632776'>

给出以下代码

# view
def get(self request):
# stuff...
obj = MyModel.objects.get(id=2)
# more stuff...
print(obj.my_prop)
some_val = MyOtherModel(my_prop=obj.my_prop)

# tests
def test_my_test(mocker):
other_obj = mocker.patch("app.views.MyOtherModel")
obj_get = mocker.patch("app.views.MyModel.objects.get")
obj_prop = mocker.PropertyMock(return_value=1)
# This should translate to an instance of MyModel i.e. MyModel().my_prop
obj_get.return_value.my_prop = obj_prop

# run view

obj_prop.assert_called_once() # Says never invoked
# Failed as my_prop was a PropertyMock instead of actual value
other_obj.assert_called_once_with(my_prop=obj_prop)

打印语句显示

 <PropertyMock name='get().my_prop' id='4524632776'>

所以看起来它是同一个实例,只是实际上没有被调用

我还尝试直接从模型中修补属性,但这似乎不起作用,因为模拟并不相同。

def test_my_test(mocker):
other_obj = mocker.patch("app.views.MyOtherModel")
obj_prop = mocker.patch("app.views.MyModel.my_prop", new_callable=mocker.PropertyMock)
obj_get = mocker.patch("app.views.MyModel.objects.get")
obj_get.return_value.my_prop = obj_prop

# run view
obj_prop.assert_called_once()
# Failed as my_prop was a PropertyMock instead of actual value
other_obj.assert_called_once_with(my_prop=obj_prop)

失败了...

_mock_self = <PropertyMock name='my_prop' id='4543022192'>

但打印

 <MagicMock name='get().my_prop' id='4543752232'>

编辑添加了其他补丁,可以更准确地描述实现

最佳答案

PropertyMock 覆盖所需的属性是不必要的,因为我可以简单地将我想要的值分配给 MagicMock

def test_my_test(mocker):

other_obj = mocker.patch("app.views.MyOtherModel")

obj_get = mocker.patch("app.views.MyModel.objects.get")
obj_get.return_value.my_prop = 2

# run view
other_obj.assert_called_once_with(my_prop=obj_get.return_value.my_prop)

.assert_used_once 用于检查该属性是否曾被调用,并在 .assert_used_once_with 最初失败时添加。

关于python - 将 MagicMock return_value 实例方法可调用更改为 PropertyMock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52520670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com