如何获取与 python 的 `mock.assert_used_with()` 的差异?

问题描述 投票:0回答:1

当在两个复杂的字典上调用

unittest.TestCase.assertEqual()
时,我得到了一个很好的差异。

有什么方法可以与 Python 2.7 的

mock.Mock.assert_called_with
进行比较吗?我正在测试采用一些具有复杂值的字典参数的调用,当其中一个缺少布尔值时,很难看出问题是什么。

例如

AssertionError: Expected call: post('http://cloud-atlas.cogolo.net/api/executions', auth=('cloudatlas', 'cloudatlas'), data={'environment': 'hadoop', 'source': 'repo', 'output_path': 'hdfs://namenode-01/user/erose/testing', 'production': True, 'input_path': 'hdfs://namenode-01/foo/bar', 'name': 'linecount', 'mrcloud_options': '{"mrcloud_option_A": "foobar", "hadoop_user_name": "erose"}', 'details': '{"path_to_file": "linecount.py", "parameters": {}, "branch": "master", "repo_name": "example_repo"}'}, headers={'X-COGO-CLOUDATLAS-USER': 'erose'})
Actual call: post('http://cloud-atlas.cogolo.net/api/executions', auth=('cloudatlas', 'cloudatlas'), data={'input_path': 'hdfs://namenode-01/foo/bar', 'name': 'linecount', 'environment': 'hadoop', 'source': 'repo', 'output_path': 'hdfs://namenode-01/user/erose/testing', 'details': '{"path_to_file": "linecount.py", "parameters": {}, "branch": "master", "repo_name": "example_repo"}', 'mrcloud_options': '{"mrcloud_option_A": "foobar", "hadoop_user_name": "erose"}'}, headers={'X-COGO-CLOUDATLAS-USER': 'erose'})
python python-2.7 python-unittest python-mock
1个回答
0
投票

如果没有对

Mock.assert_called_with
的 diff 输出的官方支持,您可以使用
Mock
子类自行实现逻辑,方法是使用已进行调用的断言覆盖
assert_called_with
方法,以及
args
 kwargs
如给定,利用
assertTupleEqual
assertDictEqual
的良好差异输出:

from unittest import mock

class CallDiffingMock(mock.Mock):
    def assert_called_with(self, *args, **kwargs):
        self.assert_called()
        test = TestCase()
        test.assertTupleEqual(args, self.call_args.args)
        test.assertDictEqual(kwargs, self.call_args.kwargs)

这样:

from unittest import TestCase

class Test(TestCase):
    def test_call(self):
        f = CallDiffingMock()
        f(a=1, b=2)
        f.assert_called_with(a=1, b=2, c=3)

会产生:

======================================================================
FAIL: test_call (main.Test.test_call)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "main.py", line 14, in test_call
    f.assert_called_with(a=1, b=2, c=3)
  File "main.py", line 8, in assert_called_with
    test.assertDictEqual(kwargs, self.call_args.kwargs)
AssertionError: {'a': 1, 'b': 2, 'c': 3} != {'a': 1, 'b': 2}
- {'a': 1, 'b': 2, 'c': 3}
?                --------

+ {'a': 1, 'b': 2}

----------------------------------------------------------------------
Ran 1 test in 0.003s

FAILED (failures=1)

演示:https://ideone.com/OvfWY8

© www.soinside.com 2019 - 2024. All rights reserved.