当前位置: 首页 > 工具软件 > PyUnit > 使用案例 >

pyunit扩展:根据标签自动选择需要执行的用例

申博厚
2023-12-01

http://blog.csdn.net/tillfall/article/details/38355169一文中介绍了通过配置文件集中定义需要执行的用例。


但是静态的定义并不方便,比如新增用例要加入到用例执行列表中,环境的变化要调整用例......


通过标签来定义用例的执行属性,让pyunit在执行时动态选择用例来得更加灵活:


#rules in this run
#use :: to be replaced in logical formula
rule = '(None::) or (not (1::) and ((2::) or ("three"::)))'

def matchrule(tags):
	if isinstance(tags, tuple):
		matchformula = rule.replace('::', ' in ' + str(tags))
	elif None == tags:
		matchformula = rule.replace('::', ' == None')
	elif isinstance(tags, str):
		matchformula = rule.replace('::', ' == "' + tags + '"')
	else:
		matchformula = rule.replace('::', ' == ' + str(tags))

	#log.d(matchformula)
	return eval(matchformula)
	
def tag(tags = None):
	def tag_func(func):
		def _(*args, **kwds):
			if matchrule(tags):
				func(*args, **kwds)
			else:
				args[0].skipTest(tags)
		return _
	return tag_func
	
class test1(TestCase):
	@tag()	#match None
	def testaaa(self):
		print 'aaa'
	@tag(1)	#not match
	def testbbb(self):
		print 'bbb'
	@tag(2)	#match 2
	def testccc(self):
		print 'ccc'
class test2(TestCase):
	@tag((1, 2))	#not match 1
	def testddd(self):
		print 'ddd'
	@tag((2, 3))	#match 2
	def testeee(self):
		print 'eee'
	@tag((4, "three"))	#match three
	def testfff(self):
		print 'fff'

执行结果如下:

aaa
.sccc
.seee
.fff
.
--------------
Ran 6 tests in
OK (skipped=2)

跳过了testbbb和testddd

 类似资料: