在使用 Pytest 进行断言时,如果数据是浮点类型,可以使用以下方法进行断言:
一、使用pytest.approx
pytest.approx可以用来比较两个浮点数是否近似相等。例如:
import pytestdef test_float_assertion():result = 3.14159expected = 3.14assert 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来处理断言失败的情况。例如:
import math
import pytestdef test_float_assertion_alternate():result = 3.14159expected = 3.14with pytest.raises(AssertionError):assert not math.isclose(result, expected, rel_tol=1e-2)
这里如果结果与期望不接近,就会触发AssertionError,被pytest.raises捕获。
在进行浮点类型数据的断言时,要根据具体的精度要求和测试场景选择合适的断言方法。