接口自动化——参数化

        之前有说过,通过pytest测试框架标记参数化功能可以实现数据驱动测试。数据驱动测试使用的文件主要有以下类型:

  • txt 文件 
  • csv 文件
  • excel 文件
  • json 文件
  • yaml 文件
  • ....

本文主要讲的就是以上几种文件类型的读取和使用

一.txt 文件读取使用

        首先创建一个 txt 文件,文件内容为:

张三,男,2024-09-10
李四,女,2022-09-10
王五,男,2090-09-10

 然后读取文件内容

def get_txt_data():with open(r"D:\python_project\API_Auto\API3\data\txt_data", encoding="utf-8") as file:content = file.readlines()# print(content)# 去掉数据后面的换行符list_data = []list_data1 = []for i in content:list_data.append(i.strip())# 将数据分割for i in list_data:list_data1.append(i.split(","))return list_data1

这样就得到了 符合参数化要求的参数,对读取的内容进行使用:

@pytest.mark.parametrize(("name", "gender", "data"), get_txt_data())
def test_txt_func(name, gender, data):print(f'输入名字:{name}')print(f'输入性别 :{gender}')print(f'输入日期:{data}')

输出为:

D:\python_project\API_Auto\API3\venv\Scripts\python.exe D:\python_project\API_Auto\API3\main.py 
============================= test session starts =============================
platform win32 -- Python 3.10.6, pytest-8.3.5, pluggy-1.5.0 -- D:\python_project\API_Auto\API3\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\python_project\API_Auto\API3
configfile: pytest.ini
plugins: allure-pytest-2.13.5, result-log-1.2.2
collecting ... [['张三', 18.0, 185.0, 10000000.0], ['李四', 30.0, 178.0, 2000.0], ['王五', 40.0, 169.0, 43323.0]]
collected 3 itemstestcases/test_ddt.py::test_txt_func[张三-男-2024-09-10] 输入名字:张三
输入性别 :男
输入日期:2024-09-10
PASSED
testcases/test_ddt.py::test_txt_func[李四-女-2022-09-10] 输入名字:李四
输入性别 :女
输入日期:2022-09-10
PASSED
testcases/test_ddt.py::test_txt_func[王五-男-2090-09-10] 输入名字:王五
输入性别 :男
输入日期:2090-09-10
PASSED============================== 3 passed in 0.06s ==============================
Report successfully generated to .\reportProcess finished with exit code 0

二.csv 文件读取使用

首先创建一个csv文件,内容为:

1,2,3
1,3,3
2,2,4

 然后读取文件内容

import csvdef get_csv_data():list1 = []f = csv.reader(open(r"D:\python_project\API_Auto\API3\data\x_y_z.csv", encoding="utf-8"))for i in f:# list1.append(i.strip())# [int(element) for element in i],  列表推导式,它的作用是对 i 中的每个元素进行遍历,并将每个元素从字符串(str)转换为整数(int)a = [int(element) for element in i]list1.append(a)return list1

然后使用读取到的数据

@pytest.mark.parametrize(("x", "y", "z"), get_csv_data()
)
def test_csv_func(x, y, z):assert x * y == z

输出为:

D:\python_project\API_Auto\API3\venv\Scripts\python.exe D:\python_project\API_Auto\API3\main.py 
============================= test session starts =============================
platform win32 -- Python 3.10.6, pytest-8.3.5, pluggy-1.5.0 -- D:\python_project\API_Auto\API3\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\python_project\API_Auto\API3
configfile: pytest.ini
plugins: allure-pytest-2.13.5, result-log-1.2.2
collecting ... [['张三', 18.0, 185.0, 10000000.0], ['李四', 30.0, 178.0, 2000.0], ['王五', 40.0, 169.0, 43323.0]]
collected 3 itemstestcases/test_ddt.py::test_csv_func[1-2-3] FAILED
testcases/test_ddt.py::test_csv_func[1-3-3] PASSED
testcases/test_ddt.py::test_csv_func[2-2-4] PASSED================================== FAILURES ===================================
____________________________ test_csv_func[1-2-3] _____________________________x = 1, y = 2, z = 3@pytest.mark.parametrize(("x", "y", "z"), get_csv_data())def test_csv_func(x, y, z):
>       assert x * y == z
E       assert (1 * 2) == 3testcases\test_ddt.py:21: AssertionError
----------------------------- Captured log setup ------------------------------
WARNING  pytest_result_log:plugin.py:122 ---------------Start: testcases/test_ddt.py::test_csv_func[1-2-3]---------------
---------------------------- Captured log teardown ----------------------------
WARNING  pytest_result_log:plugin.py:128 ----------------End: testcases/test_ddt.py::test_csv_func[1-2-3]----------------
=========================== short test summary info ===========================
FAILED testcases/test_ddt.py::test_csv_func[1-2-3] - assert (1 * 2) == 3
========================= 1 failed, 2 passed in 0.13s =========================
Report successfully generated to .\reportProcess finished with exit code 0

