askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
test_tracking.py · 27.9 KB · 629 lines
| 1 | """The carrier-facing layer: labels, tracking, and the honest gap. |
| 2 | |
| 3 | The property this whole slice is built around is that a shop with NO |
| 4 | carrier configured loses nothing. It types the tracking number on the |
| 5 | shipment, prints the paperwork, and the poll leaves every row exactly as |
| 6 | it found it -- counting no attempt against a parcel for the shop's missing |
| 7 | credentials, because an attempt counter that fills up while somebody is |
| 8 | still fetching an API key would retire a warehouse's worth of parcels for |
| 9 | a reason that has nothing to do with any of them. |
| 10 | |
| 11 | The rest are the ones a carrier integration gets wrong. An unconfigured |
| 12 | button explains what to configure instead of 404ing or claiming to have |
| 13 | bought postage. A label is evidence, so its bytes are stored and pointed |
| 14 | at rather than described. A parcel the carrier cannot read stops being |
| 15 | asked about after three tries and starts being VISIBLE. A poll that runs |
| 16 | twice does not deliver anything twice. And a connector answering to a name |
| 17 | the shop did not configure is refused, because quietly using the wrong |
| 18 | carrier is worse than doing nothing and saying so. |
| 19 | """ |
| 20 | |
| 21 | import base64 |
| 22 | import json |
| 23 | import pathlib |
| 24 | import shutil |
| 25 | from datetime import date, timedelta |
| 26 | |
| 27 | from conftest import stage_collection |
| 28 | |
| 29 | import object_connectors |
| 30 | import object_execution |
| 31 | import object_packages |
| 32 | import object_records |
| 33 | import object_user_files |
| 34 | import python_object_runtime |
| 35 | |
| 36 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 37 | PACKAGES = REPO_ROOT / "packages" |
| 38 | SHIPPING = PACKAGES / "app-shipping" |
| 39 | RUNTIME = python_object_runtime.PythonObjectRuntime() |
| 40 | |
| 41 | TODAY = date.today().isoformat() |
| 42 | |
| 43 | |
| 44 | def setup_env(tmp_path, monkeypatch, *, settings=()): |
| 45 | """A data dir with the collections this slice touches, and the package |
| 46 | roots pinned explicitly. |
| 47 | |
| 48 | Pinning DBBASIC_PACKAGES_DIR at the real packages directory (rather |
| 49 | than leaning on the cwd-relative default) is not tidiness: the carrier |
| 50 | boundary is RESOLVED through the package roots, so a test that let the |
| 51 | working directory decide which packages exist would be testing the |
| 52 | shell it was launched from. The private overlay is pointed at a path |
| 53 | that does not exist for the same reason -- a deployment's private |
| 54 | carrier must not decide what these tests see. |
| 55 | """ |
| 56 | data_dir = tmp_path / "data" |
| 57 | for pkg, name in (("app-shipping", "shipments"), |
| 58 | ("app-shipping", "shipment_lines"), |
| 59 | ("app-catalog", "products"), |
| 60 | ("app-orders", "orders"), ("app-orders", "order_lines"), |
| 61 | ("app-files", "files")): |
| 62 | stage_collection(data_dir, pkg, name) |
| 63 | rows = "".join(f"s{i}\t{k}\t{v}\t\n" for i, (k, v) in enumerate(settings)) |
| 64 | stage_collection(data_dir, "app-settings", "app_settings", rows=rows) |
| 65 | |
| 66 | objects_root = tmp_path / "objects" |
| 67 | shutil.copytree(SHIPPING / "objects", objects_root, dirs_exist_ok=True) |
| 68 | |
| 69 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 70 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root)) |
| 71 | monkeypatch.setenv("DBBASIC_PACKAGES_DIR", str(PACKAGES)) |
| 72 | monkeypatch.setenv("DBBASIC_PRIVATE_PACKAGES_DIR", str(tmp_path / "nowhere")) |
| 73 | return data_dir, objects_root |
| 74 | |
| 75 | |
| 76 | def run(objects_root, object_id, method, payload): |
| 77 | return object_execution.execute_object( |
| 78 | RUNTIME, |
| 79 | object_execution.ObjectExecutionRequest( |
| 80 | object_id, method=method, payload=payload), |
| 81 | roots=[objects_root]).result |
| 82 | |
| 83 | |
| 84 | # --- a shop with one parcel on the road ---------------------------------------- |
| 85 | |
| 86 | def shop(tmp_path, monkeypatch, *, provider=None, stuck_days=None): |
| 87 | settings = [] |
| 88 | if provider is not None: |
| 89 | settings.append(("carrier.provider", provider)) |
| 90 | if stuck_days is not None: |
| 91 | settings.append(("carrier.stuck_days", stuck_days)) |
| 92 | data_dir, objects_root = setup_env(tmp_path, monkeypatch, settings=settings) |
| 93 | |
| 94 | object_records.create_collection_record( |
| 95 | "products", |
| 96 | {"id": "p1", "name": "Enamel Mug", "sku": "P1", "product_type": "physical", |
| 97 | "price_cents": "1200", "currency": "USD", "is_active": "true", |
| 98 | "owner_id": "shop"}, base_dir=data_dir) |
| 99 | object_records.create_collection_record( |
| 100 | "orders", |
| 101 | {"id": "ord-1", "doc_type": "sale", "number": "SO-0001", |
| 102 | "customer_name": "Ada Lovelace", "customer_email": "ada@example.test", |
| 103 | "currency": "USD", "status": "draft", "order_date": "2026-07-01", |
| 104 | "owner_id": "shop"}, base_dir=data_dir) |
| 105 | object_records.update_collection_record( |
| 106 | "orders", "ord-1", {"status": "confirmed"}, base_dir=data_dir, actor="test") |
| 107 | object_records.create_collection_record( |
| 108 | "order_lines", |
| 109 | {"id": "line-1", "order_id": "ord-1", "product_id": "p1", |
| 110 | "description": "Enamel Mug", "quantity": "1", "unit_price_cents": "1200", |
| 111 | "line_total_cents": "1200", "owner_id": "shop"}, base_dir=data_dir) |
| 112 | return data_dir, objects_root |
| 113 | |
| 114 | |
| 115 | def shipment(data_dir, shipment_id="shp-1", *, status="shipped", direction="outbound", |
| 116 | tracking="TRK-1", shipped_on=TODAY, **fields): |
| 117 | """A shipment already on the road. Written straight through the ladder, |
| 118 | the way the packing bench moves it.""" |
| 119 | record = {"id": shipment_id, "order_id": "ord-1", "direction": direction, |
| 120 | "status": "authorized" if direction == "inbound" else "open", |
| 121 | "service": "ground", "carrier": "Van Lines", |
| 122 | "tracking_number": tracking, "ship_to_name": "Ada Lovelace", |
| 123 | "shipped_on": shipped_on, "owner_id": "shop"} |
| 124 | record.update({key: str(value) for key, value in fields.items()}) |
| 125 | object_records.create_collection_record("shipments", record, base_dir=data_dir) |
| 126 | object_records.create_collection_record( |
| 127 | "shipment_lines", |
| 128 | {"id": f"{shipment_id}-l1", "shipment_id": shipment_id, |
| 129 | "order_line_id": "line-1", "product_id": "p1", |
| 130 | "description": "Enamel Mug", "quantity": "1", "owner_id": "shop"}, |
| 131 | base_dir=data_dir) |
| 132 | # Up the real ladder, one rung at a time, the way the bench moves it -- |
| 133 | # the transition map is part of what is being tested everywhere else. |
| 134 | ladder = (["open", "packed", "shipped", "in_transit", "delivered"] |
| 135 | if direction == "outbound" |
| 136 | else ["authorized", "in_transit", "received"]) |
| 137 | for step in ladder[1:ladder.index(status) + 1]: |
| 138 | object_records.update_collection_record( |
| 139 | "shipments", shipment_id, {"status": step}, |
| 140 | base_dir=data_dir, actor="test") |
| 141 | return object_records.get_collection_record("shipments", shipment_id, |
| 142 | base_dir=data_dir) |
| 143 | |
| 144 | |
| 145 | def read(data_dir, shipment_id="shp-1"): |
| 146 | return object_records.get_collection_record("shipments", shipment_id, |
| 147 | base_dir=data_dir) |
| 148 | |
| 149 | |
| 150 | def poll(objects_root, **payload): |
| 151 | return run(objects_root, "system_tracking_poll", "POST", payload) |
| 152 | |
| 153 | |
| 154 | def buy_label(objects_root, **payload): |
| 155 | return run(objects_root, "action_buy_label", "POST", payload) |
| 156 | |
| 157 | |
| 158 | def attention(objects_root): |
| 159 | return run(objects_root, "system_shipment_attention", "COUNT", {}) |
| 160 | |
| 161 | |
| 162 | def fulfil(objects_root, shipment_id): |
| 163 | """The dispatcher's own payload shape, which is how the order learns.""" |
| 164 | return run(objects_root, "system_order_fulfillment", "EVENT", |
| 165 | {"event": "shipments.record.updated", "collection": "shipments", |
| 166 | "record_id": shipment_id, "action": "update"}) |
| 167 | |
| 168 | |
| 169 | # --- a carrier that is not this package's ---------------------------------------- |
| 170 | |
| 171 | CARRIER_TEMPLATE = ''' |
| 172 | PROVIDER = "fakeco" |
| 173 | |
| 174 | def track(shipment, *, base_dir=None): |
| 175 | return {outcome} |
| 176 | |
| 177 | def buy_label(shipment, *, base_dir=None, tracking_number="", label_bytes=None, |
| 178 | label_content_type="", label_filename=""): |
| 179 | return {{"ok": True, "tracking_number": "FAKE-1", |
| 180 | "label_bytes": b"%PDF-fake", "label_content_type": "application/pdf"}} |
| 181 | |
| 182 | def reconcile(record, *, base_dir=None): |
| 183 | return {{"skip": True}} |
| 184 | ''' |
| 185 | |
| 186 | |
| 187 | def install_carrier(tmp_path, monkeypatch, outcome, *, provider="fakeco"): |
| 188 | """A second package declaring a connector for shipments -- the whole |
| 189 | extension story in eight lines. Nothing in app-shipping is edited to |
| 190 | make this work: the declaration is resolved through the same |
| 191 | object_packages.iter_connectors the daemon's reconcile pass uses.""" |
| 192 | root = tmp_path / "carrier-packages" |
| 193 | package = root / "app-fakeco" |
| 194 | (package / "connectors").mkdir(parents=True) |
| 195 | (package / "connectors" / "fakeco.py").write_text( |
| 196 | CARRIER_TEMPLATE.format(outcome=outcome).replace( |
| 197 | 'PROVIDER = "fakeco"', f'PROVIDER = "{provider}"')) |
| 198 | (package / "dbbasic-package.json").write_text(json.dumps({ |
| 199 | "id": "app-fakeco", "name": "FakeCo", "version": "1.0.0", |
| 200 | "connectors": [{"collection": "shipments", |
| 201 | "module": "connectors/fakeco.py", "entry": "reconcile"}], |
| 202 | })) |
| 203 | monkeypatch.setenv("DBBASIC_PACKAGES_DIR", str(root)) |
| 204 | return root |
| 205 | |
| 206 | |
| 207 | # --- the shop with no carrier at all ---------------------------------------------- |
| 208 | |
| 209 | def test_an_unconfigured_carrier_leaves_the_manual_path_fully_working( |
| 210 | tmp_path, monkeypatch): |
| 211 | """The sentence the whole slice is built around. Nothing configured, and |
| 212 | the parcel still has a tracking number, still prints, and is left |
| 213 | exactly as the operator typed it.""" |
| 214 | data_dir, objects_root = shop(tmp_path, monkeypatch) |
| 215 | shipment(data_dir, tracking="1Z-TYPED-BY-HAND") |
| 216 | object_records.update_collection_record( |
| 217 | "shipments", "shp-1", {"tracking_status": "Handed to the driver"}, |
| 218 | base_dir=data_dir, actor="operator") |
| 219 | |
| 220 | result = poll(objects_root) |
| 221 | assert result["provider"] == "none" |
| 222 | assert "carrier.provider" in result["skipped"] |
| 223 | assert result["polled"] == 0 |
| 224 | |
| 225 | row = read(data_dir) |
| 226 | assert row["tracking_number"] == "1Z-TYPED-BY-HAND" |
| 227 | assert row["tracking_status"] == "Handed to the driver" |
| 228 | assert row["tracking_attempts"] in ("", "0") |
| 229 | assert row["tracking_checked_at"] == "" |
| 230 | assert row["status"] == "shipped" |
| 231 | |
| 232 | slip = run(objects_root, "site_packing_slip", "GET", {"shipment_id": "shp-1"}) |
| 233 | assert "1Z-TYPED-BY-HAND" in slip["body"] |
| 234 | |
| 235 | |
| 236 | def test_buying_a_label_with_no_provider_is_a_409_that_names_the_setting( |
| 237 | tmp_path, monkeypatch): |
| 238 | """Stripe's precedent: the shop can see the button, so the button owes |
| 239 | them a sentence they can act on rather than a 404 or a fake success.""" |
| 240 | data_dir, objects_root = shop(tmp_path, monkeypatch) |
| 241 | shipment(data_dir, tracking="") |
| 242 | |
| 243 | refused = buy_label(objects_root, shipment_id="shp-1") |
| 244 | assert refused["status"] == 409 |
| 245 | assert refused["missing_settings"] == ["carrier.provider"] |
| 246 | assert "carrier.provider" in refused["error"] |
| 247 | assert "manual" in refused["error"] |
| 248 | assert read(data_dir)["tracking_number"] == "" |
| 249 | |
| 250 | |
| 251 | def test_an_unknown_shipment_and_a_finished_one_are_refused_before_any_carrier( |
| 252 | tmp_path, monkeypatch): |
| 253 | data_dir, objects_root = shop(tmp_path, monkeypatch, provider="manual") |
| 254 | assert buy_label(objects_root, shipment_id="no-such")["status"] == 404 |
| 255 | assert buy_label(objects_root)["status"] == 400 |
| 256 | |
| 257 | shipment(data_dir, "shp-done", status="delivered") |
| 258 | refused = buy_label(objects_root, shipment_id="shp-done", |
| 259 | tracking_number="TOO-LATE") |
| 260 | assert refused["status"] == 409 |
| 261 | assert "delivered" in refused["error"] |
| 262 | |
| 263 | |
| 264 | # --- the manual carrier ------------------------------------------------------------ |
| 265 | |
| 266 | LABEL = base64.b64encode(b"%PDF-1.4 fake label").decode() |
| 267 | |
| 268 | |
| 269 | def test_a_manual_label_stamps_the_tracking_number_and_the_file( |
| 270 | tmp_path, monkeypatch): |
| 271 | """The label is evidence (docs/logic-decisions.md #8): the bytes are |
| 272 | stored and pointed at, not described.""" |
| 273 | data_dir, objects_root = shop(tmp_path, monkeypatch, provider="manual") |
| 274 | shipment(data_dir, tracking="") |
| 275 | |
| 276 | result = buy_label(objects_root, shipment_id="shp-1", |
| 277 | tracking_number="1Z-COUNTER-42", label_base64=LABEL, |
| 278 | label_filename="counter.pdf") |
| 279 | assert result["ok"] and result["provider"] == "manual" |
| 280 | assert result["kind"] == "shipping label" |
| 281 | assert result["tracking_number"] == "1Z-COUNTER-42" |
| 282 | |
| 283 | row = read(data_dir) |
| 284 | assert row["tracking_number"] == "1Z-COUNTER-42" |
| 285 | assert row["label_file_id"] == result["label_file_id"] |
| 286 | assert result["label_url"] == f"/api/files/{result['label_file_id']}" |
| 287 | # The bytes are really there, and openable through the ordinary door. |
| 288 | assert object_user_files.read_file("shop", result["label_file_id"], |
| 289 | base_dir=data_dir) == b"%PDF-1.4 fake label" |
| 290 | record = object_records.get_collection_record( |
| 291 | "files", result["label_file_id"], base_dir=data_dir) |
| 292 | assert record["parent_collection"] == "shipments" |
| 293 | assert record["parent_id"] == "shp-1" |
| 294 | assert record["filename"] == "counter.pdf" |
| 295 | # The label did not move the parcel: printing is not handing over. |
| 296 | assert row["status"] == "shipped" |
| 297 | |
| 298 | |
| 299 | def test_a_second_label_is_a_second_artefact_not_an_overwrite( |
| 300 | tmp_path, monkeypatch): |
| 301 | """Evidence is never edited to agree with the current plan -- the first |
| 302 | label may be on a box somewhere.""" |
| 303 | data_dir, objects_root = shop(tmp_path, monkeypatch, provider="manual") |
| 304 | shipment(data_dir, tracking="") |
| 305 | |
| 306 | first = buy_label(objects_root, shipment_id="shp-1", |
| 307 | tracking_number="ONE", label_base64=LABEL) |
| 308 | second = buy_label(objects_root, shipment_id="shp-1", |
| 309 | tracking_number="TWO", label_base64=LABEL) |
| 310 | assert first["label_file_id"] != second["label_file_id"] |
| 311 | assert object_user_files.read_file("shop", first["label_file_id"], |
| 312 | base_dir=data_dir) |
| 313 | assert read(data_dir)["label_file_id"] == second["label_file_id"] |
| 314 | |
| 315 | |
| 316 | def test_a_manual_label_needs_the_number_the_counter_gave_you( |
| 317 | tmp_path, monkeypatch): |
| 318 | data_dir, objects_root = shop(tmp_path, monkeypatch, provider="manual") |
| 319 | shipment(data_dir, tracking="") |
| 320 | |
| 321 | refused = buy_label(objects_root, shipment_id="shp-1") |
| 322 | assert refused["status"] == 400 |
| 323 | assert "tracking number" in refused["error"] |
| 324 | assert read(data_dir)["tracking_number"] == "" |
| 325 | |
| 326 | |
| 327 | def test_a_label_without_a_pdf_still_records_the_tracking_number( |
| 328 | tmp_path, monkeypatch): |
| 329 | """Plenty of shops print from the carrier's own site and never hold the |
| 330 | bytes; refusing them a tracking number over a missing PDF would be |
| 331 | paperwork for its own sake.""" |
| 332 | data_dir, objects_root = shop(tmp_path, monkeypatch, provider="manual") |
| 333 | shipment(data_dir, tracking="") |
| 334 | |
| 335 | result = buy_label(objects_root, shipment_id="shp-1", tracking_number="NO-PDF") |
| 336 | assert result["ok"] and result["label_file_id"] == "" |
| 337 | assert read(data_dir)["tracking_number"] == "NO-PDF" |
| 338 | |
| 339 | |
| 340 | def test_a_return_label_is_the_same_verb_against_an_inbound_shipment( |
| 341 | tmp_path, monkeypatch): |
| 342 | """No action_buy_return_label: a return label is the same purchase with |
| 343 | the addresses reversed, and a second verb is a second place to drift.""" |
| 344 | data_dir, objects_root = shop(tmp_path, monkeypatch, provider="manual") |
| 345 | shipment(data_dir, "rma-1", direction="inbound", status="authorized", |
| 346 | tracking="", shipped_on="") |
| 347 | |
| 348 | result = buy_label(objects_root, shipment_id="rma-1", |
| 349 | tracking_number="RETURN-7", label_base64=LABEL) |
| 350 | assert result["ok"] |
| 351 | assert result["direction"] == "inbound" |
| 352 | assert result["kind"] == "return label" |
| 353 | assert read(data_dir, "rma-1")["tracking_number"] == "RETURN-7" |
| 354 | |
| 355 | |
| 356 | def test_the_manual_carrier_never_pretends_to_have_tracked_anything( |
| 357 | tmp_path, monkeypatch): |
| 358 | """A poll that "succeeded" every hour by writing back the status a human |
| 359 | typed would burn tracking_checked_at into a timestamp meaning nothing.""" |
| 360 | data_dir, objects_root = shop(tmp_path, monkeypatch, provider="manual") |
| 361 | shipment(data_dir) |
| 362 | |
| 363 | result = poll(objects_root) |
| 364 | assert result["provider"] == "manual" |
| 365 | assert result["considered"] == 1 |
| 366 | assert result["declined"] == 1 and result["polled"] == 0 |
| 367 | assert read(data_dir)["tracking_attempts"] in ("", "0") |
| 368 | assert read(data_dir)["tracking_checked_at"] == "" |
| 369 | |
| 370 | |
| 371 | # --- a real carrier, plugged in ------------------------------------------------------ |
| 372 | |
| 373 | def test_the_poll_marks_delivered_and_the_order_follows(tmp_path, monkeypatch): |
| 374 | """The one derived move this pass makes, and the reason it is allowed to |
| 375 | make it: the carrier just reported the fact. Everything after the stamp |
| 376 | is system_order_fulfillment's already-tested job.""" |
| 377 | data_dir, objects_root = shop(tmp_path, monkeypatch, provider="fakeco") |
| 378 | shipment(data_dir, status="in_transit") |
| 379 | install_carrier(tmp_path, monkeypatch, |
| 380 | '{"ok": True, "status": "Delivered, front porch", ' |
| 381 | '"delivered": True, "delivered_on": "2026-07-24"}') |
| 382 | # The order is already `shipped` off the handover, the way the ladder |
| 383 | # runs in life: this pass is only ever the last rung. |
| 384 | assert fulfil(objects_root, "shp-1")["order_status"] == "shipped" |
| 385 | |
| 386 | result = poll(objects_root) |
| 387 | assert result["polled"] == 1 and result["delivered"] == 1 |
| 388 | |
| 389 | row = read(data_dir) |
| 390 | assert row["status"] == "delivered" |
| 391 | assert row["delivered_on"] == "2026-07-24" |
| 392 | assert row["tracking_status"] == "Delivered, front porch" |
| 393 | assert row["tracking_checked_at"] |
| 394 | assert row["tracking_attempts"] == "0" |
| 395 | |
| 396 | # The write fires the change dispatcher in production; here we call the |
| 397 | # handler with the payload it would receive. |
| 398 | assert fulfil(objects_root, "shp-1")["order_status"] == "delivered" |
| 399 | assert object_records.get_collection_record( |
| 400 | "orders", "ord-1", base_dir=data_dir)["status"] == "delivered" |
| 401 | |
| 402 | |
| 403 | def test_a_replayed_poll_is_idempotent(tmp_path, monkeypatch): |
| 404 | """Delivered is terminal, so the second pass has nothing in flight to |
| 405 | ask about -- and the delivery date the carrier gave is not rewritten by |
| 406 | a later run that would have used today's.""" |
| 407 | data_dir, objects_root = shop(tmp_path, monkeypatch, provider="fakeco") |
| 408 | shipment(data_dir, status="in_transit") |
| 409 | install_carrier(tmp_path, monkeypatch, |
| 410 | '{"ok": True, "status": "Delivered", "delivered": True, ' |
| 411 | '"delivered_on": "2026-07-24"}') |
| 412 | |
| 413 | fulfil(objects_root, "shp-1") # the order is `shipped` |
| 414 | assert poll(objects_root)["delivered"] == 1 |
| 415 | fulfil(objects_root, "shp-1") |
| 416 | settled = read(data_dir) |
| 417 | |
| 418 | again = poll(objects_root) |
| 419 | fulfil(objects_root, "shp-1") |
| 420 | assert again["considered"] == 0 and again["delivered"] == 0 |
| 421 | # Not "nearly the same": the row is untouched, tracking_checked_at |
| 422 | # included, because a delivered parcel was never asked about again. |
| 423 | assert read(data_dir) == settled |
| 424 | assert settled["delivered_on"] == "2026-07-24" |
| 425 | assert object_records.get_collection_record( |
| 426 | "orders", "ord-1", base_dir=data_dir)["status"] == "delivered" |
| 427 | |
| 428 | |
| 429 | def test_a_parcel_still_moving_keeps_its_status_and_gains_the_carriers_words( |
| 430 | tmp_path, monkeypatch): |
| 431 | data_dir, objects_root = shop(tmp_path, monkeypatch, provider="fakeco") |
| 432 | shipment(data_dir, status="shipped") |
| 433 | install_carrier(tmp_path, monkeypatch, |
| 434 | '{"ok": True, "status": "In transit, Memphis TN", ' |
| 435 | '"delivered": False}') |
| 436 | |
| 437 | assert poll(objects_root)["delivered"] == 0 |
| 438 | row = read(data_dir) |
| 439 | assert row["status"] == "shipped" # ours is not theirs to set |
| 440 | assert row["tracking_status"] == "In transit, Memphis TN" |
| 441 | |
| 442 | |
| 443 | def test_a_shipment_that_keeps_failing_stops_being_polled_and_becomes_visible( |
| 444 | tmp_path, monkeypatch): |
| 445 | """Churning a metered carrier API forever against a mistyped tracking |
| 446 | number is how a queue silently spends money.""" |
| 447 | data_dir, objects_root = shop(tmp_path, monkeypatch, provider="fakeco") |
| 448 | shipment(data_dir, status="in_transit") |
| 449 | install_carrier(tmp_path, monkeypatch, |
| 450 | '{"ok": False, "error": "unknown tracking number"}') |
| 451 | |
| 452 | for expected in (1, 2, 3): |
| 453 | result = poll(objects_root) |
| 454 | assert result["failed"] == 1 |
| 455 | assert read(data_dir)["tracking_attempts"] == str(expected) |
| 456 | |
| 457 | row = read(data_dir) |
| 458 | assert row["tracking_error"] == "unknown tracking number" |
| 459 | assert row["status"] == "in_transit" # the parcel is not cancelled |
| 460 | |
| 461 | quiet = poll(objects_root) |
| 462 | assert quiet["considered"] == 0 and quiet["failed"] == 0 |
| 463 | assert quiet["needing_a_human"] == ["shp-1"] |
| 464 | |
| 465 | |
| 466 | def test_a_permanent_refusal_retires_a_parcel_at_once(tmp_path, monkeypatch): |
| 467 | """Three polite retries against a typo is three more chances to be wrong |
| 468 | slowly.""" |
| 469 | data_dir, objects_root = shop(tmp_path, monkeypatch, provider="fakeco") |
| 470 | shipment(data_dir, status="in_transit") |
| 471 | install_carrier(tmp_path, monkeypatch, |
| 472 | '{"ok": False, "permanent": True, ' |
| 473 | '"error": "no such tracking number, and there never was"}') |
| 474 | |
| 475 | assert poll(objects_root)["failed"] == 1 |
| 476 | assert read(data_dir)["tracking_attempts"] == "3" |
| 477 | assert poll(objects_root)["needing_a_human"] == ["shp-1"] |
| 478 | |
| 479 | |
| 480 | def test_a_carrier_that_raises_costs_one_attempt_and_not_the_pass( |
| 481 | tmp_path, monkeypatch): |
| 482 | data_dir, objects_root = shop(tmp_path, monkeypatch, provider="fakeco") |
| 483 | shipment(data_dir, "shp-1", status="in_transit") |
| 484 | shipment(data_dir, "shp-2", status="in_transit", tracking="TRK-2") |
| 485 | install_carrier(tmp_path, monkeypatch, '1 / 0') |
| 486 | |
| 487 | result = poll(objects_root) |
| 488 | assert result["failed"] == 2 # both asked, neither lost |
| 489 | assert "raised" in read(data_dir, "shp-2")["tracking_error"] |
| 490 | |
| 491 | |
| 492 | def test_a_connector_answering_to_another_name_is_never_used( |
| 493 | tmp_path, monkeypatch): |
| 494 | """Quietly shipping with a carrier the shop did not configure is worse |
| 495 | than a pass that did nothing and said so.""" |
| 496 | data_dir, objects_root = shop(tmp_path, monkeypatch, provider="fakeco") |
| 497 | shipment(data_dir, status="in_transit") |
| 498 | # app-shipping's own manual connector is the one installed, and it |
| 499 | # answers to "manual". |
| 500 | result = poll(objects_root) |
| 501 | assert result["polled"] == 0 |
| 502 | assert "'manual'" in result["skipped"] and "'fakeco'" in result["skipped"] |
| 503 | assert read(data_dir)["tracking_attempts"] in ("", "0") |
| 504 | |
| 505 | refused = buy_label(objects_root, shipment_id="shp-1", tracking_number="X") |
| 506 | assert refused["status"] == 409 |
| 507 | assert "manual" in refused["error"] |
| 508 | |
| 509 | |
| 510 | def test_a_provider_nobody_installed_is_a_decline_not_a_failure( |
| 511 | tmp_path, monkeypatch): |
| 512 | data_dir, objects_root = shop(tmp_path, monkeypatch, provider="fakeco") |
| 513 | shipment(data_dir, status="in_transit") |
| 514 | monkeypatch.setenv("DBBASIC_PACKAGES_DIR", str(tmp_path / "no-packages")) |
| 515 | |
| 516 | result = poll(objects_root) |
| 517 | assert result["polled"] == 0 |
| 518 | assert "declares a connector" in result["skipped"] |
| 519 | assert read(data_dir)["tracking_attempts"] in ("", "0") |
| 520 | |
| 521 | |
| 522 | def test_only_outbound_parcels_with_a_number_are_ever_asked_about( |
| 523 | tmp_path, monkeypatch): |
| 524 | """An inbound RMA's `received` means a human has the box and has looked |
| 525 | at it; a carrier saying delivered is not that fact. A parcel with no |
| 526 | tracking number is not failing, it simply cannot be asked about.""" |
| 527 | data_dir, objects_root = shop(tmp_path, monkeypatch, provider="fakeco") |
| 528 | shipment(data_dir, "rma-1", direction="inbound", status="in_transit", |
| 529 | tracking="RET-1", shipped_on="") |
| 530 | shipment(data_dir, "shp-blank", status="shipped", tracking="") |
| 531 | shipment(data_dir, "shp-done", status="delivered") |
| 532 | shipment(data_dir, "shp-live", status="in_transit", tracking="TRK-LIVE") |
| 533 | install_carrier(tmp_path, monkeypatch, |
| 534 | '{"ok": True, "status": "Moving", "delivered": False}') |
| 535 | |
| 536 | result = poll(objects_root) |
| 537 | assert result["considered"] == 1 |
| 538 | assert [entry["shipment"] for entry in result["results"]] == ["shp-live"] |
| 539 | assert read(data_dir, "rma-1")["tracking_status"] == "" |
| 540 | |
| 541 | |
| 542 | # --- the connector declaration itself ------------------------------------------------ |
| 543 | |
| 544 | def test_the_declared_reconcile_entry_declines_so_the_daemon_writes_nothing(): |
| 545 | """app-shipping declares a connector for shipments so the module is |
| 546 | discoverable by the mechanism that already resolves connector modules |
| 547 | safely. The daemon's desired-state pass therefore calls `reconcile` |
| 548 | against every shipment on the box, and it must never converge anything: |
| 549 | we cannot make a van arrive by wishing, and a skip leaves the row |
| 550 | untouched and uncounted.""" |
| 551 | declaration = next(entry for entry in object_packages.iter_connectors(root=PACKAGES) |
| 552 | if entry["collection"] == "shipments") |
| 553 | assert declaration["package_id"] == "app-shipping" |
| 554 | reconcile = object_connectors.load_connector(declaration["module"], |
| 555 | declaration["entry"]) |
| 556 | outcome = reconcile({"id": "shp-1"}, base_dir="data") |
| 557 | assert set(outcome) == {"skip", "reason"} and outcome["skip"] is True |
| 558 | assert "system_tracking_poll" in outcome["reason"] |
| 559 | |
| 560 | |
| 561 | # --- the parcel that stopped moving ---------------------------------------------------- |
| 562 | |
| 563 | def days_ago(count): |
| 564 | return (date.today() - timedelta(days=count)).isoformat() |
| 565 | |
| 566 | |
| 567 | def test_the_stuck_count_keys_on_in_transit_and_on_age(tmp_path, monkeypatch): |
| 568 | """`shipped` is every parcel forever in a manual shop, and a band that |
| 569 | is permanently lit is a band nobody reads.""" |
| 570 | data_dir, objects_root = shop(tmp_path, monkeypatch) |
| 571 | shipment(data_dir, "old-transit", status="in_transit", shipped_on=days_ago(24)) |
| 572 | shipment(data_dir, "new-transit", status="in_transit", shipped_on=days_ago(2)) |
| 573 | shipment(data_dir, "old-shipped", status="shipped", shipped_on=days_ago(30)) |
| 574 | shipment(data_dir, "old-delivered", status="delivered", shipped_on=days_ago(30)) |
| 575 | shipment(data_dir, "no-date", status="in_transit", shipped_on="") |
| 576 | shipment(data_dir, "inbound", direction="inbound", status="in_transit", |
| 577 | shipped_on=days_ago(30)) |
| 578 | |
| 579 | result = attention(objects_root) |
| 580 | assert result["count"] == 1 |
| 581 | assert result["detail"] == "oldest 24 days out" |
| 582 | |
| 583 | |
| 584 | def test_the_stuck_threshold_is_a_setting(tmp_path, monkeypatch): |
| 585 | data_dir, objects_root = shop(tmp_path, monkeypatch, stuck_days="3") |
| 586 | shipment(data_dir, "four-days", status="in_transit", shipped_on=days_ago(4)) |
| 587 | assert attention(objects_root)["count"] == 1 |
| 588 | |
| 589 | data_dir, objects_root = shop(tmp_path / "b", monkeypatch, stuck_days="30") |
| 590 | shipment(data_dir, "four-days", status="in_transit", shipped_on=days_ago(4)) |
| 591 | assert attention(objects_root)["count"] == 0 |
| 592 | |
| 593 | |
| 594 | def test_the_count_is_zero_where_shipping_is_not_installed(tmp_path, monkeypatch): |
| 595 | """The pass runs every few minutes on every box; an app nobody installed |
| 596 | must not log an error each time.""" |
| 597 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "empty")) |
| 598 | objects_root = tmp_path / "objects" |
| 599 | shutil.copytree(SHIPPING / "objects", objects_root, dirs_exist_ok=True) |
| 600 | assert attention(objects_root) == {"count": 0} |
| 601 | |
| 602 | |
| 603 | # --- what the manifest declares ---------------------------------------------------------- |
| 604 | |
| 605 | def test_the_poll_is_declared_hourly_and_the_count_opens_a_real_index(): |
| 606 | package = object_packages.get_package("app-shipping", root=PACKAGES) |
| 607 | schedule = next(entry for entry in package["schedules"] |
| 608 | if entry["object_id"] == "system_tracking_poll") |
| 609 | assert schedule["schedule"].endswith("* * * *") # hourly |
| 610 | assert schedule["method"] == "POST" |
| 611 | assert "hourly" in schedule["description"].lower() |
| 612 | |
| 613 | source = package["attention"][0] |
| 614 | assert source["object_id"] == "system_shipment_attention" |
| 615 | assert source["severity"] == "warning" |
| 616 | assert source["path"] == "/shipments" # no query string |
| 617 | assert source["nav_id"] == "shipments" |
| 618 | |
| 619 | # The page the count opens lists the collection the count counted. |
| 620 | view = next(row for row in _seed_rows("views") if row["id"] == "view_shipments_index") |
| 621 | block = json.loads(view["blocks"])[0] |
| 622 | assert block["kind"] == "list" and block["collection"] == "shipments" |
| 623 | assert block["where"] == {"direction": "outbound"} |
| 624 | |
| 625 | |
| 626 | def _seed_rows(name): |
| 627 | import csv |
| 628 | with open(SHIPPING / "seed" / f"{name}.tsv", newline="") as handle: |
| 629 | return list(csv.DictReader(handle, delimiter="\t")) |