简体   繁体   中英

Why is this code raising an AssertionError?

This is the code.

# mean_var_std.py

def calculate(list):
    try:
        if len(list) < 9:
            raise ValueError
        else:
            return 0
    
    except ValueError:
        print("List must contain nine numbers.")

This is the test.

import unittest
import mean_var_std


# the test case
class UnitTests(unittest.TestCase):
    def test_calculate_with_few_digits(self):
        self.assertRaisesRegex(ValueError, "List must contain nine numbers.", mean_var_std.calculate, [2,6,2,8,4,0,1,])

if __name__ == "__main__":
    unittest.main()

When I run it, I get the following output:

F
======================================================================
FAIL: test_calculate_with_few_digits (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/fcc-mean-var-std-2/test_module.py", line 8, in test_calculate_with_few_digits
    self.assertRaisesRegex(ValueError, "List must contain nine numbers.", mean_var_std.calculate, [2,6,2,8,4,0,1,])
AssertionError: ValueError not raised by calculate

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)

The output says that the code isn't raising a ValueError, but from the code we can clearly see that the code raises a ValueError. Why is my code still failing the unittest?

It's because you catch the ValueError before the test can receive it. Remove the try catch and it should work

# mean_var_std.py

def calculate(list):
    if len(list) < 9:
        print("List must contain nine numbers.")
        raise ValueError
    else:
        return 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM