【问题标题】:Why is assert_called_with failing to pass?为什么 assert_call_with 没有通过?
【发布时间】:2016-12-06 03:05:11
【问题描述】:

我在设置单元测试时遇到了很多困难。我一直在使用补丁,但它的行为并不完全符合预期。

我的测试函数顶部有一个装饰器: @mock.patch('WarningFactory.WarningAPIUpdate') @mock.patch('WarningFactory.SomethingElse') def test_send_tc_update(self, other_mock, api_mock):

但是,在我的函数结束时,当我尝试做出以下断言时:

api_mock.send_warning.assert_called_with('IDQ20026', 'IDQ20026')

失败了

我知道这应该通过,因为我运行了

print api_mock.mock_calls

给予

[call(u'test_api'), call().send_warning('IDQ20026', 'IDQ20026'), call().send_warning('IDQ24500', 'IDQ24500')]

我可以清楚地看到使用正确的值调用了 send_warning 方法,那么为什么我的断言失败了?

【问题讨论】:

  • 你有想过这个吗?有同样的问题
  • @learningKnight 添加了答案,希望对您有所帮助。

标签: mocking patch python-2.6


【解决方案1】:

现在回想起来,问题是 assert_call_with 只检查最近的调用。

assert_any_call(*args, **kwargs)¶ 断言模拟已被调用 指定的参数。

如果曾经调用过模拟,则断言通过,不像 只有当 该呼叫是最近的呼叫,并且在以下情况下 assert_call_once_with() 它也必须是唯一的调用。

文档有点狡猾,因为他们没有在 assert_call_with 方法下提及这一点。

我最终使用 assert_any_call 方法进行测试。

【讨论】:

  • 没有帮助我,但感谢你无论如何都回来了
【解决方案2】:

如果user3559247's answer 不起作用,可能是您正在尝试模拟嵌套对象,您需要阅读有关chaining mock calls 的信息。就我而言,我想在利用 Azure Python SDK 的假设类 MyAzureBatchClient 中测试此代码:

def node_counts():
  self.batch_client = azure.batch.batch_service_client.BatchServiceClient(...)
  self.batch_client.account.list_pool_node_counts()
  ...

调用mocked_batch_client.account.list_pool_node_counts.assert_called_with() 失败,尽管检查mock_calls 属性会显示与您类似的内容:

[call().list_pool_node_counts()]

但是,当与mocked_batch_client.return_value.account.list_pool_node_counts.assert_called_with() 正确链接时,它会按预期工作。检查mocked_batch_client.return_value.account.mock_calls 时,注意call.method 是如何出现而不是call().method: [call.list_pool_node_counts()]

【讨论】:

    【解决方案3】:

    根据您提到的打印输出,语法可能应该是:

    api_mock.return_value.send_warning.assert_called_with('IDQ20026', 'IDQ20026')
    

    注意 call().send_warning('IDQ20026', 'IDQ20026') 前缀,它与 .return_value 相关。

    但是为什么要这么努力呢?我写了一个helper library 来自动为我生成断言。

    只需添加这些行即可为您的案例打印正确的断言:

    import mock_autogen.generator
    print(mock_autogen.generator.generate_asserts(api_mock))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多