三.excel 文件读取使用

首先创建一个excel文件,文件内容为:

然后在读取Excel数据内容前,要针对不同版本使用不同的第三方库

  • xls
    • office 2003版本
      • 安装:xlrd第三库
      • 必须指定版本
      • pip install xlrd==1.2.0
  • xlsx
    • office 2016版本
      • 安装:openpyxl第三方库
      • 默认安装最新的版本库即可
      • pip install openpyxl

安装完后,读取 数据:

import xlrd# # 读取excel 文件数据获取xls文件对象
# xls = xlrd.open_workbook(r'D:\python_project\API_Auto\API3\data\test.xlsx')
#
# # 获取excel 中的sheet 表,0代表第一张 表的索引、
# sheet = xls.sheet_by_index(0)
#
# # 输出数据列
# print(sheet.ncols)
#
# # 输出数据行
# print(sheet.nrows)
#
# # 读取具体某一行内容,0代表第一行数据索引
# print(sheet.row_values(1))
#def get_excel_data(path):list_excel =  []xls = xlrd.open_workbook(path)# 获取excel 中的sheet 表,0代表第一张 表的索引、sheet = xls.sheet_by_index(0)for i in range(sheet.nrows):list_excel.append(sheet.row_values(i))# 删除表头数据list_excel.pop(0)# print(list_excel)return list_excel

使用读取到的数据:

@pytest.mark.parametrize(("name", "age", "height", "money"), get_excel_data(r"D:\python_project\API_Auto\API3\data\test.xlsx")
)
def test_excel_func(name, age, height, money):print(f"name是{name},age是{age},height是{height},money是{money}")

输出结果为 :

D:\python_project\API_Auto\API3\venv\Scripts\python.exe D:\python_project\API_Auto\API3\main.py 
============================= test session starts =============================
platform win32 -- Python 3.10.6, pytest-8.3.5, pluggy-1.5.0 -- D:\python_project\API_Auto\API3\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\python_project\API_Auto\API3
configfile: pytest.ini
plugins: allure-pytest-2.13.5, result-log-1.2.2
collecting ... collected 3 itemstestcases/test_ddt.py::test_excel_func[张三-18.0-185.0-10000000.0] name是张三,age是18.0,height是185.0,money是10000000.0
PASSED
testcases/test_ddt.py::test_excel_func[李四-30.0-178.0-2000.0] name是李四,age是30.0,height是178.0,money是2000.0
PASSED
testcases/test_ddt.py::test_excel_func[王五-40.0-169.0-43323.0] name是王五,age是40.0,height是169.0,money是43323.0
PASSED============================== 3 passed in 0.09s ==============================
Report successfully generated to .\reportProcess finished with exit code 0

四.json 文件的读取使用

首先创建一个json文件,内容为:

[[1,2,3],[4,2,6],[7,8,9]
]

然后读取文件内容

def get_json_data(path):with open(path, encoding="utf-8") as file:content = file.read()# print(eval(content))# print(type(eval(content)))# eval() : 去掉最外层的引号return eval(content)

对读取到的内容进行使用:


@pytest.mark.parametrize(("x", "y", "z"), get_json_data(r'D:\python_project\API_Auto\API3\data\json.json')
)
def test_json_func(x, y, z):assert x + y == z

输出结果为:

