gpt4 book ai didi

python - 断言两个字典几乎相等

转载 作者:太空狗 更新时间:2023-10-29 18:01:34 24 4
gpt4 key购买 nike

我试图断言两个词典几乎相等,但我似乎做不到。

这是一个例子:

>>> import nose.tools as nt
>>> nt.assert_dict_equal({'a' : 12.4}, {'a' : 5.6 + 6.8})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/unittest/case.py", line 838, in assertDictEqual
self.fail(self._formatMessage(msg, standardMsg))
File "/usr/lib/python2.7/unittest/case.py", line 413, in fail
raise self.failureException(msg)
AssertionError: {'a': 12.4} != {'a': 12.399999999999999}
- {'a': 12.4}
+ {'a': 12.399999999999999}

我希望这样过去:

>>> nt.assert_almost_equal(12.4, 5.6 + 6.8)

我希望我遗漏了一些简单的东西,比如 nt.assert_almost_dict_equal,或者我可以传递给 nt.assert_dict_equal 的参数指定 float 的接近程度应该是,但我找不到任何东西。

当然,我可以循环遍历字典并使用 nt.assert_almost_equal 来单独比较值;然而,在我的例子中,字典更复杂,所以我希望避免这种情况。

断言两个字典几乎相等的最佳方法是什么?

最佳答案

@dano 的评论回答了我的问题:

我从 link provided by dano 复制了一个函数

import unittest
import numpy

def assertDeepAlmostEqual(test_case, expected, actual, *args, **kwargs):
"""
Assert that two complex structures have almost equal contents.

Compares lists, dicts and tuples recursively. Checks numeric values
using test_case's :py:meth:`unittest.TestCase.assertAlmostEqual` and
checks all other values with :py:meth:`unittest.TestCase.assertEqual`.
Accepts additional positional and keyword arguments and pass those
intact to assertAlmostEqual() (that's how you specify comparison
precision).

:param test_case: TestCase object on which we can call all of the basic
'assert' methods.
:type test_case: :py:class:`unittest.TestCase` object
"""
is_root = not '__trace' in kwargs
trace = kwargs.pop('__trace', 'ROOT')
try:
if isinstance(expected, (int, float, long, complex)):
test_case.assertAlmostEqual(expected, actual, *args, **kwargs)
elif isinstance(expected, (list, tuple, numpy.ndarray)):
test_case.assertEqual(len(expected), len(actual))
for index in xrange(len(expected)):
v1, v2 = expected[index], actual[index]
assertDeepAlmostEqual(test_case, v1, v2,
__trace=repr(index), *args, **kwargs)
elif isinstance(expected, dict):
test_case.assertEqual(set(expected), set(actual))
for key in expected:
assertDeepAlmostEqual(test_case, expected[key], actual[key],
__trace=repr(key), *args, **kwargs)
else:
test_case.assertEqual(expected, actual)
except AssertionError as exc:
exc.__dict__.setdefault('traces', []).append(trace)
if is_root:
trace = ' -> '.join(reversed(exc.traces))
exc = AssertionError("%s\nTRACE: %s" % (exc.message, trace))
raise exc

# My part, using the function

class TestMyClass(unittest.TestCase):
def test_dicts(self):
assertDeepAlmostEqual(self, {'a' : 12.4}, {'a' : 5.6 + 6.8})
def test_dicts_2(self):
dict_1 = {'a' : {'b' : [12.4, 0.3]}}
dict_2 = {'a' : {'b' : [5.6 + 6.8, 0.1 + 0.2]}}

assertDeepAlmostEqual(self, dict_1, dict_2)

def main():
unittest.main()

if __name__ == "__main__":
main()

结果:

Ran 2 tests in 0.000s

OK

关于python - 断言两个字典几乎相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23549419/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com