python 2:
在python2里,用assert判断一个字典是否是另一个字典的子集并不能直接用in
, not in
,只能用set
的issubset
比较方法:
a = {'x': 1, 'y': 2, 'z': 3}
b = {'x': 1}
c = {'y': 2, 'd': 3}
assert six.viewitems(b) in six.viewitems(a)
# 直接比较会出错
"""
Traceback (most recent call last):
File "/home/python/Desktop/zxc/others/six_test.py", line 21, in <module>
assert six.viewitems(b) in six.viewitems(a)
AssertionError
"""
# 可以用:
assert set(six.viewitems(b)).issubset(set(six.viewitems(a)))
unittest的assert:
a = {'x': 1, 'y': 2, 'z': 3}
b = {'x': 1}
c = {'y': 2, 'd': 3}
class TestZ(unittest.TestCase):
def test_compare(self):
print six.viewitems(a)
print six.viewitems(b)
# self.assertTrue(set(six.viewitems(b)).issubset(six.viewitems(a)))
self.assertFalse(set(six.viewitems(c)).issubset(six.viewitems(a)))
if __name__ == '__main__':
unittest.main()
网友评论