Python模拟不断言调用
我正在使用mock库修补程序中的一个类,该程序连接到外部资源并发送一个dictionanry 结构有点像这样 代码.pyPython模拟不断言调用,python,unit-testing,mocking,python-mock,Python,Unit Testing,Mocking,Python Mock,我正在使用mock库修补程序中的一个类,该程序连接到外部资源并发送一个dictionanry 结构有点像这样 代码.py def make_connection(): connection = OriginalClass(host, port) connection.connect() connection.send(param) connection.close() test.py @mock.path('code.OriginalClass') def te
def make_connection():
connection = OriginalClass(host, port)
connection.connect()
connection.send(param)
connection.close()
test.py
@mock.path('code.OriginalClass')
def test_connection(self, mocked_conn):
code.make_connection()
mocked_conn.assert_called_with(host, port)
mocked_conn.connect.assert_called_once()
mocked_conn.send.assert_called_with(param)
第一个assert_称为_with,它可以完美地工作,但是对mock类的方法的调用
不要通过。我尝试过使用patch.object作为装饰程序,但也没有成功。在第一次调用的返回值上调用connect()
和send()
方法;相应地调整您的测试:
mocked_conn.return_value.connect.assert_called_once()
mocked_conn.return_value.send.assert_called_with(param)
我通常首先存储对“实例”的引用:
@mock.path('code.OriginalClass')
def test_connection(self, mocked_conn):
code.make_connection()
mocked_conn.assert_called_with(host, port)
mocked_instance = mocked_conn.return_value
mocked_instance.connect.assert_called_once()
mocked_instance.send.assert_called_with(param)
难以置信,我真不敢相信我没看到。我能把这个票数超过9000吗?谢谢,一大堆热气腾腾的东西我将从现在开始保留那个参考资料,避免再次出现类似的头痛。