写这篇笔记的初心是为了Python+unittest+requests+HTMLTestRunner完整的接口自动化测试框架搭建——参数动态化
import unittest
from parameterized import parameterized
"""
目标:parameterized 插件应用
步骤:
1. 导包 from parameterized import parameterized
2. 修饰测试函数 @parmeterized.expand(列表类型数据)
3. 在测试函数中使用变量接收,传递过来的值。
语法:
1. 单个参数:值为列表
2. 多个参数:值为列表嵌套元组 如:[(1,2,3),(2,3,4)]
"""
# 定义测试类 并 继承
class Test01(unittest.TestCase):
# 单个参数使用方法
# @parameterized.expand(["1", "2", "3"])
# def test_add_one(self, num):
# print("num:", num)
# 多个参数使用方法 写法1
# @parameterized.expand([(1, 2, 3), (3, 0, 3), (2, 1, 3)])
# def test_add_more(self, a, b, result):
# print("{}+{}={}:".format(a, b, result))
# data = [(1, 2, 3), (3, 0, 3), (2, 1, 3)]
# 写法2
# @parameterized.expand(data)
# def test_add_more(self, a, b, result):
# print("{}+{}={}:".format(a, b, result))
# 写法 3 推荐
def get_data(self):
return [(1, 2, 3), (3, 0, 3), (2, 1, 3)]
@parameterized.expand(get_data())
def test_add_more(self, a, b, result):
print("{}+{}={}:".format(a, b, result))
由上面的代码可以看到UnitTest参数化时@parameterized.expand( )里面需要传入[(x,x,x),(x,x,x),(x,x,x)]类型的参数,我们在做接口自动化测试的时候可以把接口参数写在Excel里,然后定义get_data()函数来返回指定格式的数据来实现参数化。
一、读取一个没有表头的二维csv文件,并以元组的形式表现数据:
((1.0, 0.0, 3.0, 180.0), (2.0, 0.0, 2.0, 180.0), (3.0, 0.0, 1.0, 180.0), (4.0, 0.0, 0.0, 180.0), (5.0, 0.0, 3.0, 178.0)) :
使用python内建的数据处理库:
#python自带的库
rows = open( 'allnodes.csv','r',encoding='utf-8' ).readlines( )
lines = [ x.rstrip() for x in rows ]#去掉每行数据的/n转义字符
lines[0] = '1,0,3,180' #拿第一个值赋值一次,实现手动去掉第一行的csv开始符号
data = [] #使用列表读取是因为列表长度是可变的,而元组不可。
[data.append(eval(i)) for i in lines]#将每一行数据以子列表的形式加入到data中
print(allnodes)
out:[(1, 0, 3, 180), (2, 0, 2, 180), (3, 0, 1, 180), (4, 0, 0, 180), (5, 0, 3, 178), (6, 0, 2, 178), (7, 0, 1, 178), (8, 0, 0, 178),...,(29484, -40, 0, 0)]
二、读取Excel的数据使用下面的openpyxl库处理:
from openpyxl import load_workbook, Workbook
get_data(xlsx_file,sheet_name)
wb = load_workbook(xlsx_file) #加载Excel文件,如:test.xlsx
sheet = wb[sheet_name]
#print(sheet.max_row)
#print(sheet.max_column)
#print(type(sheet.values)) #<class 'generator'>
#sheet.values返回一个所有行数据的迭代对象,每次迭代都返回一行数据,这个数据是元组类型
data_tuple_list = []
for data in sheet.values:
#print(type(data)) #tuplel
if data[0]=='用户名': #跳过表头数据 ,data是每一行的所有列的值组成的元组:(第一列值,第二列值,第三列值)
continue
#print("用户名:%s 密码:%s"%(data[0],data[1]))
data_tuple_list.append(data)
print(data_tuple_list)
return data_tuple_list
运行结果: