← Lesson
Unit Tests for Tools
Joeven
Run
Reset
Python loads on first run
USERS = { "a": {"invoices": [{"id": 1, "cents": 1999}]}, "b": {"invoices": [{"id": 2, "cents": 5000}]}, } def get_invoice(actor, invoice_id): if not isinstance(invoice_id, int): return {"ok": False, "code": "INVALID_ARGUMENT", "error": "id must be int"} for user, blob in USERS.items(): for inv in blob["invoices"]: if inv["id"] == invoice_id: if user != actor: return {"ok": False, "code": "PERMISSION_DENIED", "error": "not yours"} return {"ok": True, "invoice": inv} return {"ok": False, "code": "NOT_FOUND", "error": "no invoice"} def refund(actor, invoice_id, key, ledger): inv = get_invoice(actor, invoice_id) if not inv["ok"]: return inv if key in ledger: return {"ok": True, "duplicate": True, "cents": ledger[key]} ledger[key] = inv["invoice"]["cents"] return {"ok": True, "duplicate": False, "cents": ledger[key]} ledger = {} print("own invoice", get_invoice("a", 1)["ok"]) print("cross user", get_invoice("a", 2)["code"]) print("bad id", get_invoice("a", "x")["code"]) r1 = refund("a", 1, "k1", ledger) r2 = refund("a", 1, "k1", ledger) print("first dup", r1["duplicate"], "second dup", r2["duplicate"])
Run to execute this in your browser. Nothing is sent to a server.