Verify approximate equality of floating point calculations using pytest.approx
Preconditions (2)
✅ Expected Result: The test passes if the actual floating point result is within the allowed tolerance of the expected value
import pytest def calculate_area(radius: float) -> float: # Simple area calculation for a circle return 3.141592653589793 * radius * radius def test_calculate_area_approx(): radius = 2.0 expected_area = 12.566370614359172 # pi * 2^2 actual_area = calculate_area(radius) assert actual_area == pytest.approx(expected_area, rel=1e-9), f"Expected area approx {expected_area}, got {actual_area}"
This test defines a simple function calculate_area that returns a floating point number.
The test test_calculate_area_approx calls this function with a radius of 2.0 and stores the result.
It then asserts that the actual area is approximately equal to the expected area using pytest.approx with a relative tolerance of 1e-9.
This approach handles small floating point differences gracefully, avoiding false failures due to tiny rounding errors.
Now add data-driven testing with 3 different radius inputs and verify approximate area calculations for each.
pytest.approx in tests?pytest.approxpytest.approx allows tests to pass if numbers are close within a tolerance, avoiding false failures.result is approximately equal to 3.14 using pytest.approx?def test_value():
value = 0.1 + 0.2
assert value == pytest.approx(0.3)def test_approx():
result = 1.0001
assert result == pytest.approx(1.0, rel=0.00001)pytest.approx?Pass the test and this pattern moves unknown