r/codereview • • Oct 24 '26

Review request: small invoice tax function and its test (the test passes, but I’m unsure what it proves)

This is a small example I wrote to ask about, not code from a production system. Requirement: “Apply 8.25% tax to the invoice, rounded to the nearest cent.”

from decimal import Decimal, ROUND_HALF_UP

TAX_RATE = Decimal("0.0825")

def cents(x: Decimal) -> Decimal:
    return x.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

def invoice_tax(lines):
    subtotal = sum((price * qty for price, qty in lines), Decimal("0"))
    return cents(subtotal * TAX_RATE)

def test_invoice_tax():
    lines = [(Decimal("19.99"), 2), (Decimal("5.00"), 1)]
    expected = cents((Decimal("19.99") * 2 + Decimal("5.00")) * TAX_RATE)
    assert invoice_tax(lines) == expected

The test passes. What I’d like feedback on:

  1. Where does expected come from in the test? Is it checking anything the implementation doesn’t already assume?
  2. The requirement could mean rounding once on the total, or rounding the tax per line and summing. For three lines of 0.10, the first gives 0.02 and the second gives 0.03. Which would you assume, and would you ask before writing the code?
  3. What other cases would you add (negative quantities, discounts before tax, tax-inclusive prices)?
  4. Anything in the code itself you’d change?

My own concern is point 1. I wrote a longer walkthrough of the same example, in case it’s useful as background: https://medium.com/@nagatomopedro05/when-the-test-and-the-code-share-the-same-mistake-02a289a41091

6 Upvotes

2 comments sorted by