我试图模仿MagicMock实例函数的返回值,但结果并没有像我预期的那样:
>>> f = mock.MagicMock() # => <MagicMock id='139903823124048'>
>>> g = mock.MagicMock() # => <MagicMock id='139903823522512'>
>>> f.goo.return_value = g
>>> g # => <MagicMock name='mock.goo()' id='139903823522512'>
实例g没有改变,但其名称有变化吗? 当我尝试:
>>> f.goo(1,2)
>>> g.zoo('a')
>>> f.goo(3,4)
>>> f.goo.assert_has_calls([call(1,2), call(3,4)])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/lando/.local/lib/python2.7/site-packages/mock/mock.py", line 969, in assert_has_calls
), cause)
File "/home/lando/.local/lib/python2.7/site-packages/six.py", line 737, in raise_from
raise value
AssertionError: Calls not found.
Expected: [call(1, 2), call(3, 4)]
Actual: [call(1, 2), call().zoo('a'), call(3, 4)]
为什么g的通话成为f.goo通话的一部分? 甚至:
>>> f.goo.call_args_list # => [call(1, 2), call(3, 4)]
答案 0 :(得分:0)
这种行为不是很直观,但是是出于期望。 见 -
https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_has_calls https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.mock_calls
还会在mock_calls中跟踪对返回值的调用。
使用any_order
标志。