一、钩子函数

钩子函数这个称呼是很多开发语言中都会涉及到的一个东西。

1、理解钩子函数

如何理解钩子函数 - 知乎

2、pytest的钩子函数

Hooks钩子函数是pytest框架预留的函数,通过这些钩子我们可以对pytest 用例收集、用例执行、报告输出等各个阶段进行干预。

pytest插件就是用1个或者多个hook函数,也就是钩子函数构成的。如果想要编写新的插件,或者是仅仅改进现有的插件,都必须通过这个hook函数进行。所以想掌握pytest插件二次开发,必须搞定hook函数。

二、钩子函数分类

pytest中的钩子函数按功能一共分为6类:引导钩子,初始化钩子、用例收集钩子、用例执行钩子、报告钩子、调试钩子。

pytest内置hooks函数源码文件路径:\site-packages\_pytest\hookspec.py

pytest内置hooks函数源码

1、Bootstrapping hooks 引导钩子

引导钩子要求尽早注册插件(内部插件和 setuptools 插件)。

  • pytest_load_initial_conftests(early_config,parser,args): 在命令行选项解析之前实现初始conftest文件的加载。
  • pytest_cmdline_preparse(config,args): (废弃)在选项解析之前修改命令行参数。
  • pytest_cmdline_parse(pluginmanager,args): 返回一个初始化的配置对象,解析指定的args。
  • pytest_cmdline_main(config): 要求执行主命令行动作。默认实现将调用configure hooks和runtest_mainloop。

2、Initialization hooks 初始化钩子

初始化钩子调用插件和conftest.py文件。

  • pytest_addoption(parser): 注册argparse样式的选项和ini样式的配置值,这些值在测试运行开始时被调用一次。
  • pytest_addhooks(pluginmanager): 在插件注册时调用,以允许通过调用来添加新的挂钩
  • pytest_configure(config): 允许插件和conftest文件执行初始配置。
  • pytest_unconfigure(config): 在退出测试过程之前调用。
  • pytest_sessionstart(session): 在Session创建对象之后,执行收集并进入运行测试循环之前调用。
  • pytest_sessionfinish(session,exitstatus): 在整个测试运行完成后调用,就在将退出状态返回系统之前。
  • pytest_plugin_registered(plugin,manager):一个新的pytest插件已注册。

3、Collection hooks 测试用例收集钩子

pytest调用以下钩子函数来收集测试文件及目录。

  • pytest_collection(session): 执行给定会话的收集协议。
  • pytest_collect_directory(path, parent): 在遍历目录以获取集合文件之前调用。
  • pytest_collect_file(path, parent) 为给定的路径创建一个收集器,如果不相关,则创建“无”。
  • pytest_pycollect_makemodule(path: py._path.local.LocalPath, parent) 返回给定路径的模块收集器或无。
  • pytest_pycollect_makeitem(collector: PyCollector, name: str, obj: object) 返回模块中Python对象的自定义项目/收集器,或者返回None。在第一个非无结果处停止
  • pytest_generate_tests(metafunc: Metafunc) 生成(多个)对测试函数的参数化调用。
  • pytest_make_parametrize_id(config: Config, val: object, argname: str) 返回val 将由@ pytest.mark.parametrize调用使用的给定用户友好的字符串表示形式,如果挂钩不知道,则返回None val。
  • pytest_collection_modifyitems(session: Session, config: Config, items: List[Item]) 在执行收集后调用。可能会就地过滤或重新排序项目。
  • pytest_collection_finish(session: Session) 在执行并修改收集后调用。

4、Test running (runtest) hooks 测试运行钩子

运行测试相关的钩子,接收一个pytest.Item对象。

  • pytest_runtestloop(session: Session) 执行主运行测试循环(收集完成后)。
  • pytest_runtest_protocol(item: Item, nextitem: Optional[Item]) 对单个测试项目执行运行测试协议。
  • pytest_runtest_logstart(nodeid: str, location: Tuple[str, Optional[int], str]) 在运行单个项目的运行测试协议开始时调用。
  • pytest_runtest_logfinish(nodeid: str, location: Tuple[str, Optional[int], str])在为单个项目运行测试协议结束时调用。
  • pytest_runtest_setup(item: Item) 调用以执行测试项目的设置阶段。
  • pytest_runtest_call(item: Item) 调用以运行测试项目的测试(调用阶段)。
  • pytest_runtest_teardown(item: Item, nextitem: Optional[Item]) 调用以执行测试项目的拆卸阶段。
  • pytest_runtest_makereport(item: Item, call: CallInfo[None]) 被称为为_pytest.reports.TestReport测试项目的每个设置,调用和拆卸运行测试阶段创建一个。
  • pytest_pyfunc_call(pyfuncitem: Function) 调用基础测试功能。

5、Reporting hooks 测试报告钩子

