我正在处理一种叫做“带”的奇怪行为。我的模拟可以工作,但是如果我尝试比较调用函数的参数,我会得到错误(如下所示):
data = {"result": {"fizz": "buzz"}}
mock = MagicMock()
mock.configure_mock(**{"post.return_value": mock, "json.return_value": data})
dispatcher.session = mock
@dispatcher.dispatch()
def test():
pass
test() # here calls self.session.post(...).json()
assert mock.post.assert_called_with()
无参数:
assert mock.post.assert_called_with()
我得到了错误(如预期的那样):
> assert mock.post.assert_called_with()
E AssertionError: expected call not found.
E Expected: post()
E Actual: post('', json={'id': 0, 'jsonrpc': '2.0', 'method': 'test', 'params': {}})
E
E pytest introspection follows:
E
E Args:
E assert ('',) == ()
E Left contains one more item: ''
E Full diff:
E - ()
E + ('',)
E Kwargs:
E assert {'json': {'id...'params': {}}} == {}
E Left contains 1 more item:
E {'json': {'id': 0, 'jsonrpc': '2.0', 'method': 'test', 'params': {}}}
E Full diff:
E - {}
E + {'json': {'id': 0, 'jsonrpc': '2.0', 'method': 'test', 'params': {}}}
但是,如果我传递调用的参数,如下所示:
assert mock.post.assert_called_with(
"", json={"id": 0, "jsonrpc": "2.0", "method": "test", "params": {}}
)
我得到
> assert mock.post.assert_called_with(
"", json={"id": 0, "jsonrpc": "2.0", "method": "test", "params": {}}
)
E AssertionError: assert None
E + where None = <bound method wrap_assert_called_with of <MagicMock name='mock.post' id='140014005058048'>>('', json={'id': 0, 'jsonrpc': '2.0', 'method': 'test', 'params': {}})
E + where <bound method wrap_assert_called_with of <MagicMock name='mock.post' id='140014005058048'>> = <MagicMock name='mock.post' id='140014005058048'>.assert_called_with
E + where <MagicMock name='mock.post' id='140014005058048'> = <MagicMock id='140014005036992'>.post
删除前面的
assert
调用。它应该是mock.post.assert_called_with()
。它失败是因为在模拟对象上的该断言之前有一个assert
。由于mock.post.assert_called_with()
返回None
,测试失败,因为它的计算结果为assert None
。你可以在documentation here中看到更多信息相关问题 更多 >
编程相关推荐