KatInterview

Fix a Failing Budget-Check Module and Add Regression Tests

Arrays & HashingModel answer
MediumModel answerArrays & Hashingdebuggingunit-testingroot-cause-analysis

Last 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

  1. Identify the root cause of every failure. Do not just patch the symptoms or edit the expected values in the tests.
  2. 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.
  3. Add a minimal regression test for each defect.
  4. Describe your debugging strategy: the order in which you investigated, and the tools you used.
  5. 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?