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

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

相关推荐
dgiij4 小时前
excel大表导入数据库
数据库·mysql·node.js·excel
多敲代码防脱发4 小时前
导出导入Excel文件(详解-基于EasyExcel)
java·开发语言·jvm·数据库·mysql·excel
文人sec6 小时前
接口自动化测试设计思路--设计实战
python·https·单元测试·自动化·pytest
琉璃℡初雪6 小时前
vue2/3 中使用 @vue-office/docx 在网页中预览(docx、excel、pdf)文件
vue.js·pdf·excel
河山入梦来1 天前
Excel表的导入与导出
excel
wtsolutions1 天前
Excel-to-JSON插件专业版功能详解:让Excel数据转换更灵活
json·excel·excel-to-json·wtsolutions·专业版
梦幻通灵1 天前
Excel分组计算求和的两种实现方案
前端·excel
莫负初1 天前
Excel使用VBA批量计算指定列的中位数和标准差并筛选指定列数据
数据分析·自动化·excel·vba·方差·标准差
测试开发Kevin2 天前
从投入产出、效率、上手难易度等角度综合对比 pytest 和 unittest 框架
python·pytest
杜子腾dd2 天前
17.Excel:实用的 VBA 自动化程序
数据分析·自动化·excel