Here's everything in the starter repo, so you can look around before you download it. Click a file to open it.
README.md 94 lines
# Cake Club billing: bug squash
Cake Club is Crumb & Co.'s cake-box subscription: pick a box, and a cake turns up every month. This is the
billing side. It loads the plans from the bakery's price sheet, signs people up, bills them on the right
days, shows the Plans page, and gives finance a report at the end of each month. Four bug reports have come
in. Find and fix them.
## Running the tests
Python 3.10 or newer, standard library only (nothing to install). From this folder:
python3 -m unittest discover -s tests
To run one bug's tests: `python3 -m unittest discover -s tests -p "test_stage1.py"`
- `tests/test_existing.py` covers behaviour that already works. It passes now; keep it passing.
- `tests/test_stage1.py` to `tests/test_stage4.py` go with bugs 1 to 4. Each fails until its bug is fixed.
- There are hidden tests too, like the ones an interviewer runs after you say you're done. In the browser
workspace, choose "Hidden tests" in the Run menu. Locally, download `hidden-tests.zip` from the problem
page and unzip it where you unzipped the starter. It adds a `hidden_tests` folder next to `tests`. Then,
from this folder, run `python3 -m unittest discover -s hidden_tests`.
## Time box and rules
75 minutes. Work through the bugs in order.
Use any editor and any AI assistant you like. In a real AI-allowed interview you'd be expected to explain
and verify everything the AI writes, so practice that too.
Change anything under `cakeclub/`, but don't edit the tests. For each fix, be ready to say what the root
cause was and why your change fixes it.
## How it works
| File | What it does |
|---|---|
| `cakeclub/money.py` | `to_cents`, `format_cents`, `percent_off` |
| `cakeclub/models.py` | `Plan`, `Subscriber`, `Invoice`, `Payment` |
| `cakeclub/catalog.py` | `Catalog`, `load_price_sheet` (which reads `data/price_sheet.csv`), and `menu_export`, the printed menu |
| `cakeclub/dates.py` | `next_billing_date`, `next_annual_date` |
| `cakeclub/billing.py` | `sign_up` and `run_billing`, the daily billing run |
| `cakeclub/pages.py` | `pricing_page` (the Plans page) and `holiday_menu` |
| `cakeclub/reports.py` | `month_end_report` for finance |
| `CHANGELOG.md` | What changed, and when |
The rules, as the business wants them:
- The menu order is the order of the price sheet. The first plan on the menu is the default for people who
sign up without choosing one. The printed menu and the holiday menu use menu order; the Plans page lists
plans cheapest first.
- Plans are monthly or annual. An annual plan costs 10 months' price and brings 12 months of boxes.
- Subscribers are billed the day they sign up, then on that same day of the month every month. When a month
is too short for their day, they're billed on its last day, and on their own day again after that. Annual
plans work the same way, a year at a time.
- The daily billing run bills everyone whose billing date has come. If a run was missed, it catches up: one
invoice for each date that went by.
- The month-end report has one row per invoice issued on or before the last day of the month, in the order
the invoices are given. Each row shows what's been paid against the invoice by the end of the month:
successful payments minus refunds. Failed payments don't count, and a payment made after the month ends
goes in next month's report.
## Bug 1: Annual subscribers are charged 100 times too much
> From: customer support
>
> Fay signed up for the annual Classic box this morning and her card was charged $32,000.00. It should be
> $320.00: ten months of $32.00, the pay-for-10-get-12 deal. Her receipt email doesn't add up either. We've
> refunded her and turned off annual signups until this is fixed. Monthly subscribers look fine.
## Bug 2: Billing dates drift after a short month
> From: a subscriber, forwarded by support
>
> I signed up on January 31 because I wanted my cake at the end of each month. I was billed on January 31
> and February 28, which is fair. But then March was billed on the 28th, and April too. My sister signed up
> on January 30 and the same thing happened to her.
## Bug 3: New signups get the wrong default plan
> From: the shop
>
> Since the new Plans page went live, people who sign up without choosing a plan get the Mini box. The
> default has always been the first plan on our menu, the Classic box, and nobody has touched the price
> sheet. It doesn't happen every time: after a restart it's fine for a while. The printed menu at the
> counter came out in a funny order on Tuesday, too.
## Bug 4: The month-end report never finishes
> From: Omar, finance
>
> The month-end report was fine in the summer, but November's ran for 15 minutes and then the job was
> killed. We're up to about 20,000 invoices and 30,000 payments a month. Please don't change what the report
> says, only how long it takes: its numbers go straight into the books, and its rules are the ones we agreed
> with our accountants.
CHANGELOG.md 23 lines
# Changelog
## 2.4 (November 2026)
- The Plans page (`pages.pricing_page`): every plan, cheapest first.
- The holiday menu (`pages.holiday_menu`) for December's specials.
## 2.3 (June 2026)
- The month-end report for finance (`reports.month_end_report`).
## 2.2 (March 2026)
- Annual plans: pay for 10 months, get 12.
## 2.0 (January 2026)
- All money is whole cents (`int`) now: plan prices, invoice lines, payments. No more floats.
The price sheet the bakery exports is still in dollars, and `load_price_sheet` converts it.
## 1.0 (2025)
- Monthly cake boxes.
cakeclub/__init__.py 1 line
"""Cake Club: monthly and annual cake-box subscriptions for Crumb & Co."""
cakeclub/billing.py 72 lines
"""Signing people up, and the daily billing run."""
from datetime import date
from cakeclub.catalog import Catalog
from cakeclub.dates import next_annual_date, next_billing_date
from cakeclub.models import Interval, Invoice, InvoiceLine, Plan, Subscriber
from cakeclub.money import format_cents, to_cents
# Annual plans: pay for 10 months, get 12.
ANNUAL_MONTHS_CHARGED = 10
def sign_up(catalog: Catalog, subscriber_id: str, email: str, started_on: date,
plan_code: str | None = None, interval: Interval = Interval.MONTH) -> Subscriber:
"""A new subscriber, on the plan they chose or the catalog's default. They're billed
for the first time on the day they sign up."""
plan = catalog.get(plan_code) if plan_code else catalog.default_plan()
return Subscriber(
id=subscriber_id,
email=email.strip().lower(),
plan_code=plan.code,
interval=interval,
started_on=started_on,
next_bill_on=started_on,
)
def plan_amount(plan: Plan, interval: Interval) -> int:
"""What one billing period of the plan costs, in cents."""
if interval is Interval.MONTH:
return plan.price
return _annual_amount(plan)
def _annual_amount(plan: Plan) -> int:
# Plan prices are in dollars, so convert the annual price to cents.
return to_cents(plan.price * ANNUAL_MONTHS_CHARGED)
def line_description(plan: Plan, interval: Interval) -> str:
"""The invoice line, as the customer's email shows it."""
if interval is Interval.MONTH:
return f"{plan.name}, monthly ({format_cents(plan.price)})"
boxes = plan.boxes_per_month * 12
return f"{plan.name}, annual: {boxes} boxes for ${plan.price * ANNUAL_MONTHS_CHARGED:,.2f}"
def run_billing(subscribers: list[Subscriber], catalog: Catalog, today: date) -> list[Invoice]:
"""Bills every active subscriber whose next billing date is today or earlier: one invoice
per date that's come due (someone the run missed twice gets two invoices), dated that
day. Moves each subscriber's next_bill_on on past today."""
invoices = []
for subscriber in subscribers:
if not subscriber.active:
continue
plan = catalog.get(subscriber.plan_code)
while subscriber.next_bill_on <= today:
invoices.append(Invoice(
id=f"INV-{subscriber.id}-{subscriber.next_bill_on:%Y%m%d}",
subscriber_id=subscriber.id,
issued_on=subscriber.next_bill_on,
lines=[InvoiceLine(line_description(plan, subscriber.interval), plan_amount(plan, subscriber.interval))],
))
subscriber.next_bill_on = _following_date(subscriber)
return invoices
def _following_date(subscriber: Subscriber) -> date:
if subscriber.interval is Interval.MONTH:
return next_billing_date(subscriber.next_bill_on)
return next_annual_date(subscriber.next_bill_on)
cakeclub/catalog.py 57 lines
"""The plans on the menu, and the price sheet they're loaded from."""
import csv
import io
from cakeclub.models import Plan
from cakeclub.money import format_cents, to_cents
class UnknownPlanError(KeyError):
pass
class Catalog:
"""The plans on the menu, in menu order: the order the bakery lists them in."""
def __init__(self, plans):
self._plans = list(plans)
self._by_code = {plan.code: plan for plan in self._plans}
if not self._plans:
raise ValueError("a catalog needs at least one plan")
if len(self._by_code) != len(self._plans):
raise ValueError("two plans have the same code")
def plans(self) -> list[Plan]:
"""Every plan, in menu order."""
return self._plans
def get(self, code: str) -> Plan:
try:
return self._by_code[code]
except KeyError:
raise UnknownPlanError(code) from None
def default_plan(self) -> Plan:
"""New signups who don't choose a plan get the first plan on the menu."""
return self._plans[0]
def load_price_sheet(text: str) -> Catalog:
"""Reads the price sheet the bakery exports: a CSV with a header row and the columns
code, name, monthly_price (in dollars, like 32.00) and boxes_per_month, in menu order."""
rows = csv.DictReader(io.StringIO(text))
return Catalog(
Plan(
code=row["code"].strip(),
name=row["name"].strip(),
price=to_cents(row["monthly_price"].strip()),
boxes_per_month=int(row["boxes_per_month"]),
)
for row in rows
)
def menu_export(catalog: Catalog) -> str:
"""The printed menu at the shop counter: one line per plan, in menu order."""
return "\n".join(f"{plan.name} - {format_cents(plan.price)} a month" for plan in catalog.plans())
cakeclub/dates.py 23 lines
"""Billing dates."""
import calendar
from datetime import date
def days_in_month(year: int, month: int) -> int:
return calendar.monthrange(year, month)[1]
def next_billing_date(previous: date) -> date:
"""The monthly billing date after `previous`: the same day of the next month, or that
month's last day if it's shorter (Jan 31 -> Feb 28)."""
year = previous.year + previous.month // 12
month = previous.month % 12 + 1
return date(year, month, min(previous.day, days_in_month(year, month)))
def next_annual_date(previous: date) -> date:
"""The yearly billing date after `previous`: the same day a year later, or Feb 28 for
Feb 29 when next year isn't a leap year."""
year = previous.year + 1
return date(year, previous.month, min(previous.day, days_in_month(year, previous.month)))
cakeclub/models.py 71 lines
"""The data the billing service works with."""
from dataclasses import dataclass, field
from datetime import date
from enum import Enum
class Interval(Enum):
MONTH = "month"
YEAR = "year"
@dataclass(frozen=True)
class Plan:
"""A cake box you can subscribe to."""
code: str
name: str
price: int # monthly price, in dollars
boxes_per_month: int = 1
@dataclass
class Subscriber:
id: str
email: str
plan_code: str
interval: Interval
started_on: date
next_bill_on: date # moved on by billing.run_billing each time they're billed
active: bool = True
@dataclass(frozen=True)
class InvoiceLine:
description: str
amount_cents: int
@dataclass
class Invoice:
id: str
subscriber_id: str
issued_on: date
lines: list[InvoiceLine] = field(default_factory=list)
@property
def total_cents(self) -> int:
return sum(line.amount_cents for line in self.lines)
class PaymentKind(Enum):
PAYMENT = "payment"
REFUND = "refund"
class PaymentStatus(Enum):
SUCCEEDED = "succeeded"
FAILED = "failed"
@dataclass(frozen=True)
class Payment:
"""Money in (a payment) or out (a refund) against one invoice."""
id: str
invoice_id: str
amount_cents: int # always positive: kind says which way the money went
paid_on: date
kind: PaymentKind = PaymentKind.PAYMENT
status: PaymentStatus = PaymentStatus.SUCCEEDED
cakeclub/money.py 27 lines
"""Money helpers.
to_cents is for amounts that come in from outside, written in dollars: the price
sheet the bakery exports, and the admin form.
"""
from decimal import ROUND_HALF_UP, Decimal
def to_cents(dollars) -> int:
"""'32.00', 32 or Decimal('19.5') dollars -> whole cents, rounding half up."""
cents = Decimal(str(dollars)) * 100
return int(cents.quantize(Decimal(1), rounding=ROUND_HALF_UP))
def format_cents(cents: int) -> str:
"""3200 -> '$32.00', 3200000 -> '$32,000.00', -150 -> '-$1.50'."""
sign = "-" if cents < 0 else ""
dollars, rest = divmod(abs(cents), 100)
return f"{sign}${dollars:,}.{rest:02d}"
def percent_off(cents: int, percent: int) -> int:
"""The discount for `percent` (0-100) off, rounded down to a whole cent."""
if not 0 <= percent <= 100:
raise ValueError(f"percent must be 0-100, not {percent}")
return cents * percent // 100
cakeclub/pages.py 24 lines
"""The customer-facing pages: the Plans page and the holiday menu."""
from cakeclub.billing import ANNUAL_MONTHS_CHARGED
from cakeclub.catalog import Catalog
from cakeclub.models import Plan
from cakeclub.money import format_cents
def pricing_page(catalog: Catalog) -> str:
"""The Plans page: every plan, cheapest first, with its monthly and annual price."""
plans = catalog.plans()
plans.sort(key=lambda plan: plan.price)
lines = ["Our plans, cheapest first:"]
for plan in plans:
annual = plan.price * ANNUAL_MONTHS_CHARGED
lines.append(f"{plan.name}: {format_cents(plan.price)} a month, or ${annual:,.2f} a year")
return "\n".join(lines)
def holiday_menu(catalog: Catalog, specials: list[Plan]) -> str:
"""The December menu: the regular plans in menu order, then the holiday specials."""
plans = catalog.plans()
plans.extend(specials)
return "\n".join(f"{plan.name} - {format_cents(plan.price)} a month" for plan in plans)
cakeclub/reports.py 45 lines
"""Reports for the finance team."""
from dataclasses import dataclass
from datetime import date
from cakeclub.models import Invoice, Payment, PaymentKind, PaymentStatus
@dataclass(frozen=True)
class ReportRow:
invoice_id: str
subscriber_id: str
billed_cents: int
paid_cents: int
@property
def outstanding_cents(self) -> int:
return self.billed_cents - self.paid_cents
def month_end_report(invoices: list[Invoice], payments: list[Payment], month_end: date) -> list[ReportRow]:
"""One row per invoice issued on or before month_end, in the order the invoices are
given, with what's been paid against it. Finance runs it on the last day of the month."""
rows = []
for invoice in invoices:
if invoice.issued_on > month_end:
continue
paid = 0
for payment in payments:
if payment.invoice_id != invoice.id:
continue
if payment.status is PaymentStatus.FAILED:
continue
if payment.paid_on > month_end:
continue # it'll be in next month's report
if payment.kind is PaymentKind.REFUND:
paid -= payment.amount_cents
else:
paid += payment.amount_cents
rows.append(ReportRow(invoice.id, invoice.subscriber_id, invoice.total_cents, paid))
return rows
def total_outstanding(rows: list[ReportRow]) -> int:
return sum(row.outstanding_cents for row in rows)
data/price_sheet.csv 4 lines
code,name,monthly_price,boxes_per_month
classic,Classic box,32.00,1
deluxe,Deluxe box,54.00,2
mini,Mini box,19.00,1
tests/test_existing.py 111 lines
"""What already works. These pass now; keep them passing."""
import unittest
from datetime import date
from cakeclub.billing import plan_amount, run_billing, sign_up
from cakeclub.catalog import Catalog, UnknownPlanError, load_price_sheet, menu_export
from cakeclub.models import Interval, Invoice, InvoiceLine, Payment, PaymentKind, PaymentStatus, Plan
from cakeclub.money import format_cents, percent_off, to_cents
from cakeclub.reports import ReportRow, month_end_report, total_outstanding
PRICE_SHEET = """code,name,monthly_price,boxes_per_month
classic,Classic box,32.00,1
deluxe,Deluxe box,54.00,2
mini,Mini box,19.00,1
"""
class TestMoney(unittest.TestCase):
def test_to_cents(self):
self.assertEqual(to_cents("32.00"), 3200)
self.assertEqual(to_cents(19.5), 1950)
self.assertEqual(to_cents("0.005"), 1)
def test_format_cents(self):
self.assertEqual(format_cents(3200), "$32.00")
self.assertEqual(format_cents(3200000), "$32,000.00")
self.assertEqual(format_cents(-150), "-$1.50")
self.assertEqual(format_cents(7), "$0.07")
def test_percent_off_rounds_down(self):
self.assertEqual(percent_off(1999, 10), 199)
with self.assertRaises(ValueError):
percent_off(1000, 120)
class TestCatalog(unittest.TestCase):
def test_price_sheet_is_read_into_cents_in_menu_order(self):
catalog = load_price_sheet(PRICE_SHEET)
self.assertEqual([plan.code for plan in catalog.plans()], ["classic", "deluxe", "mini"])
self.assertEqual(catalog.get("classic"), Plan("classic", "Classic box", 3200, 1))
self.assertEqual(catalog.get("deluxe").boxes_per_month, 2)
def test_unknown_plan(self):
with self.assertRaises(UnknownPlanError):
load_price_sheet(PRICE_SHEET).get("jumbo")
def test_duplicate_codes_are_refused(self):
with self.assertRaises(ValueError):
Catalog([Plan("a", "A", 100), Plan("a", "A again", 200)])
def test_menu_export(self):
self.assertEqual(menu_export(load_price_sheet(PRICE_SHEET)),
"Classic box - $32.00 a month\nDeluxe box - $54.00 a month\nMini box - $19.00 a month")
class TestBilling(unittest.TestCase):
def setUp(self):
self.catalog = load_price_sheet(PRICE_SHEET)
def test_monthly_price(self):
self.assertEqual(plan_amount(self.catalog.get("classic"), Interval.MONTH), 3200)
def test_sign_up(self):
sub = sign_up(self.catalog, "s1", " Ana@Example.com ", date(2027, 3, 4), "deluxe")
self.assertEqual((sub.email, sub.plan_code, sub.interval), ("ana@example.com", "deluxe", Interval.MONTH))
self.assertEqual(sub.next_bill_on, date(2027, 3, 4))
def test_sign_up_without_a_plan_gets_the_first_plan_on_the_menu(self):
self.assertEqual(sign_up(self.catalog, "s1", "ben@example.com", date(2027, 3, 4)).plan_code, "classic")
def test_a_monthly_subscriber_is_billed_on_signup_and_then_monthly(self):
sub = sign_up(self.catalog, "s1", "cy@example.com", date(2027, 1, 15), "classic")
invoices = run_billing([sub], self.catalog, date(2027, 3, 20))
self.assertEqual([inv.issued_on for inv in invoices], [date(2027, 1, 15), date(2027, 2, 15), date(2027, 3, 15)])
self.assertEqual([inv.total_cents for inv in invoices], [3200, 3200, 3200])
self.assertEqual(invoices[0].lines, [InvoiceLine("Classic box, monthly ($32.00)", 3200)])
self.assertEqual(invoices[0].id, "INV-s1-20270115")
self.assertEqual(sub.next_bill_on, date(2027, 4, 15))
def test_a_second_run_on_the_same_day_bills_nothing(self):
sub = sign_up(self.catalog, "s1", "di@example.com", date(2027, 5, 2), "mini")
self.assertEqual(len(run_billing([sub], self.catalog, date(2027, 5, 2))), 1)
self.assertEqual(run_billing([sub], self.catalog, date(2027, 5, 2)), [])
def test_inactive_subscribers_are_not_billed(self):
sub = sign_up(self.catalog, "s1", "ed@example.com", date(2027, 5, 2), "mini")
sub.active = False
self.assertEqual(run_billing([sub], self.catalog, date(2027, 9, 1)), [])
class TestMonthEndReport(unittest.TestCase):
def test_a_small_month(self):
invoices = [
Invoice("i1", "s1", date(2027, 6, 3), [InvoiceLine("Classic box, monthly ($32.00)", 3200)]),
Invoice("i2", "s2", date(2027, 6, 10), [InvoiceLine("Mini box, monthly ($19.00)", 1900)]),
Invoice("i3", "s3", date(2027, 7, 1), [InvoiceLine("Mini box, monthly ($19.00)", 1900)]),
]
payments = [
Payment("p1", "i1", 3200, date(2027, 6, 3)),
Payment("p2", "i2", 1900, date(2027, 6, 10), status=PaymentStatus.FAILED),
Payment("p3", "i2", 1000, date(2027, 6, 12)),
Payment("p4", "i1", 500, date(2027, 6, 20), kind=PaymentKind.REFUND),
]
rows = month_end_report(invoices, payments, date(2027, 6, 30))
self.assertEqual(rows, [ReportRow("i1", "s1", 3200, 2700), ReportRow("i2", "s2", 1900, 1000)])
self.assertEqual(total_outstanding(rows), 500 + 900)
if __name__ == "__main__":
unittest.main()
tests/test_stage1.py 40 lines
"""Bug 1: annual subscribers are charged 100 times too much."""
import unittest
from datetime import date
from cakeclub.billing import plan_amount, run_billing, sign_up
from cakeclub.catalog import load_price_sheet
from cakeclub.models import Interval
from cakeclub.money import format_cents
PRICE_SHEET = """code,name,monthly_price,boxes_per_month
classic,Classic box,32.00,1
deluxe,Deluxe box,54.00,2
mini,Mini box,19.00,1
"""
class TestAnnualPrice(unittest.TestCase):
def setUp(self):
self.catalog = load_price_sheet(PRICE_SHEET)
def test_the_reported_case(self):
sub = sign_up(self.catalog, "s1", "fay@example.com", date(2027, 2, 1), "classic", Interval.YEAR)
[invoice] = run_billing([sub], self.catalog, date(2027, 2, 1))
self.assertEqual(format_cents(invoice.total_cents), "$320.00", "ten months of $32.00")
def test_every_plan_is_ten_months_price(self):
for code, annual in [("classic", 32000), ("deluxe", 54000), ("mini", 19000)]:
with self.subTest(plan=code):
self.assertEqual(plan_amount(self.catalog.get(code), Interval.YEAR), annual)
def test_the_next_year_costs_the_same(self):
sub = sign_up(self.catalog, "s1", "gus@example.com", date(2027, 2, 1), "mini", Interval.YEAR)
invoices = run_billing([sub], self.catalog, date(2028, 2, 1))
self.assertEqual([inv.issued_on for inv in invoices], [date(2027, 2, 1), date(2028, 2, 1)])
self.assertEqual([inv.total_cents for inv in invoices], [19000, 19000])
if __name__ == "__main__":
unittest.main()
tests/test_stage2.py 45 lines
"""Bug 2: billing dates drift after a short month."""
import unittest
from datetime import date
from cakeclub.billing import run_billing, sign_up
from cakeclub.catalog import load_price_sheet
from cakeclub.models import Interval
PRICE_SHEET = """code,name,monthly_price,boxes_per_month
classic,Classic box,32.00,1
deluxe,Deluxe box,54.00,2
mini,Mini box,19.00,1
"""
class TestBillingDates(unittest.TestCase):
def setUp(self):
self.catalog = load_price_sheet(PRICE_SHEET)
def billing_dates(self, started_on, until):
sub = sign_up(self.catalog, "s1", "hal@example.com", started_on, "classic", Interval.MONTH)
return [invoice.issued_on for invoice in run_billing([sub], self.catalog, until)], sub
def test_the_reported_case(self):
dates, sub = self.billing_dates(date(2027, 1, 31), date(2027, 4, 30))
self.assertEqual(dates, [date(2027, 1, 31), date(2027, 2, 28), date(2027, 3, 31), date(2027, 4, 30)])
self.assertEqual(sub.next_bill_on, date(2027, 5, 31))
def test_one_run_a_day_gives_the_same_dates(self):
sub = sign_up(self.catalog, "s1", "ida@example.com", date(2027, 1, 31), "classic")
billed = []
day = date(2027, 1, 31)
while day <= date(2027, 3, 31):
billed += [invoice.issued_on for invoice in run_billing([sub], self.catalog, day)]
day = date.fromordinal(day.toordinal() + 1)
self.assertEqual(billed, [date(2027, 1, 31), date(2027, 2, 28), date(2027, 3, 31)])
def test_mid_month_is_unchanged(self):
dates, sub = self.billing_dates(date(2027, 1, 15), date(2027, 3, 15))
self.assertEqual(dates, [date(2027, 1, 15), date(2027, 2, 15), date(2027, 3, 15)])
if __name__ == "__main__":
unittest.main()
tests/test_stage3.py 32 lines
"""Bug 3: new signups get the wrong default plan."""
import unittest
from datetime import date
from cakeclub.billing import sign_up
from cakeclub.catalog import load_price_sheet
from cakeclub.pages import pricing_page
PRICE_SHEET = """code,name,monthly_price,boxes_per_month
classic,Classic box,32.00,1
deluxe,Deluxe box,54.00,2
mini,Mini box,19.00,1
"""
class TestDefaultPlan(unittest.TestCase):
def setUp(self):
self.catalog = load_price_sheet(PRICE_SHEET)
def test_the_reported_case(self):
pricing_page(self.catalog) # someone looked at the Plans page first
sub = sign_up(self.catalog, "s1", "jo@example.com", date(2027, 11, 20))
self.assertEqual(sub.plan_code, "classic", "the first plan on the menu is the Classic box")
def test_the_plans_page_is_still_cheapest_first(self):
names = [line.split(":")[0] for line in pricing_page(self.catalog).splitlines()[1:]]
self.assertEqual(names, ["Mini box", "Classic box", "Deluxe box"])
if __name__ == "__main__":
unittest.main()
tests/test_stage4.py 62 lines
"""Bug 4: the month-end report never finishes."""
import random
import unittest
from datetime import date
from cakeclub.models import Invoice, InvoiceLine, Payment, PaymentKind, PaymentStatus
from cakeclub.reports import month_end_report, total_outstanding
class TookTooLong(Exception):
pass
class MeteredPayment:
"""Stands in for a Payment and counts how many times anything looks up which invoice it's
for. Past the limit it gives up, the way finance's 15-minute job timeout does."""
def __init__(self, payment, meter):
self._payment = payment
self._meter = meter
@property
def invoice_id(self):
self._meter["lookups"] += 1
if self._meter["lookups"] > self._meter["limit"]:
raise TookTooLong(f"more than {self._meter['limit']:,} payment lookups: this won't finish on a real month")
return self._payment.invoice_id
def __getattr__(self, name):
return getattr(self._payment, name)
def a_busy_month():
"""20,000 invoices in November and 30,000 payments: every invoice paid in full, 5,000 of
them after a failed first try, and 5,000 with a $5.00 refund."""
invoices, payments = [], []
for n in range(20_000):
invoice_id = f"INV-{n:05d}"
invoices.append(Invoice(invoice_id, f"s{n}", date(2027, 11, 1 + n % 30),
[InvoiceLine("Classic box, monthly ($32.00)", 3200)]))
if n < 5_000:
payments.append(Payment(f"f{n}", invoice_id, 3200, date(2027, 11, 1 + n % 30), status=PaymentStatus.FAILED))
payments.append(Payment(f"p{n}", invoice_id, 3200, date(2027, 11, 1 + n % 30)))
if 5_000 <= n < 10_000:
payments.append(Payment(f"r{n}", invoice_id, 500, date(2027, 11, 30), kind=PaymentKind.REFUND))
random.Random(4).shuffle(payments)
return invoices, payments
class TestMonthEndReportScales(unittest.TestCase):
def test_the_reported_case(self):
invoices, payments = a_busy_month()
meter = {"lookups": 0, "limit": 50 * len(payments)}
rows = month_end_report(invoices, [MeteredPayment(p, meter) for p in payments], date(2027, 11, 30))
self.assertEqual(len(rows), 20_000)
self.assertEqual([row.invoice_id for row in rows[:3]], ["INV-00000", "INV-00001", "INV-00002"])
self.assertEqual(total_outstanding(rows), 5_000 * 500)
if __name__ == "__main__":
unittest.main()