测试面试题:pytest断言时,数据是符点类型,如何断言?

在使用 Pytest 进行断言时,如果数据是浮点类型,可以使用以下方法进行断言:

一、使用pytest.approx

pytest.approx可以用来比较两个浮点数是否近似相等。例如:

python 复制代码
import pytest

def test_float_assertion():
    result = 3.14159
    expected = 3.14
    assert result == pytest.approx(expected, rel=1e-2)

在这个例子中,pytest.approx(expected, rel=1e-2)表示允许结果与期望值之间有相对误差不超过1e-2(即 0.01)。

二、使用math.isclose结合pytest.raises进行断言

可以结合 Python 的内置函数math.isclose来判断两个浮点数是否接近,并使用pytest.raises来处理断言失败的情况。例如:

python 复制代码
import math
import pytest

def test_float_assertion_alternate():
    result = 3.14159
    expected = 3.14
    with pytest.raises(AssertionError):
        assert not math.isclose(result, expected, rel_tol=1e-2)

这里如果结果与期望不接近,就会触发AssertionError,被pytest.raises捕获。

在进行浮点类型数据的断言时,要根据具体的精度要求和测试场景选择合适的断言方法。

相关推荐
糖果店的幽灵16 小时前
软件测试接口测试从入门到精通:Python接口自动化 - pytest测试框架
软件测试·python·功能测试·自动化·pytest·接口测试
2601_961875241 天前
花生十三资料1200题|题库|刷题
conda·pytest·pillow·pip·web3.py·ipython·gunicorn
某人辛木1 天前
Web自动化测试
前端·python·pycharm·pytest
淡漠的蓝精灵3 天前
pytest-xdist:把 pytest 测试分发到多核 CPU 执行
其他·pytest
弹简特5 天前
【接口自动化】03-YAML详解及Parametrize数据驱动
自动化·pytest
007张三丰6 天前
软件测试专栏(11/20):测试框架开发:pytest深度解析与插件体系
运维·服务器·自动化测试·pytest·测试框架
我的xiaodoujiao7 天前
API 接口自动化测试详细图文教程学习系列25--继续处理testCase中的数据
python·学习·测试工具·pytest
xiaobai1788 天前
pytest+playwright实现UI自动化(4)-上夹具fixture
ui·自动化·pytest·playwright
弹简特8 天前
【接口自动化】02-Pytest固件fixture核心机制与Allure企业级报告实战
自动化·pytest·测试
弹简特10 天前
【接口自动化】01-pytest详解、pytest执行逻辑、pytest参数、配置文件和pytest标记
自动化·pytest