IT story

pytest : 거의 동등하다고 주장

hot-time 2020. 8. 9. 09:41
반응형

pytest : 거의 동등하다고 주장


assert almost equal다음과 같은 것에 의지하지 않고 float에 대한 py.test를 사용 하는 방법 :

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

더 구체적으로 말하면 float 쌍을 풀지 않고 빠르게 비교할 수있는 깔끔한 솔루션을 아는 것이 유용합니다.

assert (1.32, 2.4) == i_return_tuple_of_two_floats()

이 질문이 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

문서는 여기에 있습니다 : https://docs.pytest.org/en/latest/reference.html#pytest-approx


"거의"항목을 지정해야합니다.

assert abs(x-y) < 0.0001

튜플 (또는 시퀀스)에 적용하려면 :

def almost_equal(x,y,threshold=0.0001):
  return abs(x-y) < threshold

assert all(map(almost_equal, zip((1.32, 2.4), i_return_tuple_of_two_floats())

NumPy에 액세스 할 수 있다면 이미 numpy.testing.

그런 다음 다음과 같이 할 수 있습니다.

numpy.testing.assert_allclose(i_return_tuple_of_two_floats(), (1.32, 2.4))

같은 것

assert round(x-y, 5) == 0

즉 무엇 유닛 테스트가 수행

두 번째 부분

assert all(round(x-y, 5) == 0 for x,y in zip((1.32, 2.4), i_return_tuple_of_two_floats()))

아마도 그것을 함수로 감싸는 것이 더 낫습니다.

def tuples_of_floats_are_almost_equal(X, Y):
    return all(round(x-y, 5) == 0 for x,y in zip(X, Y))

assert tuples_of_floats_are_almost_equal((1.32, 2.4), i_return_tuple_of_two_floats())

이 답변은 오랫동안 사용되어 왔지만 가장 쉽고 가장 읽기 쉬운 방법은 테스트 구조에 사용하지 않고 많은 멋진 주장에 대해 unittest를 사용하는 것입니다.

어설 션을 가져오고 나머지 unittest는 무시합니다.

( 이 답변을 바탕으로 )

import unittest

assertions = unittest.TestCase('__init__')

주장하기

x = 0.00000001
assertions.assertAlmostEqual(x, 0)  # pass
assertions.assertEqual(x, 0)  # fail
# AssertionError: 1e-08 != 0

원래 질문의 자동 풀기 테스트 구현

새 이름을 도입 할 필요없이 *를 사용하여 반환 값의 압축을 풉니 다.

i_return_tuple_of_two_floats = lambda: (1.32, 2.4)
assertions.assertAlmostEqual(*i_return_tuple_of_two_floats())  # fail
# AssertionError: 1.32 != 2.4 within 7 places

나는 코. 도구를 사용할 것입니다. py.test 러너와 잘 작동하며 assert_dict_equal (), assert_list_equal () 등 다른 똑같이 유용한 어설 션이 있습니다.

from nose.tools import assert_almost_equals
assert_almost_equals(x, y, places=7) #default is 7 

If you want something that works not only with floats but for example Decimals you can use python's math.isclose:

    # - rel_tol=0.01` is 1% difference tolerance.
    assert math.isclose(actual_value, expected_value, rel_tol=0.01)

Docs - https://docs.python.org/3/library/math.html#math.isclose

참고URL : https://stackoverflow.com/questions/8560131/pytest-assert-almost-equal

반응형