zoukankan      html  css  js  c++  java
  • pytest文档78 钩子函数pytest_runtest_makereport获取用例执行报错内容和print内容 上海

    前言

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

    钩子函数pytest_runtest_makereport

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

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

    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__)
    

    用例运行成功的日志

    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
    
    
    @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
    
  • 相关阅读:
    Httpclient的应用
    sql树形结构
    发送邮件
    关于多态的思考
    java集合整体结构
    应用--对HashMap进行排序(转为LinkedHashMap)
    初识POI操作Excel
    常用的开发工具
    [redis]Redis Transaction
    [ajax] quick double or multiple click ajax submit cause chrome explorer's error snatshot
  • 原文地址:https://www.cnblogs.com/yoyoketang/p/15600793.html
Copyright © 2011-2022 走看看