小编典典

pytest:断言几乎相等

all

如何assert almost equal使用 py.test 进行浮动而不诉诸于:

assert x - 0.00001 <= y <= x + 0.00001

更具体地说,了解一个快速比较浮点对的简洁解决方案将很有用,而无需解包它们:

assert (1.32, 2.4) == i_return_tuple_of_two_floats()

阅读 67

收藏
2022-05-29

共1个答案

小编典典

我注意到这个问题专门询问了 py.test。py.test 3.0 包含一个approx()对此目的非常有用的函数(嗯,真的是类)。

import pytest

assert 2.2 == pytest.approx(2.3)
# fails, default is 卤 2.3e-06
assert 2.2 == pytest.approx(2.3, 0.1)
# passes

# also works the other way, in case you were worried:
assert pytest.approx(2.3, 0.1) == 2.2
# passes

文档在这里

2022-05-29