与会话相关,断言相关的测试报告钩子。

  • pytest_collectstart(collector: Collector) 收集器开始收集。
  • pytest_make_collect_report(collector: Collector) 执行collector.collect()并返回一个CollectReport。
  • pytest_itemcollected(item: Item) 我们刚刚收集了一个测试项目。
  • pytest_collectreport(report: CollectReport) 收集器完成收集。
  • pytest_deselected(items: Sequence[Item]) 要求取消选择的测试项目,例如按关键字。
  • pytest_report_header(config: Config, startdir: py._path.local.LocalPath) 返回要显示为标题信息的字符串或字符串列表,以进行终端报告。
  • pytest_report_collectionfinish(config: Config, startdir: py._path.local.LocalPath, items: Sequence[Item]) 返回成功完成收集后将显示的字符串或字符串列表。
  • pytest_report_teststatus(report: Union[CollectReport, TestReport], config: Config) 返回结果类别,简写形式和详细词以进行状态报告。
  • pytest_terminal_summary(terminalreporter: TerminalReporter, exitstatus: ExitCode, config: Config) 在终端摘要报告中添加一个部分。
  • pytest_fixture_setup(fixturedef: FixtureDef[Any], request: SubRequest) 执行夹具设置执行。
  • pytest_fixture_post_finalizer(fixturedef: FixtureDef[Any], request: SubRequest) 在夹具拆除之后但在清除缓存之前调用,因此夹具结果fixturedef.cached_result仍然可用(不是 None)
  • pytest_warning_captured(warning_message: warnings.WarningMessage, when: Literal[‘config’, ‘collect’, ‘runtest’], item: Optional[Item], location: Optional[Tuple[str, int, str]]) (已弃用)处理内部pytest警告插件捕获的警告。
  • pytest_warning_recorded(warning_message: warnings.WarningMessage, when: Literal[‘config’, ‘collect’, ‘runtest’], nodeid: str, location: Optional[Tuple[str, int, str]]) 处理内部pytest警告插件捕获的警告。
  • pytest_runtest_logreport(report: TestReport) 处理项目的_pytest.reports.TestReport每个设置,调用和拆卸运行测试阶段产生的结果。
  • pytest_assertrepr_compare(config: Config, op: str, left: object, right: object) 返回失败断言表达式中的比较的说明。
  • pytest_assertion_pass(item: Item, lineno: int, orig: str, expl: str) (实验性的)在断言通过时调用。

6、Debugging/Interaction hooks 调试/交互钩子

有几个钩子可以用于特殊报告或与异常交互。

  • pytest_internalerror(excrepr: ExceptionRepr, excinfo: ExceptionInfo[BaseException]) 要求内部错误。返回True以禁止对将INTERNALERROR消息直接打印到sys.stderr的回退处理。
  • pytest_keyboard_interrupt(excinfo: ExceptionInfo[Union[KeyboardInterrupt, Exit]]) 要求键盘中断。
  • pytest_exception_interact(node: Union[Item, Collector], call: CallInfo[Any], report: Union[CollectReport, TestReport]) 在引发可能可以交互处理的异常时调用。
  • pytest_enter_pdb(config: Config, pdb: pdb.Pdb) 调用了pdb.set_trace()。

三、使用钩子函数

1、定制化HTML格式的测试报告

如使用pytest-html插件生成HTML格式的测试报告的时候,可以在conftest文件中使用钩子函数来自定义测试报告内容。

"""
#!/usr/bin/env python
# -*- coding:utf-8 -*-
@Project : pytest-demo
@File : conftest.py
@Author : 057776
@Time : 2022/8/16 15:55"""
from datetime import datetime
from py.xml import html
import pytest# <editor-fold desc="自定义测试报告"># 运行测试前修改环境信息
def pytest_configure(config):config._metadata["foo"] = "bar"# 运行测试后修改环境信息
@pytest.hookimpl(tryfirst=True)
def pytest_sessionfinish(session, exitstatus):session.config._metadata["foo"] = "bar"# 编辑报告标题
def pytest_html_report_title(report):report.title = "My very own title!"# 编辑摘要信息
def pytest_html_results_summary(prefix, summary, postfix):prefix.extend([html.p("foo: bar")])# 测试结果表格
def pytest_html_results_table_header(cells):cells.insert(1, html.th("Time", class_="sortable time", col="time"))cells.pop()def pytest_html_results_table_row(report, cells):cells.insert(1, html.td(datetime.utcnow(), class_="col-time"))cells.pop()
# </editor-fold>

其中 pytest_configure,pytest_sessionfinish是pytest内置的钩子函数。

