
- Pytest 教程
- Pytest - 主页
- Pytest - 简介
- Pytest - 设置环境
- 识别测试文件和函数
- Pytest - 从基本测试开始
- Pytest - 文件执行
- 执行测试套件的子集
- 测试名称的子字符串匹配
- Pytest - 对测试进行分组
- Pytest - 固定装置
- Pytest - conftest.py
- Pytest - 测试参数化
- Pytest - Xfail/Skip 测试
- 在 N 次测试失败时停止测试套件
- Pytest - 并行运行测试
- 测试执行结果为 XML
- Pytest - 总结
- Pytest - 结论
- 有用的 Pytest 资源
- Pytest - 快速指南
- 有用的 Pytest 资源
- Pytest - 讨论
Pytest - 测试参数化
对测试进行参数化是为了在多个输入集上运行测试。我们可以通过使用以下标记来做到这一点 −
@pytest.mark.parametrize
将以下代码复制到一个名为 test_multiplication.py 的文件中 −
import pytest @pytest.mark.parametrize("num, output",[(1,11),(2,22),(3,35),(4,44)]) def test_multiplication_11(num, output): assert 11*num == output
在此测试中,将输入与 11 相乘,并将结果与预期输出进行比较。此测试有 4 组输入,每组有 2 个值 - 一个是要与 11 相乘的数字,另一个是预期结果。
通过运行以下命令执行测试 −
Pytest -k multiplication -v
上述命令将生成以下输出 −
test_multiplication.py::test_multiplication_11[1-11] PASSED test_multiplication.py::test_multiplication_11[2-22] PASSED test_multiplication.py::test_multiplication_11[3-35] FAILED test_multiplication.py::test_multiplication_11[4-44] PASSED ============================================== FAILURES ============================================== _________________ test_multiplication_11[3-35] __________________ num = 3, output = 35 @pytest.mark.parametrize("num, output",[(1,11),(2,22),(3,35),(4,44)]) def test_multiplication_11(num, output): > assert 11*num == output E assert (11 * 3) == 35 test_multiplication.py:5: AssertionError ============================== 1 failed, 3 passed, 8 deselected in 0.08 seconds ==============================
广告