D:\python_project\API_Auto\API3\venv\Scripts\python.exe D:\python_project\API_Auto\API3\main.py 
============================= test session starts =============================
platform win32 -- Python 3.10.6, pytest-8.3.5, pluggy-1.5.0 -- D:\python_project\API_Auto\API3\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\python_project\API_Auto\API3
configfile: pytest.ini
plugins: allure-pytest-2.13.5, result-log-1.2.2
collecting ... collected 3 itemstestcases/test_ddt.py::test_json_func[1-2-3] PASSED
testcases/test_ddt.py::test_json_func[4-2-6] PASSED
testcases/test_ddt.py::test_json_func[7-8-9] FAILED================================== FAILURES ===================================
____________________________ test_json_func[7-8-9] ____________________________x = 7, y = 8, z = 9@pytest.mark.parametrize(("x", "y", "z"), get_json_data(r'D:\python_project\API_Auto\API3\data\json.json'))def test_json_func(x, y, z):
>       assert x + y == z
E       assert (7 + 8) == 9testcases\test_ddt.py:35: AssertionError
----------------------------- Captured log setup ------------------------------
WARNING  pytest_result_log:plugin.py:122 --------------Start: testcases/test_ddt.py::test_json_func[7-8-9]---------------
---------------------------- Captured log teardown ----------------------------
WARNING  pytest_result_log:plugin.py:128 ---------------End: testcases/test_ddt.py::test_json_func[7-8-9]----------------
=========================== short test summary info ===========================
FAILED testcases/test_ddt.py::test_json_func[7-8-9] - assert (7 + 8) == 9
========================= 1 failed, 2 passed in 0.14s =========================
Report successfully generated to .\reportProcess finished with exit code 0

五.yaml 文件读取使用 

1.yaml数据读写

序列化:内存中数据,转化为文件

反序列化:将文件转化为内存数据 需要操作yaml文件,安装第三方库

                  pip install pyyaml

2.序列化  将yaml 数据写入文件中

"""
YAML 是一个可读性 高,用来达标数据序列化的格式基本语法格式:1.区分大小写2.使用缩进表示层级 关系3.缩进不能 使用 tab  建,只能使用空格4.缩进的空格数不重要,只要相同 层级的元素左对齐即可5.可以使用 注释符号 #yaml  序列化 常用数据类型:1.对象(python中的 字段,键值对)2.数组(python 中的列表 )3.纯量:单个的、不可再分值4.布尔值5.空值YAML 数据读写:序列化:将内存 中数据转化为文件反序列化 :将文件转化为内存数据需要安装第三方库:pip install pyyaml
"""data = {'数字': [1, 2, 3, 4, -1],'字符串': ["a", "@#", "c"],'空值': None,'布尔值': [True, False],'元组': (1, 2, 3)
}import yaml# 将 python 数据类型,转换为yaml 格式
yaml_data = yaml.safe_dump(data,  # 要转化的数据内容allow_unicode=True,  # 允许unicode 字符,中文原样显示sort_keys=False  # 不进行排序,原样输出
)# 序列化  将yaml 数据写入文件中
f = open(r"D:\python_project\API_Auto\API3\data\yaml.yaml", "w", encoding="utf-8")
f.write(yaml_data)
f.close()

3.反序列化 读取yaml 文件中的数据

# 反序列化   读取yaml 文件中的数据
f = open(r"D:\python_project\API_Auto\API3\data\yaml.yaml", "r", encoding="utf-8")
s = f.read()
data_yaml = yaml.safe_load(s)
print(data_yaml)

4.写入一个大列表里面嵌套小列表

# 写入一个大列表里面嵌套小列表list1 = [['张三', 18.0, 185.0, 10000000.0], ['李四', 30.0, 178.0, 2000.0], ['王五', 40.0, 169.0, 43323.0]]yaml_data = yaml.safe_dump(list1,  # 要转化的数据内容allow_unicode=True,  # 允许unicode 字符,中文原样显示sort_keys=False  # 不进行排序,原样输出
)# 序列化  将yaml 数据写入文件中
f = open(r"D:\python_project\API_Auto\API3\data\yaml1.yaml", "w", encoding="utf-8")
f.write(yaml_data)
f.close()

完整代码为:

data = {'数字': [1, 2, 3, 4, -1],'字符串': ["a", "@#", "c"],'空值': None,'布尔值': [True, False],'元组': (1, 2, 3)
}import yamldef get_yaml_data():# 将 python 数据类型,转换为yaml 格式yaml_data = yaml.safe_dump(data,  # 要转化的数据内容allow_unicode=True,  # 允许unicode 字符,中文原样显示sort_keys=False  # 不进行排序,原样输出)# 序列化  将yaml 数据写入文件中f = open(r"D:\python_project\API_Auto\API3\data\yaml.yaml", "w", encoding="utf-8")f.write(yaml_data)f.close()# 反序列化   读取yaml 文件中的数据f = open(r"D:\python_project\API_Auto\API3\data\yaml.yaml", "r", encoding="utf-8")s = f.read()data_yaml = yaml.safe_load(s)print(data_yaml)# 写入一个大列表里面嵌套小列表list1 = [['张三', 18.0, 185.0, 10000000.0], ['李四', 30.0, 178.0, 2000.0], ['王五', 40.0, 169.0, 43323.0]]yaml_data = yaml.safe_dump(list1,  # 要转化的数据内容allow_unicode=True,  # 允许unicode 字符,中文原样显示sort_keys=False  # 不进行排序,原样输出)# 序列化  将yaml 数据写入文件中f = open(r"D:\python_project\API_Auto\API3\data\yaml1.yaml", "w", encoding="utf-8")f.write(yaml_data)f.close()# 反序列化   读取yaml 文件中的数据f = open(r"D:\python_project\API_Auto\API3\data\yaml1.yaml", "r", encoding="utf-8")s = f.read()data_yaml1 = yaml.safe_load(s)print(data_yaml1)return data_yaml1

