简体   繁体   中英

Why I am getting pytest AssertionError with pytest?

Could you help me to understand why I am getting AssertionError in pytest with simple test below?

Here is the tested function conventer.py

from decimal import Decimal


TWO = Decimal(10) ** -2

def us_to_dec(odds=100):
    if odds >= 0:
        return Decimal((odds / 100) + 1).quantize(TWO)
    else:
        return Decimal((100 / odds) + 1).quantize(TWO)

print statement on conventer py returns expected result

print(us_to_dec(odds=205))
3.05

Here is test returning assertion error test_conventer.py

from surebet import converter


def test_us_to_dec():
    assert converter.us_to_dec(odds=205) == 3.05

Test fails with following output

E       AssertionError: assert Decimal('3.05') == 3.05
E        +  where Decimal('3.05') = <function us_to_dec at 0x106c99598>(odds=205)
E        +    where <function us_to_dec at 0x106c99598> = converter.us_to_dec
tests/test_converter.py:16: AssertionError

I am not sure why I'm getting AssertionError

EDIT:

If anyone else runs into same I ended up doing the following:

from pytest import approx

from decimal import Decimal

from surebet import converter

def test_us_to_dec():
    assert converter.us_to_dec(odds=205) == approx(Decimal(3.05))

Simply comparing converter.us_to_dec(odds=205) == approx(3.05) will cause TypeError

Decimal((205 / 100) + 1).quantize(Decimal(10) ** -2) == Decimal('3.05')
# --> True

Decimal((205 / 100) + 1).quantize(Decimal(10) ** -2) == 3.05
# --> False

Decimal values are not guaranteed to be equal to float values even if they have the same repr due to the limitations of floating point arithmatic. In this case 3.05 cannot be expressed exactly in binary, so when the two values are compared 3.05 is converted to

Decimal(3.05) == Decimal('3.04999999999999982236431605997495353221893310546875')

before the comparison is made.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM