gpt4 book ai didi

python - assertRaises 不捕获错误

转载 作者:太空宇宙 更新时间:2023-11-04 01:37:44 24 4
gpt4 key购买 nike

我有这个脚本

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)

有人能帮忙吗?

最佳答案

导致测试失败的异常是由断言的 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)以触发它时。

喂!

关于python - assertRaises 不捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8240901/

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