简体   繁体   中英

How can I raise this exception properly?

How can I raise this exception properly?

import unittest

def second_digit_value4(n): return True if n % 10 == 4 else False

class DigitValue4(unittest.TestCase):
    def test_last_digit_value4(self):
        self.assertEqual(second_digit_value4(14), True)
        self.assertFalse(second_digit_value4(22), False)

        with self.assertRaises(ValueError):
            second_digit_value4(23)

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

Since the function only works correctly for positive numbers with 2 digits, it should check that the parameter is between 10 and 99. Then you should test it with a number outside that range.

import unittest

def second_digit_value4(n): 
    if 10 <= n <= 99:
        return n % 10 == 4
    raise ValueError("number must be 2 digits")

class DigitValue4(unittest.TestCase):
    def test_last_digit_value4(self):
        self.assertEqual(second_digit_value4(14), True)
        self.assertFalse(second_digit_value4(22), False)

        with self.assertRaises(ValueError):
            second_digit_value4(123)

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

Unit tests don't need to throw an error. They check if things are true or false and depending on the result, the test either passes or it fails.

Modify your test to:

assertTrue(second_digit_value4(14), 'second_digit_value4 failed on 14')
assertFalse(second_digit_value4(22), 'second_digit_value4 failed on 22')

Exceptions are used to handle "unexpected" circumstances. You can modify your function to:

def second_digit_value4(n): 
if not n.isnumeric():
    raise ValueError("value must be a number")
if 10 <= n <= 99:
    return n % 10 == 4
else:
    raise ValueError("value out of range")

Then to check if the exception is thrown:

def test1(self):
    with self.assertRaises(ValueError):
       second_digit_value4('This is NaN')

You can add another test for the out of range exception.

What this does is it allows your function to return without performing the operation and returning the result, which would be impossible on that input.

Alternatively you can just return a NaN and not throw.

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