天天看點

pytest學習(四)- @pytest.mark.parametrize 參數化的使用

一、前言

Pytest中參數化文法

@pytest.mark.parametrize(‘參數名’,list) 可以實作測試用例參數化

  • 如果隻有一個參數,裡面則是值的清單如:@pytest.mark.parametrize(“username”, [“yy”, “yy2”,

    “yy3”]) 或者是 @pytest.mark.parametrize([“username”], [“yy”, “yy2”, “yy3”])

  • 如果有多個參數,則需要用元組來存放值,一個元組對應一組參數的值,如:@pytest.mark.parametrize(“name,pwd”,

    [(“yy1”, “123”), (“yy2”, “123”), (“yy3”, “123”)])

二、使用

1、一個參數一個值

示例代碼:

@pytest.mark.parametrize('input', ['輸入值1'])
def test01(input):
    print('\n ', input)
    assert input == '輸入值1'
           

結果:

pytest學習(四)- @pytest.mark.parametrize 參數化的使用

2、一個參數多個值

示例代碼:

@pytest.mark.parametrize('input', ['輸入值1','輸入值2','輸入值3','輸入值4'])
def test01(input):
    print(input)
           

結果:

pytest學習(四)- @pytest.mark.parametrize 參數化的使用

3、多個參數多個值

代碼示例1:

@pytest.mark.parametrize('user, pwd', [('root', '123'), ('admin', '456')])
def test_03(user, pwd):
    db = {
        'root': '202cb962ac59075b964b07152d234b70',
        'admin': '250cf8b51c773f3f8dc8b4be867a9a02'
    }

    assert hashlib.md5(pwd.encode()).hexdigest() == db[user]
           

結果:

pytest學習(四)- @pytest.mark.parametrize 參數化的使用

4、多個參數混合使用

代碼示例,類似于笛卡爾積:

data1 = ['A', 'B']
data2 = ['1', '2']
data3 = ['python', 'C++', 'java', 'shell']


@pytest.mark.parametrize('a', data1)
@pytest.mark.parametrize('b', data2)
@pytest.mark.parametrize('c', data3)
def test_04(a, b, c):
    print(f"生成新的組合為[{a} {b} {c}]")
           

結果:

pytest學習(四)- @pytest.mark.parametrize 參數化的使用

5、參數化,傳入字典資料

代碼示例:

json = [{'user': 'admin', 'pwd': '123'}, {'user': 'root', 'pwd': '456'}]


@pytest.mark.parametrize('json', json)
def test_06(json):
    print(f'\n {json}')
    print(f'user: {json["user"]}, pwd: {json["pwd"]}')
           

結果:

pytest學習(四)- @pytest.mark.parametrize 參數化的使用

6、裝飾測試類

代碼示例:

data6 = [(1, 2, 3), (2, 3, 5)]


@pytest.mark.parametrize('a,b,expect', data6)
class TestCase():
    def test01(self, a, b, expect):
        print(f'\n函數01 測試資料:{a}+{b}, 結果為{expect}')
        assert a + b == expect


    def test02(self, a, b, expect):
        print(f'\n函數02 測試資料:{a}+{b}, 結果為{expect}')
        assert a + b == expect
           

結果:

pytest學習(四)- @pytest.mark.parametrize 參數化的使用

小結:

當裝飾器 @pytest.mark.parametrize 裝飾測試類時,會将資料集合傳遞給類的所有測試用例方法

繼續閱讀