我从所有测试中捕获测试结果并将其写入conftest.py中的html文件。我能够在conftest.py中获取test_name,class_name,module_name和测试结果。我还想捕获给定测试失败的异常。
在这个例子中,test2和test3会失败,我想在我的conftest文件中捕获异常的堆栈跟踪。
test.py
def test1():
assert 1 == 1
def test2():
assert 1 == 2
def test3():
pytest.fail('abc')
conftest.py
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
rep = outcome.get_result()
if rep.when == 'call':
setattr(item, "rep_" + rep.when, rep)
@pytest.fixture(scope="function", autouse=True)
def runtime_report(request):
yield
test_name = request.node.name
class_name = ''
module_name = ''
test_result = ''
parent_type_name = type(request.node.parent).__name__
if parent_type_name == 'Module':
class_name = None
module_name = request.node.parent.name
elif parent_type_name == 'Instance':
class_name = request.node.parent.parent.name
module_name = request.node.parent.parent.parent.name
else:
pytest.fail('Unknown parent %s for node %s' % (
request.node.parent.name,
request.node.name
))
# And then Logic for writing the results to html file below.