使用 YAML 文件编写测试用例是一种结构化的方式,常用于配置文件和数据驱动测试。虽然 pytest 本身不直接支持 YAML 格式的测试用例,但你可以通过自定义读取 YAML 文件并在测试中使用其内容来实现。以下是如何做到这一点的步骤。
1. 安装所需库
首先,确保你已经安装了 PyYAML 库,用于处理 YAML 文件:
pip install pyyaml
2. 创建 YAML 文件
创建一个 YAML 文件,如 test_data.yml,并在其中定义测试用例。例如:
# test_data.yml
test_cases:
- input: [1, 2]
expected: 3
- input: [10, 20]
expected: 30
- input: [5, 5]
expected: 10
3. 编写测试代码
在测试文件中,使用 pytest 和 PyYAML 读取 YAML 文件并提取测试数据。以下是一个示例:
# test_calculator.py
import pytest
import yaml
def add(a, b):
return a + b
def load_test_cases():
with open("test_data.yml", "r") as file:
return yaml.safe_load(file)["test_cases"]
@pytest.mark.parametrize("test_case", load_test_cases())
def test_add(test_case):
input_data = test_case["input"]
expected = test_case["expected"]
result = add(*input_data)
assert result == expected
解释代码
- 加载测试用例:
load_test_cases函数读取test_data.yml文件并返回测试用例列表。 - 参数化测试:使用
@pytest.mark.parametrize装饰器,将每个测试用例传递给测试函数test_add。 - 运行测试:通过
add函数计算结果并进行断言检查。
4. 运行测试
在命令行中运行以下命令运行测试:
pytest test_calculator.py
5. 处理异常
如果你想在 YAML 文件中也包含异常测试用例,可以在 YAML 中添加另一个字段来表示预期的异常。例如:
# test_data.yml
test_cases:
- input: [1, 2]
expected: 3
- input: [10, 20]
expected: 30
- input: [5, 5]
expected: 10
- input: [1, 0]
expected_exception: ZeroDivisionError
然后在测试代码中处理这个字段:
@pytest.mark.parametrize("test_case", load_test_cases())
def test_add(test_case):
input_data = test_case["input"]
expected = test_case.get("expected")
expected_exception = test_case.get("expected_exception")
if expected_exception:
with pytest.raises(expected_exception):
add(*input_data)
else:
result = add(*input_data)
assert result == expected
总结
通过将测试用例定义在 YAML 文件中,你可以实现数据驱动测试,增强测试的可读性和可维护性。结合 pytest 和 PyYAML,你能够灵活地管理和组织测试数据。