简体   繁体   English

将MagicMock实例分配给另一个MagicMock实例的return_value

[英]Assign a MagicMock instance to return_value of another MagicMock instance

I'm trying to mock the return value of a MagicMock instance's function, but the result doesn't go as I expected: 我正在尝试模拟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'>

Instance g hasn't changed but its name changes? 实例g尚未更改,但其名称已更改? And when I try: 当我尝试:

>>> 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)]

Why does g's call become a part of f.goo's call? 为什么g的通话成为f.goo通话的一部分? Even: 甚至:

>>> f.goo.call_args_list # => [call(1, 2), call(3, 4)]

This behaviour not very intuitive, but is per expectation. 这种行为不是很直观,但是是意料之中的。 See- 看到-

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 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

The calls to the returned values are also tracked in the mock_calls. 在mock_calls中也跟踪对返回值的调用。

Use the any_order flag. 使用any_order标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM