標籤:
原始碼:
roman_mumeral_map = ((‘M‘,1000),(‘CM‘,900),(‘D‘,500),(‘CD‘,400),(‘C‘,100),(‘XC‘,90),(‘L‘,50),(‘XL‘,40),(‘X‘,10),(‘IX‘,9),(‘V‘,5),(‘IV‘,4),(‘I‘,1))def to_roman(n):‘‘‘ convert integer to Roman numeral ‘‘‘if not (0 < n < 4000):raise OutOfRangeError(‘number out of range (must be 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,numeral))return resultclass OutOfRangeError(ValueError):pass
單元測試代碼:
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, numeral in self.known_values:result = roman1.to_roman(integer)self.assertEqual(numeral,result)class ToRomanBadInput(unittest.TestCase):def 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): -- 讓該測試案例稱為unittest模組下TestCase類的子類。
TestCase類提供了assertEqual()方法來檢查兩個值是否相等.
該模組中的每一個類方法都是一個測試案例,需要繼承TestCase類
對於每一個測試案例,unittest模組會列印出每個測試案例的docstring,並說明該測試案例是失敗還是成功。對於每一個失敗的測試案例,unittest模組會列印出詳細跟蹤資訊。
Python學習筆記8-單元測試(1)