Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/test_mileage_log.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 19 minutes ago History
test_mileage_log.py · 14.9 KB · 314 lines
1"""A mileage log an auditor can follow, and the reimbursement it produces.
2
3A trip in your own car on business is reimbursed per mile at the year's
4rate; the log -- date, odometer, from, to, why -- is the receipt. So the
5log must be as hard to fudge as a receipt: readings that go backwards,
6two trips claiming the same miles, a rate somebody remembered instead of
7the one on file, and approving your own trip are each refused. Rates are
8the operator's rows (mileage_rates), never code; the numbers below are test
9data, not statements of any year's IRS rate.
10
11Through the real ASGI app with enforcement on and event handlers on, as
12ann (drives her own car), mia (role:manager, approves) and fin
13(role:finance, keeps the rates).
14"""
15
16from __future__ import annotations
17
18from pathlib import Path
19
20import pytest
21
22import object_change_dispatch
23import object_handlers
24import object_records
25from scripts.try_package import Sandbox
26
27ROOT = Path(__file__).resolve().parents[1]
28LOGS = "/collections/mileage_logs/records"
29RATE_2025 = 7000 # test data: 70.00 cents a mile
30RATE_2023 = 6550 # test data: 65.50 cents a mile, the half cent is the point
31
32
33@pytest.fixture
34def box(monkeypatch):
35 monkeypatch.setenv("DBBASIC_ENABLE_EVENT_HANDLERS", "true")
36 object_handlers.invalidate()
37 with Sandbox(["app-nav", "app-settings", "app-intake", "app-finance"]) as sandbox:
38 sandbox.add_user("ann")
39 sandbox.add_user("bob")
40 sandbox.add_user("mia", roles=["manager"])
41 sandbox.add_user("fin", roles=["finance"])
42 for year, rate in ((2025, RATE_2025), (2023, RATE_2023)):
43 ok(sandbox.call("fin", "POST", "/collections/mileage_rates/records", {
44 "year": year, "rate_hundredths_cent": rate, "owner_id": "fin",
45 "source_url": "https://www.irs.gov/tax-professionals/standard-mileage-rates",
46 "source_date": f"{year - 1}-12-19"}))
47 yield sandbox
48 object_handlers.invalidate()
49
50
51def ok(answer, status=(200, 201)):
52 code, body = answer
53 assert code in (status if isinstance(status, tuple) else (status,)), body
54 return body
55
56
57def refused(answer, status):
58 code, body = answer
59 assert code == status, body
60 return body.get("error") if isinstance(body, dict) else body
61
62
63def vehicle(box, who="ann", ownership="personal", name=None):
64 return ok(box.call(who, "POST", "/collections/vehicles/records", {
65 "name": name or f"{who}'s car", "ownership": ownership, "owner_id": who}))["record"]["id"]
66
67
68def trip(box, vehicle_id, who="ann", start=10_000, end=10_123, day="2025-04-02", **extra):
69 body = {"vehicle_id": vehicle_id, "trip_date": day, "from_place": "Office",
70 "to_place": "Acme, Round Rock", "business_purpose": "Quarterly review with Acme",
71 "owner_id": who, **extra}
72 if start is not None:
73 body["start_odometer"] = start
74 if end is not None:
75 body["end_odometer"] = end
76 return box.call(who, "POST", LOGS, body)
77
78
79def approve(box, log_id, who="ann"):
80 ok(box.call(who, "PUT", f"{LOGS}/{log_id}", {"status": "submitted"}))
81 return box.call("mia", "PUT", f"{LOGS}/{log_id}", {"status": "approved"})
82
83
84def expense_for(box, log_id):
85 body = ok(box.call("admin", "GET", f"/collections/expenses/records?generated_from=mileage_logs/{log_id}"))
86 return body["records"]
87
88
89def test_the_miles_are_worked_out_from_the_odometer(box):
90 record = ok(trip(box, vehicle(box)))["record"]
91 assert record["miles"] == "123"
92
93
94def test_an_end_reading_at_or_below_the_start_is_refused(box):
95 car = vehicle(box)
96 assert "greater than the start" in refused(trip(box, car, start=500, end=400), 400)
97 assert "greater than the start" in refused(trip(box, car, start=500, end=500), 400)
98
99
100def test_a_log_needs_a_purpose_and_places(box):
101 car = vehicle(box)
102 refused(box.call("ann", "POST", LOGS, {"vehicle_id": car, "trip_date": "2025-04-02",
103 "miles": 10, "from_place": "A", "to_place": "B",
104 "owner_id": "ann"}), 400)
105
106
107def test_overlapping_odometer_ranges_in_one_vehicle_are_refused(box):
108 car = vehicle(box)
109 ok(trip(box, car, start=1000, end=1100))
110 assert "overlaps" in refused(trip(box, car, start=1050, end=1200), 409)
111 assert "overlaps" in refused(trip(box, car, start=900, end=1001), 409)
112 assert "overlaps" in refused(trip(box, car, start=1010, end=1020), 409)
113 ok(trip(box, car, start=1100, end=1150)) # starts where the last one ended
114 ok(trip(box, vehicle(box, name="second car"), start=1000, end=1100)) # another vehicle
115
116
117def test_a_rejected_trip_frees_its_miles_for_the_corrected_one(box):
118 car = vehicle(box)
119 first = ok(trip(box, car, start=1000, end=1100))["record"]
120 ok(box.call("ann", "PUT", f"{LOGS}/{first['id']}", {"status": "submitted"}))
121 ok(box.call("mia", "PUT", f"{LOGS}/{first['id']}", {"status": "rejected"}))
122 ok(trip(box, car, start=1000, end=1090))
123 # ...and the rejected one cannot be reopened onto miles now taken.
124 assert "overlaps" in refused(box.call("ann", "PUT", f"{LOGS}/{first['id']}", {"status": "draft"}), 409)
125
126
127def test_a_writer_below_the_hook_meets_the_same_odometer_rules(box):
128 car = vehicle(box)
129 ok(trip(box, car, start=1000, end=1100))
130 row = {"vehicle_id": car, "trip_date": "2025-04-03", "start_odometer": "1099",
131 "end_odometer": "1200", "miles": "101", "from_place": "A", "to_place": "B",
132 "business_purpose": "Import", "owner_id": "ann"}
133 with pytest.raises(object_records.CheckRefusedError, match="overlaps"):
134 object_records.create_collection_record("mileage_logs", row, base_dir=box.data_dir,
135 roots=[box.objects_dir])
136 with pytest.raises(object_records.CheckRefusedError, match="readings say 100"):
137 object_records.create_collection_record(
138 "mileage_logs", {**row, "start_odometer": "1100", "miles": "5"},
139 base_dir=box.data_dir, roots=[box.objects_dir])
140
141
142def test_nobody_logs_trips_in_somebody_elses_vehicle(box):
143 annes = vehicle(box)
144 assert refused(trip(box, annes, who="bob"), 400)
145
146
147def test_approval_stamps_the_years_rate_and_creates_one_reimbursable_expense(box):
148 log = ok(trip(box, vehicle(box), start=20_000, end=20_123))["record"]
149 approved = ok(approve(box, log["id"]))["record"]
150 # 123 miles x 70.00 cents = 8610 cents, exactly
151 assert (approved["rate_year"], approved["rate_hundredths_cent"], approved["reimbursement_cents"]) == (
152 "2025", str(RATE_2025), "8610")
153 [expense] = expense_for(box, log["id"])
154 assert (expense["amount_cents"], expense["paid_by"], expense["status"]) == ("8610", "personal", "approved")
155 assert (expense["category_id"], expense["approved_by"], expense["owner_id"]) == ("expcat_mileage", "mia", "ann")
156 assert expense["business_purpose"] == "Quarterly review with Acme"
157 assert (expense["deductible_cents"], expense["receipt_required"]) == ("8610", "false")
158 # replaying the event creates nothing more
159 object_handlers.invalidate()
160 for _ in range(2):
161 object_records.update_collection_record("mileage_logs", log["id"], {"notes": "seen"},
162 base_dir=box.data_dir, roots=[box.objects_dir])
163 box.call("mia", "PUT", f"{LOGS}/{log['id']}", {"notes": "seen again"})
164 assert len(expense_for(box, log["id"])) == 1
165
166
167def test_a_half_cent_rate_rounds_half_up_once(box):
168 log = ok(trip(box, vehicle(box), start=0, end=123, day="2023-06-01"))["record"]
169 approved = ok(approve(box, log["id"]))["record"]
170 # 123 x 65.50 = 8056.5 cents -> 8057
171 assert approved["reimbursement_cents"] == "8057"
172 assert expense_for(box, log["id"])[0]["amount_cents"] == "8057"
173
174
175def test_a_year_with_no_rate_is_refused_by_name(box):
176 log = ok(trip(box, vehicle(box), day="2024-02-02"))["record"]
177 ok(box.call("ann", "PUT", f"{LOGS}/{log['id']}", {"status": "submitted"}))
178 assert "no mileage rate for 2024" in refused(
179 box.call("mia", "PUT", f"{LOGS}/{log['id']}", {"status": "approved"}), 409)
180
181
182def test_nobody_approves_their_own_trip(box):
183 log = ok(trip(box, vehicle(box)))["record"]
184 ok(box.call("ann", "PUT", f"{LOGS}/{log['id']}", {"status": "submitted"}))
185 refused(box.call("ann", "PUT", f"{LOGS}/{log['id']}", {"status": "approved"}), 403)
186
187
188def test_an_approval_below_the_hook_must_carry_the_years_rate(box):
189 log = ok(trip(box, vehicle(box)))["record"]
190 ok(box.call("ann", "PUT", f"{LOGS}/{log['id']}", {"status": "submitted"}))
191 with pytest.raises(object_records.CheckRefusedError, match="rate_hundredths_cent"):
192 object_records.update_collection_record(
193 "mileage_logs", log["id"], {"status": "approved", "rate_year": "2025",
194 "rate_hundredths_cent": "9900", "reimbursement_cents": "12177"},
195 base_dir=box.data_dir, roots=[box.objects_dir])
196
197
198def test_editing_the_rate_restates_nothing_already_approved(box):
199 log = ok(trip(box, vehicle(box)))["record"]
200 ok(approve(box, log["id"]))
201 rates = ok(box.call("fin", "GET", "/collections/mileage_rates/records?year=2025"))["records"]
202 ok(box.call("fin", "PUT", f"/collections/mileage_rates/records/{rates[0]['id']}",
203 {"rate_hundredths_cent": 7250}))
204 again = ok(box.call("ann", "GET", f"{LOGS}/{log['id']}"))["record"]
205 assert again["reimbursement_cents"] == "8610"
206 code, body = box.call("mia", "PUT", f"{LOGS}/{log['id']}", {"miles": 200})
207 assert code == 409 and body["code"] == "record_locked"
208
209
210def test_a_business_vehicles_trip_is_evidence_and_reimburses_nothing(box):
211 van = vehicle(box, ownership="business", name="the van")
212 log = ok(trip(box, van, start=5, end=55))["record"]
213 approved = ok(approve(box, log["id"]))["record"]
214 assert (approved["reimbursement_cents"], approved["rate_hundredths_cent"]) == ("0", str(RATE_2025))
215 assert expense_for(box, log["id"]) == []
216
217
218def test_rejecting_an_approved_trip_rejects_its_expense_and_the_books_reverse(box, monkeypatch):
219 for key, value in (("expenses.journal.expense_account", "acct-x"),
220 ("expenses.journal.reimbursable_account", "acct-owed")):
221 ok(box.call("admin", "POST", "/collections/app_settings/records", {"key": key, "value": value}))
222 for account_id, kind in (("acct-x", "expense"), ("acct-owed", "liability")):
223 ok(box.call("admin", "POST", "/collections/fin_accounts/records",
224 {"id": account_id, "name": account_id, "account_type": kind}))
225 monkeypatch.setenv(object_change_dispatch.ENABLE_ENV, "true")
226 roots = [box.objects_dir]
227 assert object_change_dispatch.dispatch_pending(base_dir=box.data_dir, roots=roots)["processed"] == 0
228
229 log = ok(trip(box, vehicle(box)))["record"]
230 ok(approve(box, log["id"]))
231 _replay(box) # the expense's own created event books it
232 [expense] = expense_for(box, log["id"])
233 journals = ok(box.call("admin", "GET", "/collections/fin_journals/records?limit=100"))["records"]
234 assert [j["generated_from"] for j in journals] == [f"expenses/{expense['id']}"]
235
236 ok(box.call("mia", "PUT", f"{LOGS}/{log['id']}", {"status": "rejected"}))
237 _replay(box)
238 assert expense_for(box, log["id"])[0]["status"] == "rejected"
239 journals = ok(box.call("admin", "GET", "/collections/fin_journals/records?limit=100"))["records"]
240 assert sorted(j["generated_from"].split(":")[0] for j in journals) == [
241 f"expenses/{expense['id']}", "reversal"]
242
243
244def _replay(box):
245 for _ in range(8):
246 outcome = object_change_dispatch.dispatch_pending(base_dir=box.data_dir, roots=[box.objects_dir])
247 assert outcome["errors"] == 0, outcome["results"]
248 if not outcome["processed"]:
249 return
250 raise AssertionError("change dispatch never went quiet")
251
252
253def test_who_may_do_what_with_trips_vehicles_and_rates(box):
254 car = vehicle(box)
255 log = ok(trip(box, car))["record"]
256 assert ok(box.call("bob", "GET", LOGS))["total"] == 0
257 assert ok(box.call("mia", "GET", LOGS))["total"] == 1
258 assert ok(box.call("fin", "GET", LOGS))["total"] == 1
259 refused(box.call("fin", "PUT", f"{LOGS}/{log['id']}", {"notes": "x"}), 403)
260 ok(box.call("ann", "DELETE", f"{LOGS}/{log['id']}")) # a draft is a note to self
261 log = ok(trip(box, car))["record"]
262 ok(box.call("ann", "PUT", f"{LOGS}/{log['id']}", {"status": "submitted"}))
263 refused(box.call("ann", "DELETE", f"{LOGS}/{log['id']}"), 403) # a claim is not
264 refused(box.call("ann", "DELETE", f"/collections/vehicles/records/{car}"), 403)
265 assert ok(box.call("ann", "GET", "/collections/mileage_rates/records"))["total"] == 2
266 rate_id = ok(box.call("ann", "GET", "/collections/mileage_rates/records"))["records"][0]["id"]
267 refused(box.call("ann", "PUT", f"/collections/mileage_rates/records/{rate_id}",
268 {"rate_hundredths_cent": 9999}), 403)
269 refused(box.call("mia", "POST", "/collections/mileage_rates/records", {
270 "year": 2026, "rate_hundredths_cent": 1, "source_url": "x", "source_date": "2026-01-01",
271 "owner_id": "mia"}), 403)
272 code, body = box.call("fin", "POST", "/collections/mileage_rates/records", {
273 "year": 2025, "rate_hundredths_cent": 1, "source_url": "x", "source_date": "2026-01-01",
274 "owner_id": "fin"})
275 assert code == 409 and body["code"] == "unique_violation"
276
277
278def test_submitted_mileage_is_a_queue_for_the_approver(box):
279 log = ok(trip(box, vehicle(box)))["record"]
280 ok(box.call("ann", "PUT", f"{LOGS}/{log['id']}", {"status": "submitted"}))
281 attention = {row["id"]: row for row in ok(box.call("mia", "GET", "/objects/action_nav_entries"))["attention"]}
282 assert attention["mileage_to_approve"]["count"] == 1
283 assert attention["mileage_to_approve"]["detail"] == "123 miles awaiting approval"
284
285
286def test_two_overlapping_trips_written_at_once_cannot_both_land(box):
287 """The overlap rule is a locked check, so it holds under a race a hook
288 (advisory, before the lock) could not close: eight writers each try to
289 claim the same odometer range at the same moment; one lands."""
290 import threading
291
292 car = vehicle(box)
293 barrier = threading.Barrier(8)
294 outcomes = []
295
296 def claim(index):
297 row = {"vehicle_id": car, "trip_date": "2025-04-03", "start_odometer": "100",
298 "end_odometer": str(150 + index), "miles": str(50 + index), "from_place": "A",
299 "to_place": "B", "business_purpose": "Race", "owner_id": "ann"}
300 barrier.wait()
301 try:
302 object_records.create_collection_record("mileage_logs", row, base_dir=box.data_dir,
303 roots=[box.objects_dir])
304 outcomes.append("written")
305 except object_records.CheckRefusedError:
306 outcomes.append("refused")
307
308 threads = [threading.Thread(target=claim, args=(i,)) for i in range(8)]
309 for thread in threads:
310 thread.start()
311 for thread in threads:
312 thread.join()
313 assert sorted(outcomes) == ["refused"] * 7 + ["written"]
314 assert ok(box.call("ann", "GET", LOGS))["total"] == 1