0
0
PyTesttesting~15 mins

Approximate comparisons (pytest.approx) - Build an Automation Script

Choose your learning style9 modes available
Verify approximate equality of floating point calculations using pytest.approx
Preconditions (2)
Step 1: Call the function or perform the calculation that returns a floating point result
Step 2: Use pytest.approx to compare the result with the expected value allowing a small tolerance
Step 3: Assert that the actual result is approximately equal to the expected value using pytest.approx
✅ Expected Result: The test passes if the actual floating point result is within the allowed tolerance of the expected value
Automation Requirements - pytest
Assertions Needed:
Assert that actual floating point value is approximately equal to expected value using pytest.approx
Best Practices:
Use pytest.approx for floating point comparisons instead of exact equality
Avoid hardcoding very tight tolerances unless necessary
Write clear assertion messages if needed
Automated Solution
PyTest
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.

Common Mistakes - 3 Pitfalls
Using exact equality (==) to compare floating point numbers
Setting the tolerance in pytest.approx too tight or too loose without reason
Not importing pytest or pytest.approx before using it
Bonus Challenge

Now add data-driven testing with 3 different radius inputs and verify approximate area calculations for each.

Show Hint