数据与脚本分离是测试自动化的一大进步。在相同逻辑对应多组数据的情况下,采用测试驱动测试DDT的方式能更高效、简洁的开发自动化测试用例。
框架扩展:
class DataDrivenTestCase(TestCase):
def gettestdata(self, key):
return self.testdata[key]
def run(self, result=None):
#run once for every test data
#eg. there are three times for loginok, loginfail, loginerror
for self.testdata_name_inrun in testdata[self._testMethodName].keys():
self.testdata = testdata[self._testMethodName][self.testdata_name_inrun]
super(DataDrivenTestCase, self).run(result)
class DataDrivenTestResult(TextTestResult):
def printErrorList(self, flavour, errors):
for test, err in errors:
self.stream.writeln(self.separator1)
#print test data name for failed result
self.stream.writeln("%s: %s: %s" % (flavour,self.getDescription(test), test.testdata_name_inrun))
self.stream.writeln(self.separator2)
self.stream.writeln("%s" % err)
if __name__ == '__main__':
TestProgram(testRunner=TextTestRunner(resultclass=DataDrivenTestResult))
测试数据和脚本如下:
testdata = {'testaaa':{ #test method name
'loginok': #test data name
{'user':'admin','pwd':'admin'}, #test data key, test data value
'loginfail':{'user':'user','pwd':'wrong'},
'loginerror':{'user':'guest','pwd':'error'},
},
'testbbb':{
'click':{'target':'button'},
'touch':{'target':'screen'},
}
}
class test1(DataDrivenTestCase):
def testaaa(self):
print self.gettestdata('user')
if self.gettestdata('pwd') == 'wrong':
fail('wrong pwd')
def testbbb(self):
print self.gettestdata('target')
if self.gettestdata('target') == 'screen':
fail('do not support screen')
则testaaa对应三组数据,testbbb对应两组数据,框架将自动为数据扩展用例,执行结果如下:
guest
.admin
.user
Escreen
Ebutton
.
=============================================
ERROR: testaaa (__main__.test1): loginfail
---------------------------------------------
Traceback (most recent call last):
File "a.py", line 117, in testaaa
fail('wrong pwd')
NameError: global name 'fail' is not defined
=============================================
ERROR: testbbb (__main__.test1): click
---------------------------------------------
Traceback (most recent call last):
File "a.py", line 122, in testbbb
fail('do not support screen')
NameError: global name 'fail' is not defined
---------------------------------------------
Ran 5 tests in 0.005s
FAILED (errors=2)