How to Assert Approximately Equal in pytest: Simple Guide
In
pytest, you can assert approximate equality using pytest.approx(). This helper allows you to compare floating-point numbers within a tolerance, making tests reliable for values that may differ slightly due to rounding.Syntax
The basic syntax to assert approximate equality in pytest is:
assert actual == pytest.approx(expected, rel=relative_tolerance, abs=absolute_tolerance)
Here, actual is the value you got, expected is the value you want to compare against.
rel sets the relative tolerance (default 1e-6), and abs sets the absolute tolerance (default 0).
python
assert actual == pytest.approx(expected, rel=1e-6, abs=0)
Example
This example shows how to test that two floating-point numbers are approximately equal using pytest.approx(). It passes even if the numbers differ slightly due to rounding.
python
import pytest def test_approx_equal(): result = 0.1 + 0.2 expected = 0.3 assert result == pytest.approx(expected) if __name__ == "__main__": pytest.main([__file__])
Output
============================= test session starts ==============================
collected 1 item
test_approx_equal.py . [100%]
============================== 1 passed in 0.01s ===============================
Common Pitfalls
Common mistakes include:
- Using simple
==for floating-point numbers, which can fail due to tiny rounding errors. - Not specifying tolerances when needed, causing tests to be too strict or too loose.
- Confusing relative and absolute tolerance; use
relfor proportional differences andabsfor fixed differences.
Always use pytest.approx() for floating-point comparisons instead of plain equality.
python
import pytest def test_wrong(): result = 0.1 + 0.2 expected = 0.3 # This will fail due to floating point precision # assert result == expected # Correct way assert result == pytest.approx(expected) if __name__ == "__main__": pytest.main([__file__])
Output
============================= test session starts ==============================
collected 1 item
test_wrong.py . [100%]
============================== 1 passed in 0.01s ===============================
Quick Reference
Summary tips for using pytest.approx():
- Use
assert actual == pytest.approx(expected)for approximate equality. - Adjust
relandabsparameters to control tolerance. - Works with floats, lists, tuples, and dicts of numbers.
- Helps avoid flaky tests caused by floating-point rounding.
Key Takeaways
Use pytest.approx() to assert approximate equality of floating-point numbers.
Adjust relative (rel) and absolute (abs) tolerances to fit your precision needs.
Avoid direct equality checks (==) for floats to prevent flaky tests.
pytest.approx() supports complex data structures like lists and dicts of numbers.
Always prefer pytest.approx() for reliable floating-point comparisons in tests.