使用读取到的数据:

@pytest.mark.parametrize(("x"), get_yaml_data()
)
def test_yaml_func(x):for i in x:print(i)

输出为 :

D:\python_project\API_Auto\API3\venv\Scripts\python.exe D:\python_project\API_Auto\API3\main.py 
============================= test session starts =============================
platform win32 -- Python 3.10.6, pytest-8.3.5, pluggy-1.5.0 -- D:\python_project\API_Auto\API3\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\python_project\API_Auto\API3
configfile: pytest.ini
plugins: allure-pytest-2.13.5, result-log-1.2.2
collecting ... {'数字': [1, 2, 3, 4, -1], '字符串': ['a', '@#', 'c'], '空值': None, '布尔值': [True, False], '元组': [1, 2, 3]}
[['张三', 18.0, 185.0, 10000000.0], ['李四', 30.0, 178.0, 2000.0], ['王五', 40.0, 169.0, 43323.0]]
collected 3 itemstestcases/test_ddt.py::test_yaml_func[x0] 张三
18.0
185.0
10000000.0
PASSED
testcases/test_ddt.py::test_yaml_func[x1] 李四
30.0
178.0
2000.0
PASSED
testcases/test_ddt.py::test_yaml_func[x2] 王五
40.0
169.0
43323.0
PASSED============================== 3 passed in 0.10s ==============================
Report successfully generated to .\reportProcess finished with exit code 0

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/904119.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

游戏引擎学习第257天:处理一些 Win32 相关的问题

设定今天的工作计划 今天我们本来是打算继续开发性能分析器(Profiler),但在此之前,我们认为有一些问题应该先清理一下。虽然这类事情不是我们最关心的核心内容,但我们觉得现在是时候处理一下了,特别是为了…

实验三 触发器及基本时序电路

1.触发器的分类?各自的特点是什么? 1 、 D 触发器 特点:只有一个数据输入端 D ,在时钟脉冲的触发沿,输出 Q 的状态跟随输入端 D 的 状态变化,即 ,功能直观,利于理解和感受…

硬件加速模式Chrome(Edge)闪屏

Chrome开启“硬件加速模式”后,打开浏览器会闪屏或看视频会闪屏,如果电脑只有集显,直接将这个硬件加速关了吧,没啥必要开着 解决方法 让浏览器使用独立显卡 在Windows左下角搜索 图形设置 ,将浏览器添加进去&#…

前端工程化利器:Node.js 文件匹配库 fast-glob 完全指南——比传统方案快 350% 的「文件搜索神器」

为什么需要 fast-glob? 在前端工程化场景中,文件匹配是高频操作:自动化构建、资源打包、静态资源管理等都依赖高效的路径匹配。传统的 node-glob 虽然功能齐全,但性能瓶颈明显。fast-glob 应运而生——它以 极简 API 和 超高性能…

React class 的组件库与函数组件适配集成

如果你有一个 基于 React class 的组件库,现在需要在 React hooks 函数组件中使用,你可以通过以下几种方式实现适配和集成: 数据生命周期确保 class 组件使用 React.forwardRef 导出(或手动绑定 ref) ✅ 1. 直接使用 c…

Sway初体验

Sway(缩写自 SirCmpwn’s Wayland compositor[1])是一款专为 Wayland 设计的合成器,旨在与 i3 完全兼容。根据官网所述: Sway 是 Wayland 的合成器,也是 x11 的 i3 窗口管理器的替代品。它可以根据您现有的 i3 配置工作…

dubbo 参数校验-ValidationFilter

