Python unittest excel数据驱动
<span style="font-family: 微软雅黑; widows: auto; background-color: rgb(255, 255, 255);">这两天在网上找关于Python的unittest框架的数据驱动,一直没有找到一个比较详细的资料,在这里就自己写一个啦。。。</span>1. 首先安装ddt,ddt可以实现多数据的处理
C:\windows\system32>pip install wheel
You are using pip version 6.0.8, however version 6.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Collecting wheel
Downloading wheel-0.24.0-py2.py3-none-any.whl (63kB)
100% |################################| 65kB 476kB/s
Installing collected packages: wheel
Successfully installed wheel-0.24.0
C:\windows\system32>pip install C:\Users\***\Downloads\ddt-1.0.0-py2.py3-none-
any.whl
You are using pip version 6.0.8, however version 6.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Processing c:\users\***\downloads\ddt-1.0.0-py2.py3-none-any.whl
Installing collected packages: ddt
Successfully installed ddt-1.0.0
2.安装xlrd,excel处理包
下载链接http://pypi.python.org/pypi/xlrd
3.对excel数据进行处理,这个类主要是将excel中所有的数据封装成一个数据,数组里面append所有列的dic,代码如下:
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] = col
r.append(s)
self.curRowNo += 1
return r
def hasNext(self):
if self.rowNum == 0 or self.rowNum <= self.curRowNo :
return False
else:
return True4.在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)
@ddt.data接收一个可迭代的类型,来判断执行的次数,excel.next()返回的是一个数组
excel数据如下
username
password
country
a
1
CH
b
2
USA
执行结果:
Finding files... done.
Importing test modules ... done.
start
a
1.0
CH
----------------------
b
2.0
USA
----------------------
stop
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK
版权声明:本文为博主原创文章,未经博主允许不得转载。
页:
[1]