侧边栏壁纸
博主头像
一朵云的博客博主等级

拥抱生活,向阳而生。

  • 累计撰写 107 篇文章
  • 累计创建 28 个标签
  • 累计收到 7 条评论

目 录CONTENT

文章目录

Python -- 基于YAML文件的数据驱动测试

一朵云
2024-01-07 / 0 评论 / 0 点赞 / 636 阅读 / 3359 字

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)

image-fhyv.png

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

适用场景

  • 多个测试函数需要共享同一组测试数据
  • 需要数据预处理/后处理时
0

评论区