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 @ 2022-09-09 19:38  小小滴人a  阅读(64)  评论(0编辑  收藏  举报