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

posted @ 2015-05-20 16:56  summerlong  阅读(242)  评论(0编辑  收藏  举报