pytest之parametrize参数化

本文介绍了pytest的parametrize参数化功能,包括源码解读、单个和多个参数化用法、标记数据以及用例ID的设定。通过示例展示了如何使用parametrize进行测试用例的创建,并提到了与unittest的ddt数据驱动的区别。文章末尾提供了相关项目实战资源和福利。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章末尾给大家留了大量福利哟

前言

我们都知道pytest和unittest是兼容的,但是它也有不兼容的地方,比如ddt数据驱动,测试夹具fixtures(即setup、teardown)这些功能在pytest中都不能使用了,因为pytest已经不再继承unittest了。 

不使用ddt数据驱动那pytest是如何实现参数化的呢?答案就是mark里自带的一个参数化标签。

 

 

一、源码解读 

​ 关键代码:@pytest.mark.parametrize

​ 我们先看下源码:def parametrize(self,argnames, argvalues, indirect=False, ids=None, scope=None):,按住ctrl然后点击对应的函数名就可查看源码。

    def parametrize(self,argnames, argvalues, indirect=False, ids=None, scope=None):
        """ Add new invocations to the underlying test function using the list
        of argvalues for the given argnames.  Parametrization is performed
        during the collection phase.  If you need to setup expensive resources
        see about setting indirect to do it rather at test setup time.

        :arg argnames: a comma-separated string denoting one or more argument
                       names, or a list/tuple of argument strings.

        :arg argvalues: The list of argvalues determines how often a
            test is invoked with different argument values.  If only one
            argname was specified argvalues is a list of values.  If N
            argnames were specified, argvalues must be a list of N-tuples,
            where each tuple-element specifies a value for its respective
            argname.

        :arg indirect: The list of argnames or boolean. A list of arguments'
            names (self,subset of argnames). If True the list contains all names from
            the argnames. Each argvalue corresponding to an argname in this list will
            be passed as request.param to its respective argname fixture
            function so that it can perform more expensive setups during the
            setup phase of a test rather than at collection time.

        :arg ids: list of string ids, or a callable.
            If strings, each is corresponding to the argvalues so that they are
            part of the test id. If None is given as id of specific test, the
            automatically generated id for that argument will be used.
            If callable, it should take one argument (self,a single argvalue) and return
            a string or return None. If None, the automatically generated id for that
            argument will be used.
            If no ids are provided they will be generated automatically from
            the argvalues.

        :arg scope: if specified it denotes the scope of the parameters.
            The scope is used for grouping tests by parameter instances.
         
pytest中的参数化装饰器parametrize可以用于为函数或类添加多个参数组合,生成多个测试用例。参数的组合是根据给定的参数值列表来生成的。 具体使用方式如下: 1. 使用装饰器@parametrize来标记需要参数化的测试函数或测试类。 2. 在@parametrize装饰器中,通过指定参数名和对应的参数值列表来定义参数组合。参数值列表可以是一个可迭代对象,例如列表或元组。 3. 当有多个参数需要参数化时,可以使用多个@parametrize装饰器,每个装饰器对应一个参数。 4. 最终生成的测试用例数量为各个参数值列表长度的乘积。 例如,如果有两个参数a和b,分别有两个和三个取值,那么最终生成的测试用例数量就是2*3=6。 示例代码如下: ```python import pytest data1 = [1, 2] data2 = ['a', 'b', 'c'] @pytest.mark.parametrize('test1', data1) @pytest.mark.parametrize('test2', data2) def test_param(test1, test2): print('\n测试数据:{}-{}'.format(test1, test2)) ``` 在上述示例中,test_param函数有两个参数test1和test2,它们分别可以取data1和data2中的值。最终生成的测试用例数量为2*3=6,每个用例中的参数取值为(1, 'a')、(1, 'b')、(1, 'c')、(2, 'a')、(2, 'b')、(2, 'c')。 另外,参数化装饰器还支持指定参数名,用来在测试用例中展示参数值的名称。例如: ```python import pytest data = [(1, 2, 3), (4, 5, 9)] @pytest.mark.parametrize('a, b, expect', data) def test_param(a, b, expect): print('\n测试数据:{} {}'.format(a, b)) assert a + b == expect ``` 在上述示例中,test_param函数有三个参数a、b和expect,它们分别可以取data中的三元组的值。最终生成的测试用例数量为2,每个用例中的参数取值为(1, 2, 3)和(4, 5, 9)。 通过使用参数化装饰器@parametrize,可以方便地生成多个测试用例,并且在测试报告中展示参数值的组合。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Python测试框架pytest(17)参数化parametrize](https://blog.csdn.net/wangmcn/article/details/120956918)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [pytestparametrize参数化](https://blog.csdn.net/ifling99/article/details/126236312)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值