【pytest】测试数据存储在 Excel 或 TXT 文件中,如何参数化

如果测试数据存储在 Excel 或 TXT 文件中,你可以使用外部库来读取这些数据,并将其转化为参数化测试所需的格式。下面我将分别展示如何从这两种文件中读取数据,并用于参数化测试。

从 Excel 文件中读取测试数据

你可以使用 pandas 库来读取 Excel 文件中的数据。首先,确保你已经安装了 pandasopenpyxl(用于读取 .xlsx 文件)或 xlrd(用于读取 .xls 文件)。

bash 复制代码
pip install pandas openpyxl

然后,你可以编写代码来读取 Excel 文件中的数据,并将其转换为参数化测试所需的格式。

python 复制代码
import pandas as pd
import pytest
from user_processor import process_user_input

# 读取 Excel 文件中的数据
def read_excel_data(file_path):
    df = pd.read_excel(file_path)
    test_data = list(zip(df['input_string'], df['expected_result']))
    return test_data

# Excel 文件路径
excel_file_path = 'test_data.xlsx'

# 读取测试数据
test_data = read_excel_data(excel_file_path)

# 使用参数化装饰器
@pytest.mark.parametrize("input_string, expected_result", test_data)
def test_process_user_input(input_string, expected_result):
    # ... 测试逻辑与之前相同 ...

在 Excel 文件中,你需要有两列,一列是 input_string(输入字符串),另一列是 expected_result(期望结果或异常类型)。

从 TXT 文件中读取测试数据

如果你的数据存储在 TXT 文件中,并且每行包含输入字符串和期望结果(可能是以某种分隔符分隔的),你可以使用 Python 的内置文件操作函数来读取这些数据。

python 复制代码
import pytest
from user_processor import process_user_input

# 读取 TXT 文件中的数据
def read_txt_data(file_path, delimiter=','):
    test_data = []
    with open(file_path, 'r') as file:
        for line in file:
            parts = line.strip().split(delimiter)
            input_string = parts[0]
            expected_result_str = parts[1]
            # 如果期望结果是异常类型,需要特殊处理
            if expected_result_str.startswith('ValueError'):
                expected_result = pytest.raises(ValueError)
            else:
                expected_result = expected_result_str
            test_data.append((input_string, expected_result))
    return test_data

# TXT 文件路径
txt_file_path = 'test_data.txt'

# 读取测试数据
test_data = read_txt_data(txt_file_path)

# 使用参数化装饰器
@pytest.mark.parametrize("input_string, expected_result", test_data)
def test_process_user_input(input_string, expected_result):
    # ... 测试逻辑与之前相同 ...

在 TXT 文件中,每行应该包含两个由某个分隔符(例如逗号)分隔的值:输入字符串和期望结果(或异常类型)。如果期望结果是异常类型,你可能需要在文件中以某种方式标记它(例如,在值前加上 ValueError),以便在读取时能够识别并转换为正确的异常类型。

记住,这些只是从文件中读取数据的基本示例。根据你的具体需求,你可能需要调整文件读取逻辑以适应你的文件格式和内容。

相关推荐
啊森要自信36 分钟前
【GUI自动化测试】YAML 配置文件应用:从语法解析到 Python 读写
android·python·缓存·pytest·pip·dash
我的xiaodoujiao5 小时前
从 0 到 1 搭建完整 Python 语言 Web UI自动化测试学习系列 17--测试框架Pytest基础 1--介绍使用
python·学习·测试工具·pytest
SunkingYang5 小时前
详细介绍C++中通过OLE操作excel时,一般会出现哪些异常,这些异常的原因是什么,如何来解决这些异常
c++·excel·解决方案·闪退·ole·异常类型·异常原因
Wu_hello_mi5 小时前
Excel使用教程笔记
笔记·excel
恶猫6 小时前
Polaris Officev9.9.12全功能解锁版
pdf·word·excel·ppt·office·办公·打工
杂货铺的小掌柜7 小时前
apache poi excel 字体数量限制
java·excel·poi
东方佑19 小时前
基于FastAPI与LangChain的Excel智能数据分析API开发实践
langchain·excel·fastapi
许泽宇的技术分享20 小时前
当Excel遇上大语言模型:ExcelAgentTemplate架构深度剖析与实战指南
语言模型·架构·excel
gihigo199820 小时前
基于MATLAB的Excel文件批量读取与循环处理
matlab·excel