首页 > 其他分享 >pytest常用hook函数

pytest常用hook函数

时间:2022-08-15 22:55:17浏览次数:44  
标签:函数 item items terminalreporter hook pytest print 用例

pytest_runtest_makereport

说明:收集每个用例三个阶段的执行结果

  1. 先执行when='setup' 返回前置的执行结果
  2. 然后执行when='call' 返回用例步骤的执行结果
  3. 最后执行when='teardown'返回后置的执行结果

参数:

  • item - 测试用例
  • call - 测试步骤
# conftest.py 
import pytest
 
 
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    print('------------------------------------')
 
    # 获取钩子方法的调用结果
    out = yield
    print('用例执行结果', out)
 
    # 3. 从钩子方法的调用结果中获取测试报告
    report = out.get_result()
 
    print('测试报告:%s' % report)
    print('步骤:%s' % report.when)
    print('nodeid:%s' % report.nodeid)
    print('description:%s' % str(item.function.__doc__))
    print(('运行结果: %s' % report.outcome))

输出:

--------------pytest_runtest_makereport----------------------
用例执行结果 <pluggy.callers._Result object at 0x000001CCA355DCD0>
测试报告:<TestReport 'test_demo1.py::test_01[5-6-7]' when='call' outcome='passed'>
步骤:call
nodeid:test_demo1.py::test_01[5-6-7]
description:None
运行结果: passed

pytest_terminal_summary

说明:收集测试结果,统计用例

参数:

  • terminalreporter (_pytest.terminal.TerminalReporter) – 内部使用的终端测试报告对象
  • exitstatus (int) – 返回给操作系统的返回码
  • config(_pytest.config.Config) - pytest的config对象
#conftest.py
 
import time
from _pytest import terminal
# 上海-悠悠
 
 
def pytest_terminal_summary(terminalreporter, exitstatus, config):
    '''收集测试结果'''
    print("===============pytest_terminal_summary===================")
    print(terminalreporter.stats)
    print("total:", terminalreporter._numcollected)
    print('passed:', len(terminalreporter.stats.get('passed', [])))
    print('failed:', len(terminalreporter.stats.get('failed', [])))
    print('error:', len(terminalreporter.stats.get('error', [])))
    print('skipped:', len(terminalreporter.stats.get('skipped', [])))
    # terminalreporter._sessionstarttime 会话开始时间
    duration = time.time() - terminalreporter._sessionstarttime
    print('total times:', duration, 'seconds')

输出:

===============pytest_terminal_summary===================
{'warnings': [WarningReport(message="C:\\ProgramData\\Anaconda3\\lib\\site-packages\\pyreadline\\py3k_compat.py:8: DeprecationWarning: Using or importing the ABCs fro
m 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.9 it will stop working\n  return isinstance(x, collections.Callable)\n", no
deid='', fslocation=('C:\\ProgramData\\Anaconda3\\lib\\site-packages\\pyreadline\\py3k_compat.py', 8))], 'error': [<TestReport 'test_demo1.py::test_01[1-2-3]' when='s
etup' outcome='failed'>, <TestReport 'test_demo1.py::test_01[5-6-7]' when='setup' outcome='failed'>, <TestReport 'test_demo1.py::test_01[r-t-u]' when='setup' outcome=
'failed'>], '': [<TestReport 'test_demo1.py::test_01[1-2-3]' when='teardown' outcome='passed'>, <TestReport 'test_demo1.py::test_01[5-6-7]' when='teardown' outcome='p
assed'>, <TestReport 'test_demo1.py::test_01[r-t-u]' when='teardown' outcome='passed'>]}
total: 3
passed: 0
failed: 0
error: 3
skipped: 0
total times: 0.07572793960571289 seconds

pytest_collection_modifyitems

说明:用于收集测试用例,且在测试用例收集完毕之后被调用。

参数:

  • session - 会话对象
  • config - 配置对象
  • items - 用例对象列表;改变items里面用例的顺序就可以改变用例的执行顺序了
def pytest_collection_modifyitems(items):
    """
    用于收集测试用例
    :return:
    """
    # 测试用例收集完成时,将收集到的item的name和nodeid的中文显示在控制台上
    for item in items:
        print(item.name)
        item.name = item.name.encode("utf-8").decode("unicode_escape")
        print(item.nodeid)
        item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")
    # 打印收集到的所有用例
    print("收集到的所有用例:", items)
    # 通过改变items列表用例位置来改变用例执行顺序,如调换前面两条用例的顺序
    items[0],items[1] = items[1],items[0]

标签:函数,item,items,terminalreporter,hook,pytest,print,用例
From: https://www.cnblogs.com/roronoazoro77/p/16586670.html

相关文章

  • Python调用函数模板
    内容概要函数阶段语法结构定义调用返回值参数名称空间闭包函数装饰器(难点)递归函数、二分法、匿名函数、三元表达式、列表生成式迭代器、生成器常见内置函数函数......
  • 《初等数学概览,第一卷,实数与函数》习题选做 An Excursion through Elementary Mathema
    最近在看AntonioCaminhaMunizNeto的AnExcursionthroughElementaryMathematics,VolumeIRealNumbersandFunctions这本书,在这里随便写点课后练习。英语水平......
  • Balanced Tree (数学函数式子的处理)
    题目大意•求n个点组成的每个节点都满足左右子树大小相差至多1的二叉树个数.•0≤n<264.•关键词:计数2022-暑假-VirtualJudge(vjudge.net)思路:直接用......
  • Python-09_01函数参数的传递
    参数传递:在Python中,类型属于对象,变量是没有类型的:如Str=‘hello’;Str=50,在以上代码中,hello是string类型的,50是整型,而变量Str是没有类型的,它仅仅是一个对象的引用(指针),......
  • Python-09_02函数参数类型
    Python函数参数类型:必备参数、关键字参数、缺省参数、任意个数参数。必备参数须以正确的顺序传入函数,也叫做位置参数,即参数是通过位置进行匹配的,从左到右,依次进行匹配,这个......
  • 欧拉函数
    欧拉函数acwing873.欧拉函数定义欧拉函数phi(n)表示1~n中互质的数的个数(若n为质数,这phi(n)=n-1)欧拉函数公式已知则欧拉函数的公式:\[\varphi(n)=N(1-\frac{1......
  • Pytest框架 — 07、Pytest的Fixture(部分前后置)(二)
    目录4、Fixture的相互调用5、Fixture复用6、Fixture缓存返回结果7、Fixture的后置处理(一)使用yield关键字实现后置(二)使用addfinalizer关键字实现后置(三)yield和addfinalizer......
  • Python-09函数基础、形参、实参
    Python3函数函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。函数能提高应用的模块性,和代码的重复利用率。你已经知道Python提供了许多内建函数,比如print......
  • flask中偏函数的应用
    函数在执行时,要带上所有必要的参数进行调用。但是,有时参数可以在函数被调用之前提前获知。这种情况下,一个函数有一个或多个参数预先就能用上,以便函数能用更少的参数进行调......
  • pytest中文文档教程(五)pytest钩子函数大全
    前言​ 前几篇文章介绍了pytest点的基本使用,掌握前面pytest的基本使用已经插件开发,要开发pytest插件就离不开pytest的钩子函数,就可以满足工作中编写用例和进行自动化测试......