当值为负值时,我尝试使用下面的代码进行UnitTest以引发值错误
添加了一个raise错误:数字应大于0,但当我运行以下代码时:
from functools import reduce
import math
import unittest
def calculate_factorial(number):
if number < 0:
print('about to throw value error')
raise ValueError('number should be greater than 0')
elif type(number) != int:
raise TypeError('number should be an integer type')
else:
data = []
for i in range(number):
data.append(number - i)
print(data)
results = reduce((lambda x, y: x * y), data, 1)
return results
class TestCalc(unittest.TestCase):
def test_factorial(self):
print('Function is starting to check for values')
print()
result = calculate_factorial(n)
print('results are:',result)
print()
self.assertEqual(result,math.factorial(n))
def test_n(self):
print('The value of n taken by the class function is:',n)
run = True
while run:
n = int(input('Enter an integer value: '))
if n != -9999:
unittest.main(argv=[''], verbosity=2, exit=False)
else:
run = False
我得到的错误如下。我可以在下面看到,我的提升值已经通过了,但不知何故,测试类并没有考虑它
test_factorial (__main__.TestCalc) ... ERROR
test_n (__main__.TestCalc) ... ok
======================================================================
ERROR: test_factorial (__main__.TestCalc)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<ipython-input-3-d89c3d44c70d>", line 5, in test_factorial
result = calculate_factorial(n)
File "<ipython-input-2-2ad930b1e911>", line 5, in calculate_factorial
raise ValueError('number should be greater than 0')
ValueError: number should be greater than 0
----------------------------------------------------------------------
Ran 2 tests in 0.010s
FAILED (errors=1)
正如我在评论中已经提到的,您的测试失败,因为这里不需要引发
ValueError
。 您可以使用if
扩展测试,以不同方式处理正值和非正值但是,最好对不同的值范围/类型进行不同的测试,固定值如下:
(然后您将看到,
calculate_factorial
有一个bug;)相关问题 更多 >
编程相关推荐