天天看點

軟體測試/測試開發丨Pytest參數化用例學習筆記

作者:測試人666

本文為霍格沃茲測試開發學社學員學習筆記分享

原文連結:Pytest參數化用例 - 學習筆記 - 測試人社群

Pytest參數化用例

參數化:通過參數的方式傳遞資料,進而實作資料與腳本分離,并且可以實作用例的重複生成與執行。

裝飾器:@pytest.mark.parametrize

單參數

import pytest

search_list = ["appium","selenium","pytest"]

# 參數化實作測試用例的動态生成
# 第一種:單參數情況,每一條測試資料都會生成一條測試用例
@pytest.mark.parametrize("search_key",["appium","selenium","pytest"," "])
def test_search(search_key):
    assert search_key in search_list           
軟體測試/測試開發丨Pytest參數化用例學習筆記

多參數+ids參數重命名

import pytest

# 第二種:多參數情況
@pytest.mark.parametrize("username,password",[["right","right"],
                                              ["wrong","wrong"],
                                              [" ","right"],
                                              ["right"," "]
                                              ],
                         # 用例重命名-添加 ids 參數,将别名放在清單中
                         # ids=["right username and right password","wrong username and wrong password","username is null","password is null"])
                         # ids支援中文
                         ids=["正确的使用者名和密碼","錯誤的使用者名和密碼","使用者名為空","密碼為空"])

def test_login(username,password):
    print(f"登入的使用者名:{username}, {password}")           
軟體測試/測試開發丨Pytest參數化用例學習筆記

注意:必須在同目錄下建立conftest.py檔案,将下面内容添加進去,運作腳本後,才可以正常顯示中文的重命名。

def pytest_collection_modifyitems(items):
    """
    測試用例收集完成時,将收集到的用例名name和用例辨別nodeid的中文資訊顯示在控制台上
    """
    for i in items:
        i.name=i.name.encode("utf-8").decode("unicode_escape")
        i._nodeid=i.nodeid.encode("utf-8").decode("unicode_escape")           
軟體測試/測試開發丨Pytest參數化用例學習筆記

笛卡爾積

import pytest

@pytest.mark.parametrize("a",[1,2,3])
@pytest.mark.parametrize("b",["你","好","啊"])
@pytest.mark.parametrize("c",["a","b","c"])
def test_param(a,b,c):
    print(f"笛卡爾積形式的參數化中 a={a},b={b},c={c}")           
軟體測試/測試開發丨Pytest參數化用例學習筆記