Fix a Failing Budget-Check Module and Add Regression Tests
Arrays & HashingModel answerLast updated
Debug a small spending-limit module with failing tests: find root causes, fix them, add minimal regression tests, and explain your debugging process and tools.
You are handed a small Python module that decides whether a new card charge fits inside a customer's monthly budget. Several unit tests fail, and one of them passes when run alone but fails when the whole suite runs.
# budget.py (buggy)
def parse_price(text: str) -> int:
return int(float(text) * 100)
def month_total(entries, year, month):
total = 0
for e in entries:
if e.when.month == month:
total += e.cents
return total
def within_budget(budget_cents, charge_cents, entries, today, holds=[]):
used = month_total(entries, today.year, today.month)
holds.append(charge_cents)
return used + sum(holds) < budget_cents
Each entry has a when (a datetime) and cents (an integer, negative for refunds). holds is a list of amounts, in cents, that are already reserved but not yet posted.
What is expected
- Identify the root cause of every failure. Do not just patch the symptoms or edit the expected values in the tests.
- Fix the code. A charge that brings month-to-date spend (posted entries plus holds plus this charge) exactly to the budget must be allowed. Charges must be positive, and invalid price strings must raise
ValueError. - Add a minimal regression test for each defect.
- Describe your debugging strategy: the order in which you investigated, and the tools you used.
- Explain, for each bug, why it happens and how a reviewer could have spotted it.
Hints
Hint 1
Run the full suite first, then run the failing tests one by one. A test that passes alone but fails in the suite almost always means state shared between calls.
Hint 2
Print `float('19.99') * 100` in a REPL, and read the function signature of `within_budget` closely. What is evaluated once, at definition time?
Hint 3
Check every predicate for completeness and every comparison for boundary behavior. Is the month filter missing something, and should hitting the budget exactly be allowed?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This task rewards process more than cleverness. The goal is to reproduce, isolate, hypothesize, verify and only then fix, with one regression test per defect. Editing code until the tests turn green, or changing a test's expected value, is the wrong answer.
Debugging strategy
- See the whole picture first. Run
pytest -qand note which tests fail and how. Then usepytest -x,pytest --lfandpytest -k nameto iterate on one failure at a time. - Classify by symptom.
- A test that passes alone but fails in the suite points to shared or global state.
- An off-by-one in an assertion diff such as
1998 != 1999points to numeric precision. - A total that is too high points to a filtering problem.
- A failure that appears only at an exact boundary points to a comparison operator.
- Reproduce small. Use a REPL or
breakpoint()/pdband inspect real intermediate values rather than guessing. - One hypothesis, one change, rerun. If the bug is a regression,
git bisectfinds the offending commit.pytest --covshows untested branches where more bugs may hide. - Test first. Write the regression test, watch it fail for the right reason, fix, watch it pass, then rerun everything. If state leaked, also run in random order (for example with the
pytest-randomlyorpytest-random-orderplugin).
Root causes
1. Binary floats used for money.
float("19.99") * 100 is 1998.9999999999998, and int() truncates it to 1998. Most decimal fractions have no exact binary representation. Parse with Decimal, round to cents with an explicit rounding mode, and use integer cents from then on.
2. The month filter ignores the year.
e.when.month == month also matches the same month in earlier years, so old spending counts against this month's budget. The predicate is incomplete. Compare both year and month.
3. Wrong comparison at the boundary.
Using < rejects a charge that lands exactly on the budget, but the rule says that must be allowed. Use <=. In a real interview, confirm that intent with the spec or the tests rather than assuming it.
4. Mutable default argument.
holds=[] is created once, when the function is defined. Every call appends to the same list, so later calls see phantom holds. This also explains the test that passes alone but fails in the suite. Default to None and treat it as empty. Also, the function must not mutate the caller's list. The original code appended the new charge to holds, which is a second, subtler side effect, because the charge is not a hold until it is actually approved.
Fixed code
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
from typing import Iterable, Optional, Sequence
@dataclass(frozen=True)
class Entry:
when: datetime
cents: int # negative for refunds
def parse_price(text: str) -> int:
"""Convert a decimal string such as '19.99' to integer cents exactly."""
try:
value = Decimal(text.strip())
except (InvalidOperation, AttributeError):
raise ValueError(f"invalid price: {text!r}")
if not value.is_finite():
raise ValueError(f"invalid price: {text!r}")
return int((value * 100).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
def month_total(entries: Iterable[Entry], year: int, month: int) -> int:
"""Net posted spend (refunds included) for one calendar month."""
return sum(
e.cents for e in entries
if e.when.year == year and e.when.month == month
)
def within_budget(
budget_cents: int,
charge_cents: int,
entries: Iterable[Entry],
today: datetime,
holds: Optional[Sequence[int]] = None,
) -> bool:
"""True if this charge keeps month-to-date spend at or under the budget."""
if charge_cents <= 0:
raise ValueError("charge must be positive")
held = sum(holds) if holds else 0
used = month_total(entries, today.year, today.month)
return used + held + charge_cents <= budget_cents
Minimal regression tests
One test per defect, named after the behavior it protects.
import pytest
from datetime import datetime
from budget import Entry, parse_price, month_total, within_budget
def test_parse_price_is_exact():
assert parse_price("19.99") == 1999
assert parse_price("0.29") == 29
assert parse_price("0.005") == 1 # explicit half-up rounding
def test_parse_price_rejects_garbage():
with pytest.raises(ValueError):
parse_price("abc")
def test_month_total_respects_year():
es = [Entry(datetime(2023, 3, 1), 500), Entry(datetime(2024, 3, 1), 300)]
assert month_total(es, 2024, 3) == 300
def test_budget_boundary_is_inclusive():
today = datetime(2024, 3, 10)
es = [Entry(datetime(2024, 3, 2), 900)]
assert within_budget(1000, 100, es, today) is True
assert within_budget(1000, 101, es, today) is False
def test_no_state_leaks_between_calls():
today = datetime(2024, 3, 10)
for _ in range(5):
assert within_budget(1000, 600, [], today) is True
def test_caller_holds_not_mutated():
holds = [100]
within_budget(1000, 100, [], datetime(2024, 3, 10), holds)
assert holds == [100]
Complexity
parse_priceis O(d) in the number of digits.month_totalandwithin_budgetare O(n + h) time over entries and holds, with O(1) extra space because generators avoid building intermediate lists.- At production scale, keep a running per-account monthly aggregate instead of rescanning history, and update it transactionally.
Trade-offs and common mistakes
- Silencing the test. Loosening an assertion or adding a special case for one input hides the defect.
- Fixing float rounding with
round(). This still leaves binary representation errors in other paths. UseDecimalor integers, and name the rounding mode (half-up versus banker's) explicitly. - Fixing the default but still mutating input. Removing
holds=[]while leavingholds.append(...)fixes the cross-call leak but not the side effect on the caller's list. - Skipping timezone and month-boundary questions. Mention them as follow-ups: which timezone defines "this month", and what happens for a charge at 23:59:59 on the last day.
- Fixing everything in one commit. Small commits, one per defect, each with its test, make review easy and make
git bisectuseful later.
How a reviewer could have caught each bug
- Float math on currency is a standard lint or review flag.
- A mutable default argument is flagged by linters such as
flake8-bugbear(B006) and pylint (W0102). - Missing year comparisons and boundary operators are caught by tests on month and limit edges, which is why the regression tests above target exactly those inputs.