代码之家  ›  专栏  ›  技术社区  ›  bohrax

python:为什么unittest断言equal会在这些列表中引发错误而不是失败?

  •  1
  • bohrax  · 技术社区  · 7 年前

    python 2.7和3.4:为什么 test_unexpected_error 测试抛出错误而不是失败?

    import unittest
    
    
    class TestLists(unittest.TestCase):
    
        def test_unexpected_error(self):
            self.assertEqual([0] * 1000 + [1], [1] + [0] * 1000)
    
        def test_fails_as_expected(self):
            self.assertEqual([0] * 1000 + [1], [0] * 1000 + [0])
    
    
    if __name__ == '__main__':
        unittest.main()
    

    错误是:

    RuntimeError: maximum recursion depth exceeded while calling a Python object
    

    回溯(节略-递归错误是递归错误是递归错误是递归错误是….)

    Traceback (most recent call last):
      File "sotest.py", line 7, in test_unexpected_error
        self.assertEquals([0] * 1000 + [1], [1] + [0] * 1000)
      File "/usr/lib/python2.7/unittest/case.py", line 513, in assertEqual
        assertion_func(first, second, msg=msg)
      File "/usr/lib/python2.7/unittest/case.py", line 743, in assertListEqual
        self.assertSequenceEqual(list1, list2, msg, seq_type=list)
      File "/usr/lib/python2.7/unittest/case.py", line 722, in assertSequenceEqual
        pprint.pformat(seq2).splitlines()))
      File "/usr/lib/python2.7/difflib.py", line 920, in compare
        for line in g:
      File "/usr/lib/python2.7/difflib.py", line 1038, in _fancy_replace
        for line in self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi):
      File "/usr/lib/python2.7/difflib.py", line 1051, in _fancy_helper
        for line in g:
      File "/usr/lib/python2.7/difflib.py", line 1038, in _fancy_replace
        for line in self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi):
      File "/usr/lib/python2.7/difflib.py", line 1051, in _fancy_helper
        for line in g:
      File "/usr/lib/python2.7/difflib.py", line 1038, in _fancy_replace
        for line in self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi):
      File "/usr/lib/python2.7/difflib.py", line 1051, in _fancy_helper
        for line in g:
    
    (...)
    
      File "/usr/lib/python2.7/difflib.py", line 965, in _fancy_replace
        cruncher = SequenceMatcher(self.charjunk)
      File "/usr/lib/python2.7/difflib.py", line 219, in __init__
        self.set_seqs(a, b)
      File "/usr/lib/python2.7/difflib.py", line 231, in set_seqs
        self.set_seq2(b)
      File "/usr/lib/python2.7/difflib.py", line 285, in set_seq2
        self.__chain_b()
      File "/usr/lib/python2.7/difflib.py", line 318, in __chain_b
        for i, elt in enumerate(b):
    RuntimeError: maximum recursion depth exceeded while calling a Python object
    
    1 回复  |  直到 7 年前
        1
  •  5
  •   moebius    7 年前

    这似乎是一个已知的 bug .

    如果不希望单元测试在失败时显示列表之间的差异,可以执行此备用测试:

    self.assertTrue([0] * 1000 + [1] == [1] + [0] * 1000)