pytest 测试框架学习(3):pytest.approx

2023-10-12 00:59

本文主要是介绍pytest 测试框架学习(3):pytest.approx,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

pytest.approx

  • 前言
  • 含义
  • 使用
    • 单数
    • 元祖
    • 字典
    • numpy 数组:
    • 相对误差 和 绝对误差
  • 进阶

前言

经过 API 我们已经了解到 pytest 中包括的 API 大致内容,接下来我们详细看看 Functions 中的 pytest.approx

含义

approx:在一定误差范围内断言两个数字(或两组数字)相等。
源码如图:
在这里插入图片描述

使用

我们知道计算机运算浮点数的复杂性,我们直观认为相等的而实际上并不相等;

单数

0.1 + 0.2 == 0.3
# 我们认为上方计算出来结果进行比对返回应该是 True,而实际返回
False

而 approx 可以帮我们解决这个问题:

from pytest import approx
0.1 + 0.2 == approx(0.3)

元祖

(0.1 + 0.2, 0.2 + 0.4) == approx((0.3, 0.6))

字典

{'a': 0.1 + 0.2, 'b': 0.2 + 0.4} == approx({'a': 0.3, 'b': 0.6})

numpy 数组:

numpy 介绍和使用

import numpy as np
np.array([0.1, 0.2]) + np.array([0.2, 0.4]) == approx(np.array([0.3, 0.6]))

如果 numpy 数组中结果一致,则可以直接填入一个标量,如:

import numpy as np
np.array([0.1, 0.2]) + np.array([0.2, 0.1]) == approx(0.3)

相对误差 和 绝对误差

默认情况,approx() 使用的为 相对误差,误差的范围是 1e-6 也就是百万分之一。

  1. 指定相对误差:
    在这里插入图片描述
  2. 只指定绝对误差,不指定相对误差,则根据绝对误差来进行比较:
    在这里插入图片描述
  3. 指定两个,只要满足其中一个,则认为是相等的:
    在这里插入图片描述

进阶

主要包括:

  1. 其他方法的浮点数比较与 pytest.approx() 的区别:
    技术能力有限,这里不做细致说明,贴出官网源码。
math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)
"""
- ``math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)``:  True if the relativetolerance is met w.r.t. either ``a`` or ``b`` or if the absolutetolerance is met.  Because the relative tolerance is calculated w.r.t.both ``a`` and ``b``, this test is symmetric (i.e.  neither ``a`` nor``b`` is a "reference value").  You have to specify an absolute toleranceif you want to compare to ``0.0`` because there is no tolerance bydefault.  Only available in python>=3.5.  `More information...`____ https://docs.python.org/3/library/math.html#math.isclose
"""numpy.isclose(a, b, rtol=1e-5, atol=1e-8)
"""
- ``numpy.isclose(a, b, rtol=1e-5, atol=1e-8)``: True if the differencebetween ``a`` and ``b`` is less that the sum of the relative tolerancew.r.t. ``b`` and the absolute tolerance.  Because the relative toleranceis only calculated w.r.t. ``b``, this test is asymmetric and you canthink of ``b`` as the reference value.  Support for comparing sequencesis provided by ``numpy.allclose``.  `More information...`____ http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.isclose.html
"""unittest.TestCase.assertAlmostEqual(a, b)
"""
- ``unittest.TestCase.assertAlmostEqual(a, b)``: True if ``a`` and ``b``are within an absolute tolerance of ``1e-7``.  No relative tolerance isconsidered and the absolute tolerance cannot be changed, so this functionis not appropriate for very large or very small numbers.  Also, it's onlyavailable in subclasses of ``unittest.TestCase`` and it's ugly because itdoesn't follow PEP8.  `More information...`____ https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertAlmostEqual
"""a == pytest.approx(b, rel=1e-6, abs=1e-12)
"""
- ``a == pytest.approx(b, rel=1e-6, abs=1e-12)``: True if the relativetolerance is met w.r.t. ``b`` or if the absolute tolerance is met.Because the relative tolerance is only calculated w.r.t. ``b``, this testis asymmetric and you can think of ``b`` as the reference value.  In thespecial case that you explicitly specify an absolute tolerance but not arelative tolerance, only the absolute tolerance is considered.
"""
  1. 运算符比较
