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