未通过单元测试的Raise VALUE错误

2024-09-25 00:33:07 发布

您现在位置:Python中文网/ 问答频道 /正文

当值为负值时,我尝试使用下面的代码进行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)

Tags: intestimportnumberdatamain错误be
1条回答
网友
1楼 · 发布于 2024-09-25 00:33:07

正如我在评论中已经提到的,您的测试失败,因为这里不需要引发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;)

相关问题 更多 >