Search⌘ K

More Halting, More Fire

Explore how to enhance your unit testing in Python by adding tests for invalid inputs such as zero and negative numbers when converting to Roman numerals. Understand how to catch exceptions using assertRaises, update your code conditions for input validation, and ensure your tests accurately reflect these scenarios for reliable error handling.

We'll cover the following...

Along with testing numbers that are too large, you need to test numbers that are too small. As we noted in our functional requirements, Roman numerals cannot express 0 or negative numbers.

Python 3.5
import roman2
print (roman2.to_roman(0))
#''
print (roman2.to_roman(-1))
#''

Well that’s not good. Let’s add tests for each of these conditions.

Python 3.5
import unittest
class ToRomanBadInput(unittest.TestCase):
def test_too_large(self):
'''to_roman should fail with large input'''
self.assertRaises(roman3.OutOfRangeError, roman3.to_roman, 4000) #①
def test_zero(self):
'''to_roman should fail with 0 input'''
self.assertRaises(roman3.OutOfRangeError, roman3.to_roman, 0) #②
def test_negative(self):
'''to_roman should fail with negative input'''
self.assertRaises(roman3.OutOfRangeError, roman3.to_roman, -1) #③

① The test_too_large() ...