<span style="font-family: 微軟雅黑; widows: auto; background-color: rgb(255, 255, 255);">這兩天在網上找關於Python的unittest框架的數據驅動,一直沒有找到一個比較詳細的資料,在這裏就自己寫一個啦。。。</span>
import xlrd
class ExcelUtil(object):
def __init__(self, excelPath, sheetName):
self.data = xlrd.open_workbook(excelPath)
self.table = self.data.sheet_by_name(sheetName)
#get titles
self.row = self.table.row_values(0)
#get rows number
self.rowNum = self.table.nrows
#get columns number
self.colNum = self.table.ncols
#the current column
self.curRowNo = 1
def next(self):
r = []
while self.hasNext():
s = {}
col = self.table.row_values(self.curRowNo)
i = self.colNum
for x in range(i):
s[self.row[x]] = col[x]
r.append(s)
self.curRowNo += 1
return r
def hasNext(self):
if self.rowNum == 0 or self.rowNum <= self.curRowNo :
return False
else:
return True
4.在unittest框架中使用ddt進行迭代import unittest
import ddt
from driver.ExcelUtil import ExcelUtil
excel = ExcelUtil('excelPath', 'Sheet1')
@ddt.ddt
class DataTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
print('start')
@classmethod
def tearDownClass(cls):
print('stop')
@ddt.data(*excel.next())
def testLogin(self, data):
print(data['username'])
print(data['password'])
print(data['country'])
if __name__ == "__main__":
suite = unittest.TestLoader().loadTestsFromTestCase(DataTest)
unittest.TextTestRunner(verbosity=2).run(suite)
username | password | country |
a | 1 | CH |
b | 2 | USA |
Importing test modules ... done.
start
a
1.0
CH
----------------------
b
2.0
USA
----------------------
stop
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK