如果想从头学起pytest,可以去看看这个系列的文章!

https://www.cnblogs.com/miki-peng/category/1960108.html


​ 前面已经提到,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.
            It will also override any fixture-function defined scope, allowing
            to set a dynamic scope using test context or configuration.
        """

​ 我们来看下主要的四个参数:

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/miki-peng/p/14736332.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!