前言
pytest在執行用例的時候,當用例報錯的時候,如何獲取到報錯的完整內容呢?
當用例有print()打印的時候,如何獲取到打印的內容?
鈎子函數pytest_runtest_makereport
測試用例如下,參數化第一個用例成功,第二個失敗
import pytest
import time
"""
作者:上海-悠悠
python QQ交流群:730246532
聯系微信/QQ: 283340479
"""
@pytest.fixture()
def login():
print("login first----------")
@pytest.mark.parametrize(
"user, password",
[
["test1", "123456"],
["test2", "123456"],
]
)
def test_a(login, user, password):
"""用例描述:aaaaaa"""
time.sleep(2)
print("---------打印的內容-------")
print('傳入參數 user->{}, password->{}'.format(user, password))
assert user == "test1"
使用鈎子函數pytest_runtest_makereport 可以獲取用例執行過程中生成的報告
import pytest
"""
作者:上海-悠悠
python QQ交流群:730246532
聯系微信/QQ: 283340479
"""
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
out = yield # 鈎子函數的調用結果
res = out.get_result() # 獲取用例執行結果
if res.when == "call": # 只獲取call用例失敗時的信息
print("item(我們說的用例case):{}".format(item))
print("description 用例描述:{}".format(item.function.__doc__))
print("exception異常:{}".format(call.excinfo))
print("exception詳細日志:{}".format(res.longrepr))
print("outcome測試結果:{}".format(res.outcome))
print("duration用例耗時:{}".format(res.duration))
print(res.__dict__)
用例運行成功的日志
test_b.py item(我們說的用例case):<Function test_a[test1-123456]>
description 用例描述:用例描述:aaaaaa
exception異常:None
exception詳細日志:None
outcome測試結果:passed
duration用例耗時:2.0006444454193115
{'nodeid': 'test_b.py::test_a[test1-123456]',
'location': ('test_b.py', 8, 'test_a[test1-123456]'),
'keywords': {'test1-123456': 1, 'parametrize': 1, 'test_b.py': 1, 'test_a[test1-123456]': 1, 'myweb': 1, 'pytestmark': 1},
'outcome': 'passed',
'longrepr': None,
'when': 'call',
'user_properties': [],
'sections': [('Captured stdout setup', 'login first----------\n'), ('Captured stdout call', '---------打印的內容-------\n傳入參數 user->test1, password->123456\n')],
'duration': 2.0006444454193115,
'extra': []}
用例運行失敗的日志
item(我們說的用例case):<Function test_a[test2-123456]>
description 用例描述:用例描述:aaaaaa
exception異常:<ExceptionInfo AssertionError("assert 'test2' == 'test1'\n - test1\n ? ^\n + test2\n ? ^",) tblen=1>
exception詳細日志:login = None, user = 'test2', password = '123456'
@pytest.mark.parametrize(
"user, password",
[
["test1", "123456"],
["test2", "123456"],
]
)
def test_a(login, user, password):
"""用例描述:aaaaaa"""
time.sleep(2)
print("---------打印的內容-------")
print('傳入參數 user->{}, password->{}'.format(user, password))
> assert user == "test1"
E AssertionError: assert 'test2' == 'test1'
E - test1
E ? ^
E + test2
E ? ^
test_b.py:21: AssertionError
outcome測試結果:failed
duration用例耗時:2.003612995147705
{'nodeid': 'test_b.py::test_a[test2-123456]',
'location': ('test_b.py', 8, 'test_a[test2-123456]'),
'keywords': {'parametrize': 1, 'test2-123456': 1, 'test_a[test2-123456]': 1, 'test_b.py': 1, 'myweb': 1, 'pytestmark': 1},
'outcome': 'failed',
'longrepr': ExceptionChainRepr(chain=[(ReprTraceback(reprentries=[ReprEntry(lines=[' @pytest.mark.parametrize(', ' "user, password",', ' [', ' ["test1", "123456"],', ' ["test2", "123456"],', ' ]', ' )', ' def test_a(login, user, password):', ' """用例描述:aaaaaa"""', ' time.sleep(2)', ' print("---------打印的內容-------")', " print('傳入參數 user->{}, password->{}'.format(user, password))", '> assert user == "test1"', "E AssertionError: assert 'test2' == 'test1'", 'E - test1', 'E ? ^', 'E + test2', 'E ? ^'], reprfuncargs=ReprFuncArgs(args=[('login', 'None'), ('user', "'test2'"), ('password', "'123456'")]), reprlocals=None, reprfileloc=ReprFileLocation(path='test_b.py', lineno=21, message='AssertionError'), style='long')], extraline=None, style='long'), ReprFileLocation(path='D:\\demo\\myweb\\test_b.py', lineno=21, message="AssertionError: assert 'test2' == 'test1'\n - test1\n ? ^\n + test2\n ? ^"), None)]),
'when': 'call',
'user_properties': [],
'sections': [('Captured stdout setup', 'login first----------\n'), ('Captured stdout call', '---------打印的內容-------\n傳入參數 user->test2, password->123456\n')],
'duration': 2.003612995147705,
'extra': []}
out.get_result() 用例執行結果
out.get_result() 返回用例執行的結果,主要有以下屬性
- 'nodeid': 'test_b.py::test_a[test1-123456]',
- 'location': ('test_b.py', 8, 'test_a[test1-123456]'),
- 'keywords': {'test1-123456': 1, 'parametrize': 1, 'test_b.py': 1, 'test_a[test1-123456]': 1, 'myweb': 1, 'pytestmark': 1},
- 'outcome': 'passed',
- 'longrepr': None,
- 'when': 'call',
- 'user_properties': [],
- 'sections': [('Captured stdout setup', 'login first----------\n'), ('Captured stdout call', '---------打印的內容-------\n傳入參數 user->test1, password->123456\n')],
- 'duration': 2.0006444454193115,
- 'extra': []
其中sections 就是用例里面print打印的內容了
import pytest
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
out = yield # 鈎子函數的調用結果
res = out.get_result() # 獲取用例執行結果
if res.when == "call": # 只獲取call用例失敗時的信息
print("獲取用例里面打印的內容:{}".format(res.sections))
執行結果:
test_b.py 獲取用例里面打印的內容:[('Captured stdout setup', 'login first----------\n'), ('Captured stdout call', '---------打印的內容-------\n傳入參數 user->test1, password->123456\n')]
.獲取用例里面打印的內容:[('Captured stdout setup', 'login first----------\n'), ('Captured stdout call', '---------打印 的內容-------\n傳入參數 user->test2, password->123456\n')]
可以優化下輸出
import pytest
"""
作者:上海-悠悠
python QQ交流群:730246532
聯系微信/QQ: 283340479
"""
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
out = yield # 鈎子函數的調用結果
res = out.get_result() # 獲取用例執行結果
if res.when == "call": # 只獲取call用例失敗時的信息
for i in res.sections:
print("{}: {}".format(*i))
運行結果
collected 2 items
test_b.py Captured stdout setup: login first----------
Captured stdout call: ---------打印的內容-------
傳入參數 user->test1, password->123456
.Captured stdout setup: login first----------
Captured stdout call: ---------打印的內容-------
傳入參數 user->test2, password->123456
網易雲完整視頻課程《pytest+yaml 框架使用與開發》https://study.163.com/course/courseMain.htm?courseId=1213419817&share=2&shareId=480000002230338
報名咨詢wx:283340479 (已報名的同學學習過程中有問題,都可以協助解決)