pytest-mark 参数化

 

在类前或用例前用pytest.mark.parametrize ,可进行参数化

 传参方式比较灵活,有很多种,下面是列出的几种方式,其他的可自行研究

@pytest.mark.parametrize("参数名",列表)

源码:

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

:param 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.

翻译:

        参数名:字符串的形式存在一个或多个参数,用逗号分隔 , 或者用参数字符串的列表或元组

  参数:如果是一个,则用list;

                  如果多个,参数必须以列表中元组的形式,每一个元组对应一组参数值

  • 单个参数:

         只传单个参数的值即可

    @pytest.mark.parametrize("a",["test123456","test2222"])
    def test_a(self,a):
        print(a)

 

        运行结果:

 

 

 

  • 多个参数

      以元组的形式传入多个参数的值,一个元组代表一组参数的值

     例如:第一组a=1,b=2

                第二组a=3,b=4

    @pytest.mark.parametrize("a,b",[(1,2),(3,4)])
    def test_two_param(self,a,b):
        print(a+b)

       运行结果:

 

 

          参数名以列表的传入

    @pytest.mark.parametrize(["a","b","c"],[(1,2,3),(3,4,7)])
    def test_list(self,a,b,c):
        assert a+b == c
        print(a+b)

  运行结果:

 

 

  

      单个多次传入多个参数,排列组合传入

    a = (1,2,3)
    b = (4,5)
    @pytest.mark.parametrize("test_a",a)
    @pytest.mark.parametrize("test_b",b)
    def test_2_param(self,test_a,test_b):
        print(test_a*test_b)

  运行结果

 

  •  json格式传入参数

        调用时,在名称后面加.items()读取内容

    data1 = {
    "test1":"test1",
    "test2":"test2"
    }
    @pytest.mark.parametrize("test",data1.items())
    def test_json(self,test):
        print(test)

  运行结果

 

Tags: