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