抛出ValueError未通过单元测试



我正在尝试使用下面的代码在值为负数时引发值错误。

添加了一个raise错误:number应该大于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

我得到的错误如下。我可以在下面看到,我的raise值通过了,但不知何故,测试类没有考虑它。

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扩展您的测试,以不同的方式处理正值和非正值。

class TestCalc(unittest.TestCase):
def test_factorial(self):
print('Function is starting to check for values')
print()
if n < 0:
with self.assertRaises(ValueError) as context:
calculate_factorial(n)
self.assertEqual('number should be greater than 0', str(context.exception))
else:
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)

但是,对于不同的值范围/类型使用固定的值进行不同的测试可能会更好:

class TestCalcFixedValues(unittest.TestCase):
def test_factorial_positive(self):
self.assertEqual(calculate_factorial(42), math.factorial(42))
def test_factorial_negative(self):
with self.assertRaises(ValueError) as context:
calculate_factorial(-42)
self.assertEqual('number should be greater than 0', str(context.exception))
def test_factorial_NaN(self):
with self.assertRaises(TypeError) as context:
calculate_factorial("NaN")
self.assertEqual('number should be an integer type', str(context.exception))

(然后你会看到,calculate_factorial有一个bug;))

最新更新