pytest测试框架(六) 参数化与数据驱动

参数化用例

  • @pytest.mark.parametrize(argnames, argvalues)
  • argnames: 要参数化的变量, string(逗号分隔), list, tuple
  • argvalues: 参数化的值,list, list[tuple]
import pytest


class Test_ABC:

    @pytest.mark.parametrize("test_input, expected", [("3+5", 8), ("2+4", 6)])
    def test_abc(self, test_input, expected):
        print(test_input, expected)


if __name__ == '__main__':
    pytest.main(["-s", "test_abc.py"])
运行结果:
test_abc.py 3+5 8
.2+4 6
.

数据驱动

  • 使用pytest和yaml文件相结合,pyyaml模块来处理yaml格式数据,主要使用 yaml.safe_dump() 和 yaml.safe_load() 函数将python对象和yaml格式数据相互转化
  • 安装:pip install PyYAML
  • 案例:
    • 创建data.yml文件:
- - 1
  - 2
- - 20
  - 30
创建test_abc.py
import pytest
import yaml


class Test_ABC:

    @pytest.mark.parametrize("a, b", yaml.safe_load(open("data.yml")))
    def test_abc(self, a, b):
        print(f"a + b = {a + b}")


if __name__ == '__main__':
    pytest.main(["-s", "test_abc.py"])
运行结果:
test_abc.py a + b = 3
.a + b = 50
.
posted @   小小滴人a  阅读(66)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示