pytest参数化测试用例

  • 通过参数的方式传递数据,从而实现数据和脚本分离。
  • 并且可以实现用例的重复生成与执行。
  • 1、pytest 参数化实现方法

  • 装饰器:@pytest.mark.parametrize
  • @pytest.mark.parametrize("username,password",[["right","right"], ["wrong","wrong"]])
    def test_param(username,password):
        login(username,password

    2、参数化:多参数情况

  • 将数据放在列表嵌套元组中
  • 将数据放在列表嵌套列表中
  • # 数据放在元组中
    @pytest.mark.parametrize("test_input,expected",[
        ("3+5",8),("2+5",7),("7+5",12)
    ])
    def test_mark_more(test_input,expected):
        assert eval(test_input) == expected
    # 数据放在列表中
    @pytest.mark.parametrize("test_input,expected",[
        ["3+5",8],["2+5",7],["7+5",12]
    ])
    def test_mark_more(test_input,expected):
        assert eval(test_input) == expected

    3、参数化:用例重命名-添加 ids 参数

  • 通过ids参数,将别名放在列表中
  • 几个参数,就有几个别名。如果数量不等会报错
  • @pytest.mark.parametrize("test_input,expected",[
        ("3+5",8),("2+5",7),("7+5",12)
    ],ids=['add_3+5=8','add_2+5=7','add_3+5=12'])
    def test_mark_more(test_input,expected):
        assert eval(test_input) == expected

    4、参数化:用例重命名-添加 ids 参数(中文)

  • # 创建conftest.py 文件 ,将下面内容添加进去,运行脚本
    def pytest_collection_modifyitems(items):
        """
        测试用例收集完成时,将收集到的用例名name和用例标识nodeid的中文信息显示在控制台上
        """
        for i in items:
            i.name=i.name.encode("utf-8").decode("unicode_escape")
            i._nodeid=i.nodeid.encode("utf-8").decode("unicode_escape")
    @pytest.mark.parametrize("test_input,expected",[
        ("3+5",8),("2+5",7),("7+5",12)
    ],ids=["3和5相加","2和5相加","7和5相加"])
    def test_mark_more(test_input,expected):
        assert eval(test_input) == expected

    5、参数化:笛卡尔积

  • 两组数据
    • a=[1,2,3]
    • b=[a,b,c]
  • 对应有几种组合形势 ?
    • (1,a),(1,b),(1,c)
    • (2,a),(2,b),(2,c)
    • (3,a),(3,b),(3,c)
  • @pytest.mark.parametrize("b",["a","b","c"])
    @pytest.mark.parametrize("a",[1,2,3])
    def test_param1(a,b):
        print(f"笛卡积形式的参数化中 a={a} , b={b}")

    参数

    由近至远执行装饰器 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值