【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),以便在读取时能够识别并转换为正确的异常类型。

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

相关推荐
weixin_4624462312 小时前
Python 使用 openpyxl 从 URL 读取 Excel 并获取 Sheet 及单元格样式信息
python·excel·openpyxl
wtsolutions13 小时前
MCP Server Integration - JSON to Excel for AI and Automation
json·excel
开开心心就好15 小时前
音频编辑工具,多端支持基础剪辑易操作
java·网络·windows·java-ee·电脑·maven·excel
vfvfb17 小时前
excel多个合并 xlsx工作表合并 多个excel合并到一张表
excel
金融小白数据分析之路19 小时前
msoffcrypto-tool库 Excel 加密
python·excel
开开心心_Every1 天前
文件数量统计工具:支持多层文件夹数量统计
游戏·微信·pdf·excel·语音识别·swift·lisp
私人珍藏库1 天前
[吾爱大神原创工具] Excel 数据批量转 Word 工具(2026年最新版)
word·excel·工具·软件·win
linuxxx1101 天前
excel365批量拆分列并填充单元格
excel
徐赛俊1 天前
Excel 数据写入 PowerPoint 表格与文本框(涨跌幅颜色自动处理)
powerpoint·excel
好好学操作系统1 天前
notion+excel自动创建表格| 了解了notion api
数据库·python·oracle·excel·notion