其它的钩子函数是属于pytest-html插件的,附上pytest-html插件的hooks.py源码:

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.def pytest_html_report_title(report):""" Called before adding the title to the report """def pytest_html_results_summary(prefix, summary, postfix):""" Called before adding the summary section to the report """def pytest_html_results_table_header(cells):""" Called after building results table header. """def pytest_html_results_table_row(report, cells):""" Called after building results table row. """def pytest_html_results_table_html(report, data):""" Called after building results table additional HTML. """

reference:

API Reference — pytest documentation

Pytest权威教程21-API参考-04-钩子(Hooks) - 韩志超 - 博客园

pytest合集(10)— Hook钩子函数相关推荐

  1. pytest合集(4)— 使用pytest-html插件生成HTML测试报告

    1.pytest-html插件安装 pytest-html 是 pytest 的一个插件,它为测试结果生成 HTML 报告. 要求: Python >=3.6 或 PyPy3. pip inst ...

  2. 惜时间_珍惜时间作文合集10篇

    珍惜时间作文合集10篇 在学习.工作或生活中,大家都经常看到作文的身影吧,作文一定要做到主题集中,围绕同一主题作深入阐述,切忌东拉西扯,主题涣散甚至无主题.那要怎么写好作文呢?下面是小编为大家收集的珍 ...

  3. mfc中嵌入python_Python 中的 Hook 钩子函数

    1. 什么是Hook 经常会听到钩子函数(hook function)这个概念,最近在看目标检测开源框架mmdetection,里面也出现大量Hook的编程方式,那到底什么是hook?hook的作用是 ...

  4. pytest合集(7)— Mark标记

    一.mark标记 1.介绍 Pytest提供的mark标记,允许我们标记测试函数,测试类和整个模块.通过不同的标记实现不同的运行策略,如标记冒烟测试用例. 2.特点 使用装饰器@pytest.mark ...

  5. pytest合集(5)— Function函数

    1.pytest.approx 断言两个数字(或两组数字)在某个容差范围内彼此相等. from pytest import approx def test_one():assert 0.1 + 0.2 ...

  6. pytest合集(3)— 命令行参数

    1.命令行参数大全 使用 pytest -h 可以查看 pytest 的命令行参数,有 10 大类共 132 个. 详见:Python pytest 132 个命令行参数用法 - 习久性成 - 博客园 ...

  7. pytest合集(6)— Fixture夹具

    一.关于夹具 1.夹具介绍 简单来说,pytest中的夹具就是用来实现测试前的环境准备,提供测试数据和测试后的环境清理动作.类似于unittest框架里的setup(前置处理),teardown(后置 ...

  8. pytest合集(8)— 测试用例和夹具的参数化

    一.测试用例参数化 pytest.mark.parametrize() 语法糖: parametrize(argnames, argvalues, indirect=False, ids=None,  ...

  9. 人脸识别合集 | 10 ArcFace解析

    转自:https://zhuanlan.zhihu.com/p/76541084 ArcFace/InsightFace(弧度)是伦敦帝国理工学院邓建康等在2018.01发表,在SphereFace基 ...

最新文章

  1. 06-GICv3_v4_overview
  2. 口语语言理解(SLU)最新资源库:综述、数据集、开源论文
  3. 浅谈JavaScript、ES5、ES6
  4. 动态决定viewarea应该加载哪个view
  5. android view过度动画,为View的切换添加过渡动画
  6. phpcmsV9栏目内文章批量移动后,新的内容页模板不生效 -分析篇
  7. 统计学基础一:基础概念
  8. 如何使用Facebook广告为shopify商店引流
  9. 10 个优秀的JavaScript开发框架
  10. iOS开发最新之CocoaPods环境配置教程
  11. Java 8新特性探究(十一)Base64详解
  12. java 程序计数器_JVM入门系列之程序计数器
  13. linux系统进入管理员命令行,电脑如何进入管理员命令提示符
  14. python编程基础-类的使用
  15. 建网站应该买什么云服务器,建网站应该买什么云服务器
  16. 如何在透视表中同时显示客户编码和客户名称
  17. mysql 子链接_MySQL多表查询实例详解【链接查询、子查询等】
  18. http://www.jb51.net/softjc/33896.html(vs2010破解)
  19. 第1章 Redis查阅官网和基本配置
  20. react 打包体积过大_create-react-app andt 打包的 js 文件过大

热门文章

  1. problem 1171
  2. 解决pandas处理json为csv格式时的中文乱码
  3. 基于扩展卡尔曼滤波EKF和模型预测控制MPC,自动泊车场景建模开发
  4. C# 中TextBox控件如何限制输入的字数?
  5. 乌克兰警方揭露国际电话窃听团伙
  6. 中国菜刀,抓包,过狗版
  7. 【WinForm】TextBox只能输入中文,英文,数字,不允许输入特殊字符
  8. [mfc] SetWindowPos函数
  9. Win10设置Path环境变量的方法
  10. 写点代码-分级基金的套利交易