Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Comparing floats #101

Open
MrSaints opened this issue Oct 24, 2019 · 3 comments
Open

Comparing floats #101

MrSaints opened this issue Oct 24, 2019 · 3 comments
Labels

Comments

@MrSaints
Copy link

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
Copy link

sbland commented Sep 15, 2020

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

@MrSaints
Copy link
Author

MrSaints commented Sep 17, 2020

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
Copy link
Collaborator

medmunds commented Oct 1, 2020

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants