- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我试图断言两个词典几乎相等,但我似乎做不到。
这是一个例子:
>>> 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/
也许我在 Java 上工作的时间太长而没有真正理解它的一些基础知识。 我确实理解 == 用于对象引用相等,而 .equals() 用于对象值相等。 比较整数: Integer x = 1, y = 1
我是从一道考试题中得出这个答案的,但无法理解该解决方案的工作原理。如果值“x”和“y”相等,则此函数应该返回“true”,否则返回 False。 解决方法: function equal_boolea
我将带有表情符号的文本存储在 mysql 数据库中。 数据库、表和列设置为使用utf8mb4和utf8mb4_unicode_ci。 我可以毫无问题地输入单元格值(数据类型是 VARCHAR)。 但是
如果两个 DateTime 对象具有相同的日、月和年,我该如何比较?问题是他们有不同的小时/分钟/秒。 最佳答案 对于 DateTime 对象,没有好的方法可以做到这一点。所以你必须做,比方说,不是那
我一直想知道这个问题,所以我想我会问的。 您将看到的大多数地方都使用相同的语义逻辑来覆盖 Equals 和 GetHashCode 以实现成员平等...但是它们通常使用不同的实现: publi
苹果 CoreGraphics.framework , CGGeometry.h : CG_INLINE bool __CGSizeEqualToSize(CGSize size1, CGSize s
在最新的python 版本中, dict 保留了插入的顺序。在平等方面是否有任何变化。例如,目前以下工作。既然广告顺序很重要, future 会不会发生这种变化? 我问是因为有根本性的变化 - 以前
class VideoUserModel(models.Model): user = models.ManyToManyField(get_user_model()) viewlist
我在 COQ 中有一个有限枚举类型(比如 T),我想检查元素是否相等。这意味着,我需要一个函数 bool beq_T(x:T,y:T) 我设法定义这样一个函数的唯一方法是逐个分析。这会导致很多匹配语
我在 Windows 7(32 位)下的 MinGW 中使用 gfortran 来编译 Fortran 代码。这是文件 testequal.f 中包含的最少代码: program test
我有以下 jsp 片段: ${campaign.moderated}
我想检查两个稀疏数组是否(几乎)相等。而对于 numpy 数组,你可以这样做: import numpy as np a = np.ones(200) np.testing.assert_array_
我有以下类(class): public class MyDocuments { public DateTime registeredDate; public
这个问题已经有答案了: Is floating point math broken? (33 个回答) 已关闭 5 年前。 我在这里想做的是,我采用一个精度值(小于 1)并打印 1/n 类型的所有数字
我正在为我的arduino写一个草图,我想检查我的字符串的最后一个字符。 例如: 如果输入是 cats- 我想看看最后一个字符(在我的例子中是“-”)实际上是否 - 我使用的代码: 串行事件函数 vo
让我们开始: using System; public class Program { class A { public virtual void Do() { }
我只需要根据几个键(不是全部)来确定两个 HashMap 的相等性 除了单独访问每个字段并比较相等性之外,还有其他节省时间的方法吗? 最佳答案 我能想到的一种方法是在您的 HashMap 上存储某种“
在Java中,大写的Double可以为null。 但是如果我有 double a 和 b 并且我这样做: if (a.equals(b)) 如果其中之一为空,它会崩溃。有没有更好的方法来比较它们? 最
我正在尝试从我的旧数据库中插入表格数据。 Id 在数据库表和选择特定列中都相等。这是我的数据库。 旧数据库:sch -> 旧表:product (id, tag, url) (13, red, aaa
我正在开发一个应用程序,它在我的主视图中有一个侧边栏和两个 div。我试图在容器内平均分割两者的高度。我试过 height = 50% 但效果不太好。
我是一名优秀的程序员,十分优秀!