一、首先安装dtt模块
数据驱动原理
1.测试数据为多个字典的list类型
2.测试类前加修饰@ddt.ddt
3.case前加修饰@ddt.data()
4.运行后用例会自动加载成N个单独的用例
二、实例
ExcellData.py
1 # coding:utf-8 2 import xlrd 3 4 5 class excel: 6 def __init__(self): 7 self.test_data_path = 'F:\testdata.xlsx' 8 9 def open_excel(self,file): 10 u'''读取excel文件''' 11 try: 12 data = xlrd.open_workbook(file) 13 return data 14 except Exception, e: 15 raise e 16 17 def excel_table(self,file, sheetName): 18 u'''装载list''' 19 data = self.open_excel(file) 20 # 通过工作表名称,获取到一个工作表 21 table = data.sheet_by_name(sheetName) 22 # 获取行数 23 Trows = table.nrows 24 # 获取 第一行数据 25 Tcolnames = table.row_values(0) 26 lister = [] 27 for rownumber in range(1,Trows): 28 row = table.row_values(rownumber) 29 if row: 30 app = {} 31 for i in range(len(Tcolnames)): 32 app[Tcolnames[i]] = row[i] 33 lister.append(app) 34 return lister 35 36 def get_list(self,sheetname): 37 try: 38 data_list = self.excel_table(self.test_data_path, sheetname) 39 assert len(data_list)>=0,u'excel标签页:'+sheetname+u'为空' 40 return data_list 41 except Exception as e: 42 raise e
test.py
1 # coding:utf-8 2 __author__ = 'Helen' 3 ''' 4 project:ddt数据驱动 5 ''' 6 import unittest,ddt 7 from ExcelData import excel 8 9 # 测试数据 10 excel_data = excel() 11 testdata = excel_data.get_list('userData') 12 13 @ddt.ddt 14 class TestDtt(unittest.TestCase): 15 @classmethod 16 def setUpClass(cls): 17 print u'开始测试---------------' 18 19 @ddt.data(*testdata) 20 def test(self, data): 21 print 'username:'+data['username']+',password:'+data['password'] 22 23 @classmethod 24 def tearDownClass(cls): 25 print u'结束测试------------------' 26 27 if __name__=='__main__': 28 unittest.main()