org.apache.dubbo.rpc.Filter 核心功能 拦截RPC调用流程 Filter是Dubbo框架中实现拦截逻辑的核心接口,作用于服务消费者和提供者的作业链路,支持在方法调用前后插入自定义逻辑。如参数校验、异常处理、日志记录等。扩展性机制 Dubbo通过SPI扩展机制动态…

Lesson 16 A polite request

Lesson 16 A polite request 词汇 park n. 公园,停车场,庄园 v. 停车,泊车 例句:让我来停车。    Let me park. 相关:spot n. 车位 区别:garden n. 花园 [小,私家的] 例句:我们…

解决 Builroot 系统编译 perl 编译报错问题

本文提供一种修复 Builroot 系统编译 perl 编译报错途径 2025-05-04T22:45:08 rm -f pod/perl5261delta.pod 2025-05-04T22:45:08 /usr/bin/ln -s perldelta.pod pod/perl5261delta.pod 2025-05-04T22:45:08 /usr/bin/gcc -c -DPERL_CORE -fwrapv -fpcc-struct-return -pipe -f…

Spring MVC 中解决中文乱码问题

在 Spring MVC 中解决中文乱码问题,需要从 请求参数编码 和 响应内容编码 两方面入手。以下是完整的解决方案: 一、解决请求参数中文乱码 1. POST 请求编码(表单提交) 配置 CharacterEncodingFilter 在 web.xml 中添加 Spring 提…

MYSQL数据库突然消失

之前在下载mysql时发现没有my.ini。考虑到后面的项目可能需要,看着教程自己创建了一次,当时就发生了所有数据库消失的问题,近几天这种事件又发生了。我在服务里看到我有mysql和mysql57两个服务,启动一个的时候另一个就无法启动&am…

【Spring】idea + maven 从零创建Spring IoC容器示例

【Spring】idea maven 从零创建Spring IoC容器示例 1. 环境准备2. 创建maven项目3. 添加依赖4. 创建Java类与接口4.1 定义接口UserService4.2 实现接口UserServiceImpl 5. 配置Spring IoC容器6. 编写主类调用IoC容器扩展:使用注解方式实现IoC1. 修改beans.xml2.使用…

面试回答之STAR结构

面试回答之STAR结构 1. STAR结构的起源 STAR是行为面试法(Behavioral Interview)的核心框架,由以下四个单词首字母组成: • Situation(情境) • Task(任务) • Action&#xff…

Kubernetes部署运行应用

①使用 Deployment 运行一个无状态应用 ②运行一个单实例有状态应用 ③运行一个有状态的应用程序 ④使用 Persistent Volumes 部署 WordPress 和 MySQL

二叉搜索树的最近祖先(递归遍历)

235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode) class Solution { private:TreeNode*traversal(TreeNode*cur,TreeNode*p,TreeNode*q){if(curNULL){return NULL;}if(cur->val>p->val&&cur->val>q->val){TreeNode*lefttrave…

网络:TCP三次握手、四次挥手

目录 深刻理解三次握手 深刻理解四次挥手 深刻理解三次握手 三次握手时,如果最后一个ACK包,服务器没有收到,此时: 客户端:认为已经建立链接 服务器:认为没有建立链接,还在超时等待。 而此…

MySQL 实战 45 讲 笔记 ----来源《极客时间》

01 | 基础架构:一条SQL查询语句是如何执行的? 1. MySQL 可以分为 Server层 和 存储引擎层 两部分。Server 层包括连接器、查询缓存、分析器、优化器、执行器等。存储引擎层支持 InnoDB、MyISAM等. (1) 连接器:管理连接,权限认证…

nextjs+supabase vercel部署失败

1.不能含有<any> 改成unknown或者增加类(如图) 2.检查vecel是否配置环境变量&#xff08;即supabase的url和anon-key&#xff09;

数据库Mysql_联合查询

或许自己的不完美才是最完美的地方&#xff0c;那些让自己感到不安的瑕疵&#xff0c;最终都会变成自己的特色。 ----------陳長生. 1.介绍 1.1.为什么要进行联合查询 在数据设计的时候&#xff0c;由于范式的需求&#xff0c;会被分为多个表&#xff0c;但是当我们要查询数据…

(37)VTK C++开发示例 ---纹理地球

文章目录 1. 概述2. CMake链接VTK3. main.cpp文件4. 演示效果 更多精彩内容&#x1f449;内容导航 &#x1f448;&#x1f449;VTK开发 &#x1f448; 1. 概述 将图片纹理贴到球体上&#xff0c;实现3D地球的效果。 该代码使用了 VTK (Visualization Toolkit) 库来创建一个纹理…