Source:
Roman_mumeral_map = ((' M ', +), (' CM ', ' n '), (' D ', ' X '), (' CD ', "X"), (' C ', ' X '), (' XC ', ' n '), (' L ', '), (' XL ', ' 10 '), (' IX ', 9), (' V ', 5), (' IV ', 4), (' I ', 1)) def To_roman (n): ' Convert integer to roman numeral "if not (0 < n < 4000): Rais E Outofrangeerror (' number out of range ' must is less than 4000 ') result = "For numeral, integer in Roman_mumeral_map:while n >= integer:result + = numeraln-= Integer#print (' subtracting {0} from input, adding {1} to output '. Format (integer,num eral)) return ResultClass outofrangeerror (valueerror):p
Unit Test Code:
Import Roman1import unittestclass knownvalue (unittest. TestCase): "" "DocString for Knownvalue" "" "Known_values = ((1, ' I '), (2, ' II '), (3, ' III '), (3888, ' MMMDCCCLXXXVIII '), (3999, ' Mmmcmxcix ') def test_to_roma_konwn_values (self): "To_roman should give known result with known input" ' for Integer, Nu Meral in Self.known_values:result = Roman1.to_roman (integer) self.assertequal (Numeral,result) class Toromanbadinput ( UnitTest. TestCase):d EF test_too_large (self): "To_romam should fail with large input" self.assertraises (roman1. outofrangeerror,roman1.to_roman,4000) def test_zero (self): "To_roman should fail with 0 iput" ' self.assertraises ( Roman1. outofrangeerror,roman1.to_roman,0) def test_negative (self): "To_roman should fail with negtive input" Self.assertraises (Roman1. Outofrangeerror, Roman1.to_roman,-1) if __name__ = = ' __main__ ': Unittest.main ()
Class Knownvalue (UnitTest. TestCase):--Let the test case be called a subclass of the TestCase class under the UnitTest module.
The TestCase class provides the Assertequal () method to check whether two values are equal.
Each class method in the module is a test case that requires inheriting the TestCase class
For each test case, the UnitTest module prints out the docstring for each test case and indicates whether the test case failed or succeeded. For each failed test case, the UnitTest module prints detailed tracking information.
Python Learning note 8-unit test (1)