pytest:断言几乎相等 [英] pytest: assert almost equal

查看:32
本文介绍了pytest:断言几乎相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 py.test 对浮点数进行 assert几乎相等 而不求助于类似的东西:

How to do assert almost equal with py.test for floats without resorting to something like:

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

更具体地说,知道一种无需拆包即可快速比较浮点对的简洁解决方案会很有用:

More specifically it will be useful to know a neat solution for quickly compare pairs of float, without unpacking them:

assert (1.32, 2.4) == i_return_tuple_of_two_floats()

推荐答案

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

I noticed that this question specifically asked about py.test. py.test 3.0 includes an approx() function (well, really class) that is very useful for this purpose.

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

文档在这里:https://docs.pytest.org/en/latest/reference/reference.html?highlight=approx#pytest.approx

这篇关于pytest:断言几乎相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