pytest 参数化parametrize

该博客介绍了如何使用Pytest库进行测试用例的参数化,包括单个用例的参数化以及整个测试类的数据驱动。通过`@pytest.mark.parametrize`装饰器,可以方便地为测试输入和预期结果提供多组数据,提高测试覆盖率。示例中展示了如何处理字符串运算和字典数据类型的测试场景。
摘要由CSDN通过智能技术生成

在测试用例的前面加上:
@pytest.mark.parametrize(“参数名”,列表数据)
参数名:用来接收每一项数据,并作为测试用例的参数。
列表数据:一组测试数据。

1.单用例–参数

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
 
# 参数化
@pytest.mark.parametrize("test_input, expected", [("3+4", 9), ("2+5", 7), ("6*9", 48)])
def test_case(test_input, expected):
    print(f"测试数据{test_input}, 预期结果{expected}")
    assert eval(test_input) == expected

2.多用例–装饰器类
当装饰器 @pytest.mark.parametrize 装饰测试类时,会将数据集合传递给类的所有测试用例方法

import pytest
my_data = [(1, 2, 3), (4, 5, 9)]

datas_dict = [
    {"user": "Tests1", "pwd":"123456"},
    {"user": "Tests2", "pwd":"123456"}  
]

# 参数为列表中嵌套元组
@pytest.mark.parametrize("a, b, expect", my_data)
class TestParametrize: 
    def test_parametrize_case1(self, a, b, expect):
        print("\n测试用例case1 测试数据为{}+{}".format(a, b))
        assert a + b == expect

# 参数为列表中嵌套字典
@pytest.mark.parametrize('dic', datas_dict)
def test_parametrize_case(dic):
    print(f'测试数据为\n{dic}')
    print(f'user:{dic["user"]}, pwd:{dic["pwd"]}')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值