Search code examples
pythonfloating-pointpytestsanicpython-hypothesis

Pytest/Hypothesis not matching string as expected


I am testing a validate function I am using with Sanic.

def validate(val):
    try:
        if isinstance(val, bool):  # Here because the int(val) line will success with int(True)/int(False)
            raise ValueError()
        if isinstance(val, float):
            print("IT'S FLOAT!")
            raise ValueError()
        if '.' in str(val):
            raise ValueError()
        n = int(val)
    except ValueError as ex:
        raise InvalidUsage('Invalid value "{}" for int param "n"'.format(val))

I'm testing this against float values and using Hypothesis to generate the test conditions.

@given(val=st.floats())
def test_validate_int_float(val):
    with pytest.raises(InvalidUsage) as ex:
        validate(val)
    print("{}|{}|{}".format(ex.value, f'Invalid value "{val}" for int param "n"',
                            ex.value == f'Invalid value "{val}" for int param "n"'))
    assert ex.match(f'Invalid value "{val}" for int param "n"')

This test fails:

Falsifying example: test_validate_int_float(val=1e+16)

The print statement looks like this:

IT'S FLOAT!
Invalid value "1e+16" for int param "n"|Invalid value "1e+16" for int param "n"|False

Why is my assert not matching? The strings look the same to me. I am assuming it's due to the float value, but in that case, how do I properly match the value?


Solution

  • Convert the ex.value to str prior to checking equality with:

    print("{}|{}|{}".format(ex.value, f'Invalid value "{val}" for int param "n"',
                            str(ex.value) == f'Invalid value "{val}" for int param "n"'))