"""
In order to avoid inconsistent behavior, ``TypeError`` israised for ``>``, ``>=``, ``<`` and ``<=`` comparisons.The example below illustrates the problem::assert approx(0.1) > 0.1 + 1e-10  # calls approx(0.1).__gt__(0.1 + 1e-10)assert 0.1 + 1e-10 > approx(0.1)  # calls approx(0.1).__lt__(0.1 + 1e-10)In the second example one expects ``approx(0.1).__le__(0.1 + 1e-10)``to be called. But instead, ``approx(0.1).__lt__(0.1 + 1e-10)`` is used tocomparison. This is because the call hierarchy of rich comparisonsfollows a fixed behavior. `More information...`____ https://docs.python.org/3/reference/datamodel.html#object.__ge__
"""

说明:本篇参考官网并加入自己些许理解翻译而来,觉得有用,可以点赞和赞赏哦(^ v ^),谢谢支持;如果有不足地方,可留言评论。后续将继续更新。
在这里插入图片描述

这篇关于pytest 测试框架学习(3):pytest.approx的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/192104

相关文章

GSON框架下将百度天气JSON数据转JavaBean

《GSON框架下将百度天气JSON数据转JavaBean》这篇文章主要为大家详细介绍了如何在GSON框架下实现将百度天气JSON数据转JavaBean,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录前言一、百度天气jsON1、请求参数2、返回参数3、属性映射二、GSON属性映射实战1、类对象映

Unity新手入门学习殿堂级知识详细讲解(图文)

《Unity新手入门学习殿堂级知识详细讲解(图文)》Unity是一款跨平台游戏引擎,支持2D/3D及VR/AR开发,核心功能模块包括图形、音频、物理等,通过可视化编辑器与脚本扩展实现开发,项目结构含A... 目录入门概述什么是 UnityUnity引擎基础认知编辑器核心操作Unity 编辑器项目模式分类工程

Python学习笔记之getattr和hasattr用法示例详解

《Python学习笔记之getattr和hasattr用法示例详解》在Python中,hasattr()、getattr()和setattr()是一组内置函数,用于对对象的属性进行操作和查询,这篇文章... 目录1.getattr用法详解1.1 基本作用1.2 示例1.3 原理2.hasattr用法详解2.

解决若依微服务框架启动报错的问题

《解决若依微服务框架启动报错的问题》Invalidboundstatement错误通常由MyBatis映射文件未正确加载或Nacos配置未读取导致,需检查XML的namespace与方法ID是否匹配,... 目录ruoyi-system模块报错报错详情nacos文件目录总结ruoyi-systnGLNYpe

基于Python Playwright进行前端性能测试的脚本实现

《基于PythonPlaywright进行前端性能测试的脚本实现》在当今Web应用开发中,性能优化是提升用户体验的关键因素之一,本文将介绍如何使用Playwright构建一个自动化性能测试工具,希望... 目录引言工具概述整体架构核心实现解析1. 浏览器初始化2. 性能数据收集3. 资源分析4. 关键性能指

Python Web框架Flask、Streamlit、FastAPI示例详解

《PythonWeb框架Flask、Streamlit、FastAPI示例详解》本文对比分析了Flask、Streamlit和FastAPI三大PythonWeb框架:Flask轻量灵活适合传统应用... 目录概述Flask详解Flask简介安装和基础配置核心概念路由和视图模板系统数据库集成实际示例Stre

Olingo分析和实践之OData框架核心组件初始化(关键步骤)

《Olingo分析和实践之OData框架核心组件初始化(关键步骤)》ODataSpringBootService通过初始化OData实例和服务元数据,构建框架核心能力与数据模型结构,实现序列化、URI... 目录概述第一步:OData实例创建1.1 OData.newInstance() 详细分析1.1.1

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是

使用Python进行GRPC和Dubbo协议的高级测试

《使用Python进行GRPC和Dubbo协议的高级测试》GRPC(GoogleRemoteProcedureCall)是一种高性能、开源的远程过程调用(RPC)框架,Dubbo是一种高性能的分布式服... 目录01 GRPC测试安装gRPC编写.proto文件实现服务02 Dubbo测试1. 安装Dubb

Python的端到端测试框架SeleniumBase使用解读

《Python的端到端测试框架SeleniumBase使用解读》:本文主要介绍Python的端到端测试框架SeleniumBase使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全... 目录SeleniumBase详细介绍及用法指南什么是 SeleniumBase?SeleniumBase