pytest
pytest copied to clipboard
Extend approx to complex objects
What's the problem this feature will solve?
Approximate equality of complex objects using pytest.approx.
import pytest
class Item:
def __init__(self, x):
self.x = x
a = Item(1)
b = Item(1.0000001)
assert a == pytest.approx(b, rel=1e-4)
b.y = 2
assert a != pytest.approx(b)
a.y = 2.000000001
assert a == pytest.approx(b, rel=1e-5)
Apparently, in this toy example, we can simply compare each of the attributes using pytest.approx.
However, in reality the cases may become more complex, where comparison of the attributes may become fragile (for one objects some attrs were assigned after initialization, while for the others were not).
Describe the solution you'd like
I created a package approx to handle complex objects: https://github.com/ivanovmg/approx
I suppose that some of its functionality can be adopted by pytest if this behavior is desirable.
Basically, we loop through all the fields recursively and check if they are approximately equal.
Alternative Solutions
Delegate the responsibility for the approximate object comparisons to a developer of the class.
Additional context
Related issues:
- https://github.com/pytest-dev/pytest/issues/6632
- https://github.com/pytest-dev/pytest/issues/3164