为什么两个魔术模拟实例在ID中有所不同?
阅读本教程后,我正在尝试使用Patch()将模拟注入呼叫: https://kimsereylam.com/python/2021/03/03/how-to-to-poth-to-path-to-patch-patch-in-patch-in-python-unittest.html一下期望模拟ID与实际不同。
这是要说明的代码段:
my_class.py
class MyClass:
def __init__(self):
self.value = 5
run.py
from my_class import MyClass
def call_first():
o = MyClass()
print(o)
call_second(o)
def call_second(myclass):
print("second is called")
print(myclass)
main。 PY
from unittest.mock import patch
from my_class import MyClass
from run import call_first, call_second
with patch("run.MyClass") as myclass_mock:
print(myclass_mock)
print(call_first())
with patch("run.call_second") as call_second_mock:
call_second_mock.assert_called_once_with(myclass_mock)
输出是:
<MagicMock name='MyClass' id='140711608367712'>
<MagicMock name='MyClass()' id='140711598743312'>
second is called
<MagicMock name='MyClass()' id='140711598743312'>
None
Traceback (most recent call last):
File "main.py", line 9, in <module>
call_second_mock.assert_called_once_with(myclass_mock)
File "/usr/lib/python3.8/unittest/mock.py", line 924, in assert_called_once_with
raise AssertionError(msg)
AssertionError: Expected 'call_second' to be called once. Called 0 times.
我错过了什么?我正在尝试使用patch(),因此我可以模拟call_first()内实例化并传递给call_second()的myClass()对象。
I am trying to use patch() to inject mock into a call after reading this tutorial: https://kimsereylam.com/python/2021/03/19/how-to-use-patch-in-python-unittest.html, but the expect mock ID is different than actual.
Here is snippet of code to illustrate:
my_class.py
class MyClass:
def __init__(self):
self.value = 5
run.py
from my_class import MyClass
def call_first():
o = MyClass()
print(o)
call_second(o)
def call_second(myclass):
print("second is called")
print(myclass)
main.py
from unittest.mock import patch
from my_class import MyClass
from run import call_first, call_second
with patch("run.MyClass") as myclass_mock:
print(myclass_mock)
print(call_first())
with patch("run.call_second") as call_second_mock:
call_second_mock.assert_called_once_with(myclass_mock)
The output is:
<MagicMock name='MyClass' id='140711608367712'>
<MagicMock name='MyClass()' id='140711598743312'>
second is called
<MagicMock name='MyClass()' id='140711598743312'>
None
Traceback (most recent call last):
File "main.py", line 9, in <module>
call_second_mock.assert_called_once_with(myclass_mock)
File "/usr/lib/python3.8/unittest/mock.py", line 924, in assert_called_once_with
raise AssertionError(msg)
AssertionError: Expected 'call_second' to be called once. Called 0 times.
What did I miss? I am trying to use patch() so I can mock the MyClass() object that is instantiated inside call_first() and passed to call_second().
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
call_second
首先call_second
first