pytest 使用用例数据
尝试了几种方法,可能还是装逼方法最好用哈哈哈
涉及到的文件位置
1.读取excel文件内容进行参数化,发现不是很理想,没办法多用例使用
首先需要准备一个user.xlsx,
还要弄一个读取excel的方法 xlsxLoad.py::getConfig::read_xlsx
#!/usr/bin/env python
# encoding: utf-8 """ @author: HYN @file: xlsxLoad.py @time: 2022/3/24 13:43 @desc:读取xlsx等文件 """ import xlrd class getConfig(object): def read_xlsx(path): book = xlrd.open_workbook(path) # 根据索引获取第1个工作表对象sheet sheet = book.sheet_by_index(0) rows = sheet.nrows cols = sheet.ncols user_info = [] for i in range(1, sheet.nrows): temp = [] for j in range(0, sheet.ncols): unit_ce = sheet.cell_value(i, j) if type(unit_ce) is float: unit_ce = '{:.0f}'.format(unit_ce) temp.append(unit_ce) user_info.append(temp) # print(user_info) return user_info
最后在测试用例里test_login.py::TestLogin::test_login调用,
# 数据读取方法1 读取excell
# headers = {
# "Accept": "application/json, text/plain, */*",
# "Accept-Encoding": "gzip, deflate",
# "Accept-Language": "zh-CN,zh;q=0.9",
# "Content-Type": "application/x-www-form-urlencoded",
# "User-Agent": user_agent
# }
# user_info = getConfig.read_xlsx('../../data/user.xlsx')[0]
# body = {
# "userName": user_info[1],
# "password": des_encode(user_info[2])
# }
用下来不好用,断言还得手动写,这个测试用例不能重复用,不合适啊
看了一下也可以搞封装,但是决定先换个方法试试
2.直接读取yaml文件,没办法用多组用例
准备一个login.yaml文件,写好用例(我写了2个数组)
然后写一个读取yaml的公共类方法 yamlLoad.py
#!/usr/bin/env python
# encoding: utf-8
"""
@author: HYN
@file: yamlLoad.py
@time: 2022/3/30 14:37
@desc: 读取yaml文件
"""
import yaml
import pytest
# 读取yaml
def read_yaml(path) -> list:
with open(path, mode='r', encoding='utf-8') as f:
value = yaml.load(f, Loader=yaml.FullLoader)
return value
最后在test_login.py里引用
from common.yamlLoad import read_yaml
# 数据读取方法2 读取yaml文件
params = read_yaml("../../data/login.yaml")
class TestLogin():
def test_login(self, params):
url = conf.server_addr()+params[0]["path"]
...
要调用第2个用例就要把 params[0]换成params[1],达咩
3.调用装饰器,@pytest.mark.parametrize(argnames, argvalues)
各大视频也是推荐用yaml +装饰器来参数化,所以也试一试
login.yaml、yamlLoad.py内容均不变,修改test_login.py为
class TestLogin():
# 数据读取方法3 参数化,但是需要是list, tuple格式
@pytest.mark.parametrize("params", read_yaml("../../data/login.yaml"))
def test_login(self, params):
url = conf.server_addr()+params["path"]
headers = params["headers"]
body = params["data"]
body["password"] = des_encode(body["password"])
re = requests.post(url=url, headers=headers, data=body, timeout=5.0)
需要特别注意这个params,最开始我直接写,得到的数据压根不对!!!!path我要取字典value值‘login’,这一点我阻塞了好久,去个网站博客搜也没找到
最后 在想可不可以直接返回这个结构再区value,才搞定了,呜呜呜