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
多參數+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}")
注意:必須在同目錄下創建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")
笛卡爾積
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}")