assertRaises没有捕获错误

时间:2011-11-23 10:51:37

标签: python unit-testing

我有这个脚本

import unittest,itertools,random

##testclass
class Testcomb(unittest.TestCase):

     def test_input(self):
        self.assertRaises(TypeError,calculate_combinations,dict(comb1), 5)

def calculate_combinations(combin,target):
    counter = 0
    for L in range(0, len(combin)+1):
      for subset in itertools.combinations(combin, L):
        if sum(subset) == target: counter= counter+1
    return counter

comb1=[1,2,3,4]


if __name__=='__main__': unittest.main()

但是self.assertRaises(TypeError,calculate_combinations,dict(comb1), 5)没有拦截异常,但却给出了这个错误:

E..
======================================================================
ERROR: test_input (__main__.Testcomb)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "total_combination.py", line 25, in test_input
    self.assertRaises(TypeError,calculate_combinations,dict(comb1), 5)
TypeError: cannot convert dictionary update sequence element #0 to a sequence

----------------------------------------------------------------------
Ran 3 tests in 0.000s

FAILED (errors=1)

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

使测试失败的异常由断言的dict(comb1)部分触发。

>>> comb1=[1,2,3,4]
>>> dict(comb1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot convert dictionary update sequence element #0 to a sequence

相反,assertRaises只有在可调用(在您的情况下为True)才能触发calculate_combinations时才会返回{{1}}。

HTH!