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

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

相关推荐
专注VB编程开发20年1 小时前
OpenXml、NPOI、EPPlus、Spire.Office组件对EXCEL ole对象附件的支持
前端·.net·excel·spire.office·npoi·openxml·spire.excel
程序视点5 小时前
「Excel文件批量加密与合并工具推荐」高效办公必备神器 - 程序视点
excel
掉鱼的猫8 小时前
老码农教你:Solon + EasyExcel 导出工具
java·excel
带刺的坐椅8 小时前
老码农教你:Solon + EasyExcel 导出工具
java·excel·solon·easyexcel
米欧12 小时前
使用luckysheet在线处理复杂表格
前端·excel·vite
海上生明月丿13 小时前
Day12 数据统计-Excel报表
excel
偷心伊普西隆1 天前
Python Excel 通用筛选函数
python·excel·pandas
嗝屁小孩纸1 天前
使用EasyExcel自定义导出表格
java·excel
CodeCraft Studio1 天前
Excel处理控件Aspose.Cells教程:使用Python将 Excel 转换为 NumPy
python·excel·numpy·aspose·数据表格·aspose.cells·excel文档格式转换
liuxizhen20091 天前
Excel中运行VB的函数
excel