"""Hand-worked cases for Means Test. Run: python3 tests/test_means_test.py Every expected number below was worked by hand from the text of regulation.md (the Eskermark Local Support Ordinance shipped with each task), not from the code. The last part regenerates tasks with fixed seeds and recomputes their answers from the task files with a separate assessor written here from the regulation text (exact fractions), then compares with the task's hidden checks. """ import json, os, sys from fractions import Fraction as Fr sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from envs.means_test import gen def near(a, b, tol=1e-6): return abs(a - b) <= tol def person(pid, role, age, *income): return {"person": pid, "role": role, "age": age, "income": [{"type": t, "amount": a} for t, a in income]} def figures(hh, mistake=None): a = gen.assess(hh, mistake) return (a["norm"], a["housing_allowance"], a["countable_income"], a["asset_excess"], a["benefit"]) def same(got, want): return all(near(g, w) for g, w in zip(got, want)) and len(got) == len(want) # ---------------------------------------------------------------- entitlement (sections 1 to 6) # A: one adult, no children, earnings 4000, rent 5000, no assets. # norm = 4100 (one adult) + 900 (common costs, 1 member) = 5000 # housing = min(5000, cap 5200) = 5000 # income = 4000 - min(25% x 4000 = 1000, 1200) = 3000 # benefit = 5000 + 5000 - 3000 - 0 = 7000 A = {"case_id": "A", "members": [person("P1", "applicant", 40, ("earnings", 4000))], "monthly_rent": 5000, "liquid_assets": 0} assert same(figures(A), (5000, 5000, 3000, 0, 7000)) # B: couple, children aged 4 and 14, sanction level 1, rent 9000, assets 16000. # P1 two earnings lines 6000 + 1000 = 7000; disregard min(1750, 1200) = 1200 -> 5800 counts # P2 unemployment benefit 3000 (counted), disability allowance 900 (not counted) # children: child benefit 650 + 650 (counted); the 14-year-old's earnings 800 and meal voucher 200 are not counted # adult amount = 6900 x 0.85 = 5865; children 1450 + 2250 = 3700; common costs (4 members) 1550 # norm = 5865 + 3700 + 1550 = 11115 # housing = min(9000, cap 8100 for 4 members) = 8100 # income = 5800 + 3000 + 650 + 650 = 10100 # exemption = 12000 + 2 x 1500 = 15000; excess = 16000 - 15000 = 1000 # benefit = 11115 + 8100 - 10100 - 1000 = 8115 B = {"case_id": "B", "sanction_level": 1, "monthly_rent": 9000, "liquid_assets": 16000, "members": [ person("P1", "applicant", 41, ("earnings", 6000), ("earnings", 1000)), person("P2", "partner", 39, ("unemployment_benefit", 3000), ("disability_allowance", 900)), person("P3", "child", 4, ("child_benefit", 650)), person("P4", "child", 14, ("earnings", 800), ("child_benefit", 650), ("school_meal_voucher", 200))]} assert same(figures(B), (11115, 8100, 10100, 1000, 8115)) # C: one adult (sanction level 2), child aged 6, and an other resident whose earnings are ignored. # adult amount = 4100 x 0.70 = 2870; child 1800; common costs (2 members, the other resident is not one) 1100 # norm = 2870 + 1800 + 1100 = 5770 # rent share = 6000 x 2 members / 3 residents = 4000; cap for 2 members 6400 -> 4000 # income = pension 2500 + child benefit 600 + maintenance 1000 = 4100 # exemption = 8000 + 1500 = 9500 > assets 9000 -> excess 0 # benefit = 5770 + 4000 - 4100 = 5670 C = {"case_id": "C", "sanction_level": 2, "monthly_rent": 6000, "liquid_assets": 9000, "members": [ person("P1", "applicant", 35, ("pension", 2500)), person("P2", "child", 6, ("child_benefit", 600), ("maintenance", 1000)), person("P3", "other_resident", 22, ("earnings", 7000))]} assert same(figures(C), (5770, 4000, 4100, 0, 5670)) # D: no entitlement. One adult earning 12000: disregard capped at 1200 -> 10800 counts; rent 4000. # 5000 + 4000 - 10800 = -1800 -> benefit 0 D = {"case_id": "D", "members": [person("P1", "applicant", 50, ("earnings", 12000))], "monthly_rent": 4000, "liquid_assets": 0} assert same(figures(D), (5000, 4000, 10800, 0, 0)) and near(gen.assess(D)["raw"], -1800) # E: couple with four children aged 5, 6, 12 and 13 (band edges), no income, rent 9500, assets 20000. # norm = 6900 + (1450 + 1800 + 1800 + 2250 = 7300) + 1900 (6 or more members) = 16100 # housing = min(9500, cap 8800 for 5 or more) = 8800 # exemption = 12000 + 4 x 1500 = 18000; excess = 2000 # benefit = 16100 + 8800 - 0 - 2000 = 22900 E = {"case_id": "E", "monthly_rent": 9500, "liquid_assets": 20000, "members": [ person("P1", "applicant", 40), person("P2", "partner", 40), person("P3", "child", 5), person("P4", "child", 6), person("P5", "child", 12), person("P6", "child", 13)]} assert same(figures(E), (16100, 8800, 0, 2000, 22900)) assert [gen.child_amount(a) for a in (0, 5, 6, 12, 13, 17)] == [1450, 1450, 1800, 1800, 2250, 2250] # ---------------------------------------------------------------- change during the month (section 7) def month(hh, changes, dim, claim=1): hhs, days = gen.month_periods(hh, changes, dim, claim) rates = [gen.assess(h)["benefit"] for h in hhs] return days, rates, gen.prorate(rates, days, dim) # 1. Household A in a 30-day month; on day 11 the earnings are replaced by unemployment benefit 3500. # Days 1 to 10 (10 days) at 7000; days 11 to 30 (20 days) at 5000 + 5000 - 3500 = 6500. # payable = (7000 x 10 + 6500 x 20) / 30 = 200000 / 30 = 6666.67 days, rates, pay = month(A, [(11, {"type": "income_change", "person": "P1", "income": [{"type": "unemployment_benefit", "amount": 3500}]})], 30) assert days == [10, 20] and same(rates, (7000, 6500)) and near(pay, 200000 / 30.0) and round(pay, 2) == 6666.67 # 2. Household A, 31-day month, claim date the 6th, rent rises to 5600 on the 16th. # Nothing for days 1 to 5. Days 6 to 15 (10 days) at 7000; days 16 to 31 (16 days) at 5000 + min(5600, 5200) - 3000 = 7200. # payable = (7000 x 10 + 7200 x 16) / 31 = 185200 / 31 = 5974.19 days, rates, pay = month(A, [(16, {"type": "rent_change", "monthly_rent": 5600})], 31, claim=6) assert days == [10, 16] and same(rates, (7000, 7200)) and round(pay, 2) == 5974.19 # 3. Household A, February (28 days): a partner with no income joins on the 8th and leaves on the 22nd. # Days 1 to 7 at 7000. Days 8 to 21 (14 days): norm 6900 + 1100 = 8000, housing min(5000, 6400) = 5000, income 3000 -> 10000. # Days 22 to 28 (7 days) at 7000 again. # payable = (7000 x 7 + 10000 x 14 + 7000 x 7) / 28 = 238000 / 28 = 8500 days, rates, pay = month(A, [(22, {"type": "member_leaves", "person": "P2"}), (8, {"type": "member_joins", "member": person("P2", "partner", 38)})], 28) assert days == [7, 14, 7] and same(rates, (7000, 10000, 7000)) and near(pay, 8500) # 4. A change on the 1st leaves a single period on the new circumstances. days, rates, pay = month(A, [(1, {"type": "rent_change", "monthly_rent": 4000})], 30) assert days == [30] and same(rates, (6000,)) and near(pay, 6000) # ---------------------------------------------------------------- overpayment and recovery (section 8) # Recovery plan: deduction 410 (one adult) or 690 (couple); number = total / deduction rounded up; the last is the remainder. assert gen.recovery_plan(1000, 1) == (410.0, 3, 180.0) # 1000 / 410 = 2.44 -> 3; 1000 - 2 x 410 = 180 assert gen.recovery_plan(2000, 2) == (690.0, 3, 620.0) # 2000 / 690 = 2.90 -> 3; 2000 - 2 x 690 = 620 assert gen.recovery_plan(1380, 2) == (690.0, 2, 690.0) # exactly two full deductions assert gen.recovery_plan(300, 1) == (410.0, 1, 300.0) # 300 is not "under 300": one deduction of 300 assert gen.recovery_plan(299.99, 1)[1:] == (0, 0.0) # under 300: written off # Household A was paid 7000 for January, February (28 days) and March. A pension of 560 in fact started on 15 February. # after the change: income 3000 + 560 = 3560 -> entitlement 5000 + 5000 - 3560 = 6440 # January correct 7000 overpaid 0 # February days 1 to 14 at 7000, days 15 to 28 (14 days) at 6440: (7000 x 14 + 6440 x 14) / 28 = 6720 overpaid 280 # March correct 6440 overpaid 560 # total overpayment 840 -> 840 / 410 = 2.05 -> 3 deductions, the last 840 - 820 = 20 ch = {"type": "income_change", "person": "P1", "income": [{"type": "earnings", "amount": 4000}, {"type": "pension", "amount": 560}]} after = gen.apply_change(A, ch) assert near(gen.assess(after)["benefit"], 6440) and near(gen.assess(A)["benefit"], 7000) # apply_change leaves A untouched days, rates, feb = month(A, [(15, ch)], 28) assert days == [14, 14] and near(feb, 6720) total = (7000 - 7000) + (7000 - feb) + (7000 - 6440) assert near(total, 840) and gen.recovery_plan(total, gen.n_adults(after)) == (410.0, 3, 20.0) # A partner moving in makes the household a couple: the deduction is then 690, not 410. joined = gen.apply_change(A, {"type": "member_joins", "member": person("P2", "partner", 30, ("earnings", 6000))}) # norm 6900 + 1100 = 8000; housing 5000; income 3000 + (6000 - 1200) = 7800 -> 5200; overpaid 1800 a month assert near(gen.assess(joined)["benefit"], 5200) and gen.recovery_plan(2 * 1800, gen.n_adults(joined)) == (690.0, 6, 150.0) # 3600 / 690 = 5.2 -> 6; 3600 - 3450 # ---------------------------------------------------------------- review: the errors a decision can contain # The review family compares a decision with assess(); these are decisions worked by hand with one known error each. # B without the work disregard: income 7000 + 3000 + 1300 = 11300 -> 11115 + 8100 - 11300 - 1000 = 6915 (correct 8115, difference +1200) assert same(figures(B, "no_disregard"), (11115, 8100, 11300, 1000, 6915)) # B with the rent not capped: housing 9000 -> 9015 (difference 8115 - 9015 = -900) assert same(figures(B, "rent_not_capped"), (11115, 9000, 10100, 1000, 9015)) # B with two single adult amounts: 2 x 4100 x 0.85 = 6970 -> norm 12220 -> 9220 (difference -1105) assert same(figures(B, "two_singles"), (12220, 8100, 10100, 1000, 9220)) # B with the sanction ignored: norm 6900 + 3700 + 1550 = 12150 -> 9150 assert same(figures(B, "sanction_ignored"), (12150, 8100, 10100, 1000, 9150)) # C with the rent not shared with the other resident: housing min(6000, 6400) = 6000 -> 7670 (difference -2000) assert same(figures(C, "rent_not_shared"), (5770, 6000, 4100, 0, 7670)) # ---------------------------------------------------------------- fixed-seed tasks recomputed from their files # A separate assessor written from regulation.md, in exact fractions. It shares nothing with gen.py or oracle.py. def ind_assess(case): mem = [p for p in case["members"] if p["role"] != "other_resident"] adults = [p for p in mem if p["role"] != "child"]; kids = [p for p in mem if p["role"] == "child"] adult = Fr({1: 4100, 2: 6900}[len(adults)]) * (100 - {0: 0, 1: 15, 2: 30}[case.get("sanction_level", 0)]) / 100 norm = adult + sum(1450 if k["age"] <= 5 else 1800 if k["age"] <= 12 else 2250 for k in kids) + [900, 1100, 1350, 1550, 1750, 1900][min(len(mem), 6) - 1] housing = min(Fr(case["monthly_rent"]) * len(mem) / len(case["members"]), [5200, 6400, 7300, 8100, 8800][min(len(mem), 5) - 1]) income = Fr(0) for p in mem: for line in p["income"]: if line["type"] in ("child_benefit", "maintenance", "pension", "unemployment_benefit", "sickness_benefit"): income += line["amount"] if p["role"] != "child": earned = Fr(sum(l["amount"] for l in p["income"] if l["type"] == "earnings")) income += earned - min(earned / 4, 1200) excess = max(Fr(0), Fr(case["liquid_assets"]) - (8000 if len(adults) == 1 else 12000) - 1500 * len(kids)) return {"norm": norm, "housing_allowance": housing, "countable_income": income, "asset_excess": excess, "benefit": max(Fr(0), norm + housing - income - excess), "adults": len(adults)} def ind_change(case, ch): new = json.loads(json.dumps(case)) if ch["type"] == "income_change": for p in new["members"]: if p["person"] == ch["person"]: p["income"] = ch["income"] elif ch["type"] == "rent_change": new["monthly_rent"] = ch["monthly_rent"] elif ch["type"] == "member_joins": new["members"].append(ch["member"]) else: new["members"] = [p for p in new["members"] if p["person"] != ch["person"]] return new def ind_month(case, changes, dim, first=1): """Day by day: the entitlement in force on each day from `first`, then the periods and the prorated total.""" changes = sorted(changes, key=lambda c: c["date"]) daily = [] for day in range(first, dim + 1): cur = case for ch in changes: if int(ch["date"][8:]) <= day: cur = ind_change(cur, ch) daily.append(ind_assess(cur)["benefit"]) cuts = [first] + [int(ch["date"][8:]) for ch in changes] + [dim + 1] return [b - a for a, b in zip(cuts, cuts[1:])], [daily[c - first] for c in cuts[:-1]], sum(daily) / dim def check_all(task, answers): """Every numeric, list and set check of the task whose path is in `answers` must agree; returns how many were compared.""" n = 0 for c in task.checks: if c["path"] not in answers: continue got = answers[c["path"]]; n += 1 if c["type"] == "number": assert abs(float(got) - c["value"]) <= c["abs_tol"], (task.id, c["path"], float(got), c["value"]) elif c["type"] == "int": assert got == c["value"], (task.id, c["path"], got, c["value"]) elif c["type"] == "set": assert sorted(got) == sorted(c["value"]), (task.id, c["path"], got, c["value"]) elif c["item"] == "int": assert list(got) == c["value"], (task.id, c["path"], got, c["value"]) else: assert len(got) == len(c["value"]) and all(abs(float(g) - w) <= 0.01 for g, w in zip(got, c["value"])), (task.id, c["path"]) assert n == len(task.checks), (task.id, n, len(task.checks)) # nothing in the task was left unchecked return n FIG = ("norm", "countable_income", "housing_allowance", "asset_excess", "benefit") compared = 0 for seed in (3, 11, 42): for d in (1, 2, 3): # entitlement t = gen.generate(seed, d, "entitlement"); ans = {"no_entitlement": []}; total = Fr(0) for case in json.loads(t.files["cases.json"])["cases"]: a = ind_assess(case); total += a["benefit"] for f in FIG: ans["households.%s.%s" % (case["case_id"], f)] = a[f] if a["benefit"] == 0: ans["no_entitlement"].append(case["case_id"]) ans["total_payable"] = total if d < 2: ans = dict((k, v) for k, v in ans.items() if not k.endswith("asset_excess")) if d < 3: del ans["total_payable"] compared += check_all(t, ans) # change t = gen.generate(seed, d, "change"); data = json.loads(t.files["cases.json"]); ans = {"nothing_payable": []}; total = Fr(0) for case in data["cases"]: first = int(case["claim_date"][8:]) if "claim_date" in case else 1 days, rates, pay = ind_month(case, case["changes"], data["days_in_month"], first) pre = "cases.%s." % case["case_id"] ans[pre + "days"], ans[pre + "rates"], ans[pre + "payable"] = days, rates, pay if pay == 0: ans["nothing_payable"].append(case["case_id"]) total += pay ans["total_payable"] = total compared += check_all(t, ans) # overpayment t = gen.generate(seed, d, "overpayment"); ans = {"written_off": []}; grand = Fr(0) for case in json.loads(t.files["cases.json"])["cases"]: ch = case["discovered_change"]; after = ind_change(case, ch); pre = "cases.%s." % case["case_id"]; total = Fr(0) for m in case["benefit_paid"]: if m["month"] < ch["date"][:7]: right = ind_assess(case)["benefit"] elif m["month"] > ch["date"][:7]: right = ind_assess(after)["benefit"] else: right = ind_month(case, [ch], m["days_in_month"])[2] ans[pre + "correct." + m["month"]] = right; total += Fr(str(m["paid"])) - right ans[pre + "total_overpayment"] = total if total < 300: ans[pre + "deductions"] = 0 if total > 0: ans["written_off"].append(case["case_id"]) else: ded = Fr(410 if ind_assess(after)["adults"] == 1 else 690) n = -((-total) // ded) # total / deduction, rounded up ans[pre + "deductions"], ans[pre + "last_deduction"] = int(n), total - ded * (n - 1) grand += total ans["total_to_recover"] = grand if d < 2: del ans["written_off"] if d < 3: del ans["total_to_recover"] compared += check_all(t, ans) # review t = gen.generate(seed, d, "review"); ans = {"wrong_decisions": []}; under = over = Fr(0) for case in json.loads(t.files["decisions.json"])["decisions"]: a = ind_assess(case); dec = case["decision"] if all(abs(a[k] - Fr(str(dec[k]))) <= Fr(1, 100) for k in dec): continue ans["wrong_decisions"].append(case["case_id"]); pre = "corrected.%s." % case["case_id"] for k in dec: ans[pre + k] = a[k] diff = a["benefit"] - Fr(str(dec["benefit"])); ans[pre + "difference"] = diff if diff > 0: under += diff else: over -= diff if d >= 3: ans["total_underpaid"], ans["total_overpaid"] = under, over compared += check_all(t, ans) print("means_test: hand-worked cases ok; %d checks in 36 fixed-seed tasks recomputed independently" % compared)