• Python学习笔记8-单元测试(1)


     源代码:

    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 += numeral
    			n -= integer
    			#print('subtracting {0} from input, adding {1} to output'.format(integer,numeral))
    
    	return result
    
    class OutOfRangeError(ValueError):
    	pass
    	
    

    单元测试代码:

    import roman1
    import unittest
    
    
    class 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模块会打印出详细跟踪信息。

  • 相关阅读:
    vue使用talkIngData统计
    vue项目中使用百度统计
    vue的指令修饰符
    提问:
    整理心情再投入下一个阶段
    CSS写三角形
    单行文本和多行文本超出隐藏
    清除浮动的方法
    用JS表示斐波拉契数列
    vue中使用动态挂载和懒加载,实现点击导航栏菜单弹出不同弹框
  • 原文地址:https://www.cnblogs.com/summerlong/p/4517561.html
Copyright © 2020-2023  润新知