前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >pytest文档78 - 钩子函数pytest_runtest_makereport获取用例执行报错内容和print内容

pytest文档78 - 钩子函数pytest_runtest_makereport获取用例执行报错内容和print内容

作者头像
上海-悠悠
发布2021-11-26 15:44:54
8470
发布2021-11-26 15:44:54
举报

前言

pytest在执行用例的时候,当用例报错的时候,如何获取到报错的完整内容呢? 当用例有print()打印的时候,如何获取到打印的内容?

钩子函数pytest_runtest_makereport

测试用例如下,参数化第一个用例成功,第二个失败

代码语言:javascript
复制
import pytest
import time

@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 可以获取用例执行过程中生成的报告

代码语言:javascript
复制
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("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__)

用例运行成功的日志

代码语言:javascript
复制
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': []}

用例运行失败的日志

代码语言:javascript
复制
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打印的内容了

代码语言:javascript
复制
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))

执行结果:

代码语言:javascript
复制
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')]

可以优化下输出

代码语言:javascript
复制
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用例失败时的信息
        for i in res.sections:
            print("{}: {}".format(*i))

运行结果

代码语言:javascript
复制
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
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-11-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 从零开始学自动化测试 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 钩子函数pytest_runtest_makereport
  • out.get_result() 用例执行结果
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档