Python 基于YAML文件的数据驱动测试
前言
数据驱动测试(Data-Driven Testing,DDT)是一种将测试逻辑与测试数据分离的自动化测试方法,其核心是通过外部数据源动态驱动测试执行。
外部数据源包括:CSV 文件、Excel 表格、YAML 文件、数据库等。
在数据驱动测试中,测试数据与测试逻辑是分离的,这样就可以专注于编写测试逻辑,而无需担心测试数据的变化。
准备
安装插件:
pip install pyyaml
示例:
1、从yaml文件读取测试数据
login_data.yaml
login_tests:
- username: "admin"
password: "123456"
expected_status_code: 200
expected_message: "Login successful"
- username: "wronguser"
password: "wrongpassword"
expected_status_code: 401
expected_message: "Invalid credentials"
test_login.py
import yaml
# 读取 YAML 文件
with open("data/login_data.yaml", "r", encoding="utf-8") as f:
data = yaml.safe_load(f)
# 打印读取结果
print(data)
test_cases = data['login_tests']
for case in test_cases:
print("用户名:", case['username'])
print("密码:", case['password'])
print("预期状态码:", case['expected_status_code'])
print("预期消息:", case['expected_message'])
print("-" * 30)
2、@pytest.mark.parametrize
基础用法
最常用的数据驱动方式,直接在测试函数上参数化:
import pytest
# 单个参数
@pytest.mark.parametrize("input_value", [1, 2, 3])
def test_square(input_value):
assert input_value ** 2 == input_value * input_value
# 多个参数
@pytest.mark.parametrize("a,b,expected", [
(1, 2, 3),
(5, -1, 4),
(0, 0, 0)
])
def test_add(a, b, expected):
assert a + b == expected
3、参数化 fixture
通过 fixture 实现更灵活的数据供给:
import pytest
@pytest.fixture(params=["apple", "banana", "orange"])
def fruit(request):
return request.param
def test_fruit_length(fruit):
assert len(fruit) >= 5
适用场景:
- 多个测试函数需要共享同一组测试数据
- 需要数据预处理/后处理时
评论区