赞
踩
a.数据结构
b.文件
c.数据库
d.conftest.py配置
@ pytest.mark.parametrize("参数", (参数值1, 参数值2, 参数值3))
示例:
import pytest
# 单个参数的情况
@pytest.mark.parametrize("a", (1, 2, 3, 4))
def test_add(a):
print("\na的值")
输出:
============================= test session starts ============================= collecting ... collected 4 items parametrize01.py::test_add[1] PASSED [ 25%] a的值 parametrize01.py::test_add[2] PASSED [ 50%] a的值 parametrize01.py::test_add[3] PASSED [ 75%] a的值 parametrize01.py::test_add[4] PASSED [100%] a的值 ============================== 4 passed in 0.04s ============================== Process finished with exit code 0
@ pytest.mark.parametrize("参数a, 参数b", ([a1, b1], [a2, b2], [a3, b3]))
示例:
@pytest.mark.parametrize("b,c,d", ([1, 2, 3], [4, 5, 6], [7, 8, 0]))
def test_add2(b, c, d):
print("\nb,c,d的值分别为:", f'{b},{c},{d}')
输出:
============================= test session starts ============================= collecting ... collected 3 items parametrize01.py::test_add2[1-2-3] PASSED [ 33%] b,c,d的值分别为: 1,2,3 parametrize01.py::test_add2[4-5-6] PASSED [ 66%] b,c,d的值分别为: 4,5,6 parametrize01.py::test_add2[7-8-0] PASSED [100%] b,c,d的值分别为: 7,8,0 ============================== 3 passed in 0.03s ============================== Process finished with exit code 0
示例:
import pytest # 单个参数的情况 data1 = [1, 2, 3, 4] @pytest.mark.parametrize("a", data1) def test_add(a): print('\na的值:', a) # 多个参数多个值得情况 data2 = [ (1, 2, 3), (4, 5, 6), (0, 8, 9) ] @pytest.mark.parametrize("a,b,c", data2) def test_add2(a, b, c): print('\na,b,c的值分别为:', f'{a},{b},{c}')
输出:
============================= test session starts ============================= collecting ... collected 7 items parametrize02_list.py::test_add[1] PASSED [ 14%] a的值: 1 parametrize02_list.py::test_add[2] PASSED [ 28%] a的值: 2 parametrize02_list.py::test_add[3] PASSED [ 42%] a的值: 3 parametrize02_list.py::test_add[4] PASSED [ 57%] a的值: 4 parametrize02_list.py::test_add2[1-2-3] PASSED [ 71%] a,b,c的值分别为: 1,2,3 parametrize02_list.py::test_add2[4-5-6] PASSED [ 85%] a,b,c的值分别为: 4,5,6 parametrize02_list.py::test_add2[0-8-9] PASSED [100%] a,b,c的值分别为: 0,8,9 ============================== 7 passed in 0.05s ============================== Process finished with exit code 0
列表的基本操作:列表读取,列表添加
# 试验1:列表操作 # 列表定义 list1 = ['physics', 'chemistry', 'english', 'artist'] list2 = [1, 2, 3, 4, 5] # 列表读取 # 方法1 for data in list1: print(data) # 方法2 for i in range(0, len(list2)): print(list2[i]) # 列表元素追加 list1.append('history') print(list1)
输出:
D:\ApiTest3\.venv\Scripts\python.exe D:\ApiTest3\Pytest_session\test_parametrize\list_test.py
physics
chemistry
english
artist
1
2
3
4
5
['physics', 'chemistry', 'english', 'artist', 'history']
Process finished with exit code 0
import pytest
userinfo = [
{"username": "小李", "password": "123456"},
{"username": "大白", "password": "894561"}
]
@pytest.mark.parametrize('info', userinfo)
def test_add(info):
print(info)
输出:
============================= test session starts =============================
collecting ... collected 2 items
parametrize03_dic.py::test_add[info0] PASSED [ 50%]{'username': '小李', 'password': '123456'}
parametrize03_dic.py::test_add[info1] PASSED [100%]{'username': '大白', 'password': '894561'}
============================== 2 passed in 0.03s ==============================
Process finished with exit code 0
关于字典的一些基本操作如下:字典键值的获取,字典元素的追加
# 试验2:数据字典操作 # 数据字典定义 userinfo = { "username": "钟无艳", "password": "54674567" } # 字典读取 # 方法1:读取key for key in userinfo.keys(): print(key) # 方法2:读取value for val in userinfo.values(): print(val) # 方法3:读取所有内容 for key in userinfo: print(key,userinfo[key]) # 方法4:读取键值对 for data in userinfo.items(): print(data) # 字典元素追加 userinfo["phone"] = '13855455444' print(userinfo)
输出:
D:\ApiTest3\.venv\Scripts\python.exe D:\ApiTest3\Pytest_session\test_parametrize\dic_test.py
username
password
钟无艳
54674567
username 钟无艳
password 54674567
('username', '钟无艳')
('password', '54674567')
{'username': '钟无艳', 'password': '54674567', 'phone': '13855455444'}
Process finished with exit code 0
# 元组形式:
import pytest
data1 = [(1, 2, 3), (4, 5, 6)]
@pytest.mark.parametrize("a,b,c", data1)
def test_case1(a, b, c):
print(a, b, c)
输出:
============================= test session starts =============================
collecting ... collected 2 items
parametrize04_tuple.py::test_case1[1-2-3] PASSED [ 50%]1 2 3
parametrize04_tuple.py::test_case1[4-5-6] PASSED [100%]4 5 6
============================== 2 passed in 0.03s ==============================
Process finished with exit code 0
有些数据是通过json文件来保存的,我们可以读取json文件的内容,然后将其转换为字典格式传参,下面讲一下如何从json文件读取参数。
大体分为以下四步
{ "item": [ { "request": { "url": "http://192.xxx.xxx18/Account/Login", "body": { "username": "lipan", "password": "E10ADC*********BE56E057F20F883E", "isRememberme": false, "validateCode": "" } }, "response": { "status": 1, "msg": "", "data": null, "datas": null, "errCode": 0 } } ] }
parametrize05_json.py
# json形式: import json import pytest import requests # 1 读取json文件 # 由于需要的数据在item下面一层级,所以在读取时,需要指定位置 def rade_json(): return json.load(open('interface.json', 'r'))['item'] # 通过pytest的parametrize参数化来使用read_json()里面的内容 @pytest.mark.parametrize('data', rade_json()) def test_json_login(data): # 通过requests来指定请求方法 r = requests.post( # 通过指定read_json()里面对应的url url=data['request']['url'], # 通过指定read_json()里面对应的body json=data['request']['body']) # 通过判断返回的json数据判断read_json()里面response内容 # 通过使用assert来断言判断是否满足预期结果 assert r.json()['status'] == data['response']["status"] print(r.json()) if __name__ == '__main__': pytest.main('-s', '-v', 'parametrize05_json.py')
输出:
============================= test session starts =============================
collecting ... collected 1 item
parametrize05_json.py::test_json_login[data0]
============================== 1 passed in 0.42s ==============================
PASSED [100%]{'status': 1, 'msg': '', 'data': None, 'datas': None, 'errCode': 0}
Process finished with exit code 0
file = open("文件名.txt", "r", encoding="utf-8")
content = file.read()
print(content)
示例,从下面txt文件中获取所有权限然后传参:
代码如下:
# txt文件传参: import json import pytest import requests # 获取权限列表方法 def get_txt(): # 从文件中读取权限 authoList = [] # 打开txt文件 txt_file = open('my_test.txt', 'r', encoding='utf-8') # 读取txt文件 con = txt_file.read() print(con) result = con[1: -1].split(',') for autho in result: authoList.append(autho[1: -1]) print(authoList) return authoList @pytest.mark.parametrize('autho', get_txt()) def test_add_group(autho): print(autho)
读取csv文件要导入csv库,基本格式如下:
# 读取csv文件
file1 = open("文件名.csv", "r")
content = csv.reader(file)
file1.close()
# 写入csv文件内容
file2 = open("文件名.csv", "w")
write = csv.writer(file2)
file2.close()
示例,从以下csv表格中获取参数那列的值:
代码如下:
# csv文件传参: import pytest import csv # 打开文件 def get_userdata(): # 登入数据列表 dataList = [] file1 = open('login_params.csv', 'r') # 读文件 readers = csv.reader(file1) # 跳过首行 readers.__next__() for row in readers: print(type(row[2])) # 将字符串类型转为字典类型 userdata = eval(row[2]) print(type(userdata),userdata) dataList.append(userdata) print(dataList) return dataList @pytest.mark.parametrize('userinfo',get_userdata()) def test_add_group(userinfo): print(userinfo['username']) print(userinfo['password']) print(userinfo['state'])
输出:
============================= test session starts ============================= collecting ... collected 3 items parametrize07_csv.py::test_add_group[userinfo0] PASSED [ 33%]test1 123456 1 parametrize07_csv.py::test_add_group[userinfo1] PASSED [ 66%] 123456 0 parametrize07_csv.py::test_add_group[userinfo2] PASSED [100%]test2 0 ============================== 3 passed in 0.04s ============================== Process finished with exit code 0
读取Excel文件要导入pandas库,基本格式如下:
# 导入类库
import pandas as pd
# 读取Excel
df = pd.read_excel("文件名.xlsx")
# 提取对应行的内容
row = df.loc[[1, 3]].values # 从0开始,0是首行,所以这里读取的是第1行和第4行的内容
# 提取对应列的内容
colum = df['列的标题'].values
示例,从以下Excel文件中获取参数那一列的内容:
# Excel文件传参: import pandas import pandas as pd import pytest def get_userdata(): # 打开文件 df = pd.read_excel("test_login.xlsx") # row = df.loc[[0, 2]].values # print(row) # 读文件 cloum = df['输入参数'].values list_data = cloum.tolist() print(type(list_data), list_data) return list_data @pytest.mark.parametrize("userinfo", get_userdata()) def test_add_group(userinfo): # 将其转换为字典类型 userinfo_dic = eval(userinfo) print(userinfo_dic["username"]) print(userinfo_dic["password"])
输出:
============================= test session starts ============================= collecting ... collected 4 items parametrize08_Excel.py::test_add_group[{"username":"test1", "password":"123456"}] PASSED [ 25%]test1 123456 parametrize08_Excel.py::test_add_group[{"username":"", "password":"123456"}] PASSED [ 50%] 123456 parametrize08_Excel.py::test_add_group[{"username":"test3", "password":""}] PASSED [ 75%]test3 parametrize08_Excel.py::test_add_group[{"username":"test4", "password":""}] PASSED [100%]test4 ============================== 4 passed in 2.08s ============================== Process finished with exit code 0
读取数据库文件要导入pymysql库,基本格式如下:
# mysql数据库传参: import pymysql import pytest """ # 连接数据库 db = pymysql.connect(host="127.0.0.1", db="my_test", user="root", passwd="123456", charset="utf8") # 访问数据库 cursor = db.cursor() # 读取数据库对应内容 cursor.execute('select * from test_user') data = cursor.fetchone() print(data) # 关闭数据库 db.close() """ def get_db_data(): # 连接数据库 db = pymysql.connect(host='127.0.0.1', db='my_test', user='root', password='123456', charset='utf8') # 访问数据库 cursor = db.cursor() # 查询数据 cursor.execute('select username, password from test_user') data = cursor.fetchall() print(data) # 取出的数据类型是元组 db.close() return data @pytest.mark.parametrize("userinfo", get_db_data()) def test_add_group(userinfo): print(type(userinfo)) # 输入的是元组类型 print(userinfo[0]) print(userinfo[1])
输出:
============================= test session starts ============================= collecting ... collected 3 items parametrize09_mysql.py::test_add_group[userinfo0] PASSED [ 33%]<class 'tuple'> xiaoliu 123456 parametrize09_mysql.py::test_add_group[userinfo1] PASSED [ 66%]<class 'tuple'> zhangshan 456187 parametrize09_mysql.py::test_add_group[userinfo2] PASSED [100%]<class 'tuple'> chengyi 4536187 ============================== 3 passed in 0.08s ============================== Process finished with exit code 0
如果有多处文件都要使用同一个数据,可以将数据放在conftest.py文件下,与fixture固件结合,其他文件就可以直接使用,而不需要导入文件了。
注意点:
# conftest.py文件 import pytest # 获取权限列表方法 @pytest.fixture(scope='session') def get_autho(): # 从文件中读取权限 authoList = [] # 打开txt文件 f1 = open('my_test.txt', 'r', encoding='utf-8') # 读取txt文件 con = f1.read() resule = con[1: -1].split(',') for autho in resule: authoList.append(autho[1: -1]) return authoList
同目录下其他文件可直接引用(parametrize10_conftest.py)
import pytest
class TestDemo:
def test_add_group(self, get_autho):
for autho in get_autho:
print(autho)
if __name__ == '__main__':
pytest.main('parametrize10_conftest.py', '-s')
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。