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

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

相关推荐
LAM LAB4 天前
【VBA】Excel指定单元格范围内字体设置样式,处理导出课表单元格
excel·vba
姚青&4 天前
PyCharm 配置与界面化运行
pytest
姚青&4 天前
Pytest 测试用例断言
测试用例·pytest
在这habit之下4 天前
Keepalived学习总结
excel
姚青&4 天前
Pytest 命名规则
pytest
姚青&4 天前
Pytest 测试用例结构
测试用例·pytest
Youngchatgpt4 天前
如何在 Excel 中使用 ChatGPT:自动化任务和编写公式
人工智能·chatgpt·自动化·excel
开开心心就好4 天前
安卓开源应用,超时提醒紧急人护独居安全
windows·决策树·计算机视觉·pdf·计算机外设·excel·动态规划
D_C_tyu4 天前
Vue3 + Element Plus | el-table 多级表头表格导出 Excel(含合并单元格、单元格居中)第二版
vue.js·elementui·excel