做接口測試的時候,當一個參數需要輸入多個值的時候,就可以使用參數來實現;
python中unittest單元測試,可以使用nose_parameterized來實現;
首先需要安裝:pip install nose-parameterized,導入該模塊;
看下面的例子,一般我們寫測試用例的時候會追條定義一個test*()的方法,然后執行所有測試用例,如下:
import unittest
def calc(a,b):
res=a+b
return res
class MyTest(unittest.TestCase):
def test1(self):
res=calc(1,2)
self.assertEqual(res,3)
def test2(self):
res=calc(0,0)
self.assertEqual(0,0)
if __name__ == '__main__':
unittest.main()
執行查看結果:
當傳入的值類型相同,我們可以用讀取list的方式,進行參數化,自動調用執行,如下:
import unittest
import nose_parameterized
def calc(a,b):
res=a+b
return res
data=[
[1,2,3],
[0,0,0],
[9999,0,9999]
]
class MyTest(unittest.TestCase):
#參數化,自動的運行list里邊的數據
@nose_parameterized.parameterized.expand(data)
def test1(self,a,b,e):
res=calc(a,b)
self.assertEqual(res,e)
if __name__ == '__main__':
unittest.main()
上述我們只需要定義一個測試用例方法,使用parameterized方法自動運行data里邊的數據,查看執行結果,看到執行了三次:
還可以通過調用文件的方式來進行unittest參數化;如果測試數據存在於文件中,首先我們需要定義一個將文件轉化成list的方法,我們可以根據文件的不同類型使用不同的方法,封裝一個tool模塊,定義DataToParam類
import os
import xlrd
class DataToParam(object):
def file_exist(self,filename):
if os.path.isfile(filename):
return True
else:
raise Exception('參數化文件不存在')
def text(self,filename):
if self.file_exist(filename):
with open(filename,'r',encoding='utf-8') as f:
list=[]
for line in f :
list.append(line.strip().split(','))
return list
def excel(self,filename):
if self.file_exist(filename):
book=xlrd.open_workbook(filename)
sheet=book.sheet_by_index(0)
rows=sheet.nrows
list=[]
for row in range(rows):
list.append(sheet.row_values(row))
return list
調用DataToParam中的函數,將文件轉化成list
文件:
import unittest
from tool import DateToParam
import nose_parameterized
def calc(a,b):
res=a+b
return res
class MyTest(unittest.TestCase):
#參數化,自動的運行list里邊的數
@nose_parameterized.parameterized.expand(DateToParam.excel(r'C:\test\test.xlsx'))
def test_func(self,a,b,e):
e=float(e)
res=calc(a,b)
self.assertEqual(res,e)
if __name__ == '__main__':
unittest.main()
執行查看結果: