Raise ValueError 没有通过单元测试

Raise ValueError not getting through unit test

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

添加了一个引发错误:number should be greater than 0 But when I 运行 the code below:

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

我收到如下错误。我可以在下面看到我的加薪值正在通过,但不知何故测试 class 没有考虑它。

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)

但是,最好对不同的值 ranges/kinds 进行不同的测试,固定值如下:

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 有一个错误;))