procurement-ingest/lambdas/wo/email_processor/tests/test_healthcheck.py
Adam Moussa cb5539bd68
Some checks are pending
Deploy / deploy (push) Waiting to run
feat: deploy-pipeline guards — healthcheck, smoke gate, bundle glob + AST test (refactor phase 0) (#107)
* feat: deploy-pipeline guards — healthcheck, smoke gate, bundle glob + AST test (refactor phase 0)

Deploys of po-email-processor and workorder-email-processor had no
verification step, so an init-time ImportError in the bundled zip
could ship silently and only surface on the next real S3 event. This
adds a synchronous post-deploy smoke gate wired into the deploy
workflow: both Lambdas are invoked with {"healthcheck": true} and the
FunctionError field is checked, since an Unhandled init error still
returns HTTP 200 on RequestResponse invokes and would false-pass a
plain exit-code check.

The healthcheck branch is the first statement in each handler, before
any boto3/S3 use or ses_auth, and only fires on a top-level direct
invoke ("healthcheck" is not a key AWS ever sets on a real S3
ObjectCreated event, so mail content can't reach this path). It emits
no EMF metrics and no log text that could match the
sender-auth-rejected metric filter, so two deploys in one window
won't trip the alarm.

Separately, the PO stack's asset bundling copied a hand-maintained
four-file allowlist into the zip, so every new sibling module
handler.py imports had to be added by hand or the deploy shipped a
Lambda that ImportErrors at cold start (bit us for template_parser in
PR #105 and nearly for derived_fields in PR #2). Replaced it with a
non-recursive ./*.py glob so top-level source files ship
automatically while tests/ and the stale package/ dir still cannot,
and added an AST-based bundle-consistency test that parses each
handler's first-party imports and fails CI if the bundling command
would omit any of them (a revert to an incomplete allowlist, or code
moved into a subdirectory the glob doesn't cover).

Includes the refactor-evaluation report that scoped this phase.

* fix: review nits — unambiguous bundling-command extraction, smoke payload-parse message, dead asserts

- tests/test_bundle_consistency.py: _extract_bundling_command now collects
  all command=[...] matches and demands exactly one per stack file, instead
  of silently returning whichever ast.walk visits first if a second bundled
  function is ever added.
- scripts/post-deploy-smoke.sh: distinguish an unparseable response payload
  from a payload mismatch so the failure message says what actually happened
  (the previous "could not parse" branch was unreachable — the inline python
  always exited 0).
- test_po_healthcheck.py: drop the substring assertions on stdout that were
  dead behind the stricter `captured.out == ""` assertion; keep the stderr
  filter-pattern check.

Review follow-up on PR #107; no behavior change to any shipped code path.
2026-07-17 13:18:45 -04:00

69 lines
2.6 KiB
Python

"""Deploy-guard healthcheck branch (Phase 0).
The handler must answer a top-level direct-invoke ``{"healthcheck": true}``
probe immediately -- BEFORE any S3 fetch, SES sender-auth gate, or Records
iteration -- and must do so without touching AWS or emitting any telemetry
that could trip the ``sender_auth_rejected`` metric-filter alarm.
These tests import the WO ``handler`` via the ``_wo_parser_support`` sys.path
loader idiom (region + module dir set on import); no fake_dynamo/S3 wiring is
needed because a correct healthcheck returns before any client is used.
"""
import handler
from _wo_parser_support import FakeDynamoResource
class _ExplodingS3:
"""Any attribute access is a test failure: the healthcheck branch must
return before the handler ever reaches the S3 client."""
def get_object(self, *a, **k): # noqa: N803
raise AssertionError("healthcheck branch touched S3")
def test_healthcheck_returns_ok():
assert handler.handler({"healthcheck": True}, None) == {"healthcheck": "ok"}
def test_healthcheck_precedes_s3_and_auth(monkeypatch):
# If the early-return were missing or misplaced, the handler would call
# s3.get_object / authenticate_inbound_email; both are booby-trapped.
monkeypatch.setattr(handler, "s3", _ExplodingS3())
monkeypatch.setattr(handler, "dynamodb", FakeDynamoResource())
def _boom_auth(*a, **k):
raise AssertionError("healthcheck branch reached SES auth")
monkeypatch.setattr(handler, "authenticate_inbound_email", _boom_auth)
assert handler.handler({"healthcheck": True}, None) == {"healthcheck": "ok"}
def test_healthcheck_emits_no_metric(monkeypatch):
# No EMF / ParseOutcome emission on the healthcheck path.
def _boom_metric(*a, **k):
raise AssertionError("healthcheck branch emitted a metric")
monkeypatch.setattr(handler, "emit_parse_metric", _boom_metric)
assert handler.handler({"healthcheck": True}, None) == {"healthcheck": "ok"}
def test_healthcheck_only_on_literal_true():
# A truthy-but-not-True value must NOT trigger the branch: it falls through
# to the (empty) Records loop and returns the normal 200 envelope. This
# keeps the trigger to the exact direct-invoke contract.
assert handler.handler({"healthcheck": "yes"}, None) == {
"statusCode": 200,
"body": "OK",
}
def test_records_event_ignores_healthcheck_lookalike():
# A real S3 event shape has no top-level healthcheck key; an empty Records
# list is processed normally without hitting the early return.
assert handler.handler({"Records": []}, None) == {
"statusCode": 200,
"body": "OK",
}