测试面试题: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捕获。

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

相关推荐
nbwenren2 天前
2026实测:Gemini 3.1 Pro 从需求文档到 pytest 测试用例一条龙教程
测试用例·pytest
我的xiaodoujiao3 天前
API 接口自动化测试详细图文教程学习系列16--项目实战演练3
python·学习·测试工具·pytest
我的xiaodoujiao3 天前
API 接口自动化测试详细图文教程学习系列15--项目实战演练2
python·学习·测试工具·pytest
技术钱4 天前
PyTest配置与API测试用例
servlet·测试用例·pytest
weixin_419658315 天前
pytest 零基础入门实战指南
python·pycharm·pytest
姚青&8 天前
软件测试基础概念
单元测试·pytest
爆更小哇11 天前
pytest集成Allure报告教程
python·测试工具·pytest·接口测试·allure
gCode Teacher 格码致知12 天前
Python提高:pytest的简单案例-由Deepseek产生
python·pytest
gCode Teacher 格码致知12 天前
Python提高: unittest和 pytest的使用方法-由Deepseek产生
开发语言·python·pytest