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: