snapshottest icon indicating copy to clipboard operation
snapshottest copied to clipboard

Comparing floats

Open MrSaints opened this issue 4 years ago • 3 comments

Self-explanatory.

Some potential ideas / handlers:

https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertAlmostEqual https://docs.scipy.org/doc/numpy/reference/generated/numpy.testing.assert_almost_equal.html https://docs.python.org/3/whatsnew/3.5.html#pep-485-a-function-for-testing-approximate-equality

MrSaints avatar Oct 24 '19 10:10 MrSaints

Would this involve any more than creating a custom formatter in formatters.py and implementing it?

sbland avatar Sep 15 '20 16:09 sbland

Yes -- we'll probably need a custom assert_value_matches_snapshot which relies on some of the methods mentioned above for approximate equality.

EDIT: actually, I think a custom formatter with __eq__ may just be enough (assuming we wrap every float with the custom formatter).

MrSaints avatar Sep 17 '20 18:09 MrSaints

You can register a custom formatter via the (undocumented) snapshottest.formatter.Formatter.register_formatter() static method, overriding the default float formatter. I believe you'd want to format floats into a new custom type (FloatCloseTo(3.14159)) that implements the desired __eq__ along with a __repr__ that can construct itself.

The built-in file snapshot formatter shows all the moving parts (plus a bunch more complexity you wouldn't need, around writing additional files).

Also (although I'm not proud of this suggestion), if all your floats are of similar precision, it might be sufficient to just serialize them as Decimals?

medmunds avatar Oct 01 '20 00:10 medmunds