Fix and Test a Regression Bug in Python with Unit Tests

This code implements a circle area function that raises ValueError for negative radii, then runs basic tests and a regression check for that edge case.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 16 views 0 copies

Python code

26 lines
Python 3.9+
import math

def calculate_area(radius):
    """Calculate the area of a circle given its radius."""
    if radius < 0:
        raise ValueError("Radius cannot be negative")
    return math.pi * radius ** 2

def main():
    test_cases = [0, 1, 2.5, 5, 10]
    
    print("Circle Area Calculator")
    print("-" * 30)
    
    for radius in test_cases:
        area = calculate_area(radius)
        print(f"Radius: {radius:>4} → Area: {area:.2f}")
    
    # Regression test for edge case
    try:
        calculate_area(-1)
    except ValueError as e:
        print("\nEdge case handled: ", e)

if __name__ == "__main__":
    main()

Output

stdout
Circle Area Calculator
------------------------------
Radius:    0 → Area: 0.00
Radius:    1 → Area: 3.14
Radius:  2.5 → Area: 19.63
Radius:    5 → Area: 78.54
Radius:   10 → Area: 314.16

Edge case handled:  Radius cannot be negative

How it works

The calculate_area function uses math.pi and exponentiation to compute the area, and includes input validation to reject negative radii. The main block loops through sample radii and prints formatted results. A regression test is embedded in main() by calling calculate_area(-1) and catching the expected ValueError to confirm the bug fix is in place. This pattern allows quick verification that edge-case handling remains intact during development.

Common mistakes

  • Forgetting to raise an exception for negative input, allowing invalid calculations
  • Using integer division or truncation instead of floating-point math
  • Not testing edge cases like zero or negative values
  • Failing to use `import math` before referencing `math.pi`

Variations

  1. Use `unittest.TestCase` to write formal regression tests with `assertRaises`.
  2. Use `pytest` with `@pytest.mark.parametrize` for multiple test cases.

Real-world use cases

  • Running unit tests in CI to prevent a previously fixed negative-radius bug from recurring.
  • Validating geometric calculations in a CAD or engineering application that must reject invalid inputs.
  • Adding regression checks to a library function to ensure edge-case behavior stays stable across releases.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.