syrusakbary / snapshottest

Snapshot Testing utils for Python 📸
MIT License
537 stars 102 forks source link

Comparing floats #101

Open MrSaints opened 5 years ago

MrSaints commented 5 years ago

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

sbland commented 4 years ago

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

MrSaints commented 4 years ago

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).

medmunds commented 4 years ago

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?