前言
使用 pytest.mark.parametrize 參數化的時候,加 ids 參數用例描述有中文時,在控制台輸出會顯示unicode編碼,中文不能正常顯示。
使用 pytest_collection_modifyitems 鈎子函數,對輸出的 item.name 和 item.nodeid 重新編碼。
問題描述
參數化 ids 用例描述有中文
import pytest
# test_ids.py
import pytest
# 作者:上海-悠悠
def login(username, password):
'''登錄'''
# 返回
return {"code": 0, "msg": "success!"}
# 測試數據
test_datas = [
({"username": "yoyo1", "password": "123456"}, "success!"),
({"username": "yoyo2", "password": "123456"}, "success!"),
({"username": "yoyo3", "password": "123456"}, "success!"),
]
@pytest.mark.parametrize("test_input,expected",
test_datas,
ids=[
"輸入正確賬號,密碼,登錄成功",
"輸入錯誤賬號,密碼,登錄失敗",
"輸入正確賬號,密碼,登錄成功",
]
)
def test_login(test_input, expected):
'''測試登錄用例'''
# 獲取函數返回結果
result = login(test_input["username"], test_input["password"])
# 斷言
assert result["msg"] == expected
cmd終端運行 pytest test_ids.py -v
注意 [\u8f93\u5165\u6b63 ...] 這種不叫亂碼,這叫 unicode 編碼
pytest_collection_modifyitems
在項目的根目錄寫個 conftest.py 文件,加以下代碼
def pytest_collection_modifyitems(items):
"""
測試用例收集完成時,將收集到的item的name和nodeid的中文顯示在控制台上
:return:
"""
for item in items:
item.name = item.name.encode("utf-8").decode("unicode_escape")
print(item.nodeid)
item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")
cmd 控制台重新運行