本文主要是介绍pytest之parametrize参数化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章末尾给大家留了大量福利哟
前言
我们都知道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 listof argvalues for the given argnames. Parametrization is performedduring the collection phase. If you need to setup expensive resourcessee about setting indirect to do it rather at test setup time.:arg argnames: a comma-separated string denoting one or more argumentnames, or a list/tuple of argument strings.:arg argvalues: The list of argvalues determines how often atest is invoked with different argument values. If only oneargname was specified argvalues is a list of values. If Nargnames were specified, argvalues must be a list of N-tuples,where each tuple-element specifies a value for its respectiveargname.:arg indirect: The list of argnames or boolean. A list of arguments'names (self,subset of argnames). If True the list contains all names fromthe argnames. Each argvalue corresponding to an argname in this list willbe passed as request.param to its respective argname fixturefunction so that it can perform more expensive setups during thesetup 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 arepart of the test id. If None is given as id of specific test, theautomatically generated id for that argument will be used.If callable, it should take one argument (self,a single argvalue) and returna string or return None. If None, the automatically generated id for thatargument will be used.If no ids are provided they will be generated automatically fromthe argvalues.:arg scope: if specified it denotes the scope of the parameters.The scope is used for grouping tests by parameter instances.It will also override any fixture-function defined scope, allowingto set a dynamic scope using test context or configuration."""
我们来看下主要的四个参数:
参数1-argnames:一个或多个参数名,用逗号分隔的字符串,如"arg1,arg2,arg3",或参数字符串的列表/元组。需要注意的是,参数名需要与用例的入参一致。
参数2-argvalues:参数值,必须是列表类型;如果有多个参数,则用元组存放值,一个元组存放一组参数值,元组放在列表。(实际上元组包含列表、列表包含列表也是可以的,可以动手试一下)
# 只有一个参数username时,列表里都是这个参数的值:
@pytest.mark.parametrize("username", ["user1", "user2", "user3"])
# 有多个参数username、pwd,用元组存放参数值,一个元组对应一组参数:
@pytest.mark.parametrize("username, pwd", [("user1", "pwd1"), ("user2", "pwd2"), ("use
这篇关于pytest之parametrize参数化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!