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.
Python code
26 linesimport 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
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
- Use `unittest.TestCase` to write formal regression tests with `assertRaises`.
- 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
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Format Data with Type Hints in Python easy
Keep learning
Related tutorials and quizzes for this topic.