【问题标题】:Strange behaviour of assert_called_withassert_call_with 的奇怪行为
【发布时间】:2021-02-26 19:21:40
【问题描述】:

我正在处理 assert_call_with 的一个奇怪行为。我的模拟工作,但如果我尝试比较调用函数的参数,我得到了错误(如下):

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

【问题讨论】:

    标签: python pytest python-unittest


    【解决方案1】:

    删除领先的assert 调用。它应该只是mock.post.assert_called_with()。它失败是因为在模拟对象上的断言之前有一个assert。由于mock.post.assert_called_with() 返回None,因此您的测试失败,因为它的计算结果为assert None。你可以在documentation here看到更多。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-08
      • 2015-07-20
      • 2010-10-03
      • 2021-07-12
      • 2013-10-04
      • 2019-01-23
      相关资源
      最近更新 更多