Python學習筆記8-單元測試(1)

來源:互聯網
上載者:User

標籤:

 

 原始碼:

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)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.