canned-prompts/service/tests/test_health.py
tegwick ae52931be5 CANP-WP-0006 T01-T02: service skeleton and tenant-keyed schema
The foundation of the hosted registry, in canned-prompts so rapp.yaml gets
ownership_repo: canned-prompts — the sbom-nexus shape, where product ownership
stays out of the operations repo.

Stack matches state-hub and sbom-nexus: FastAPI, SQLAlchemy, Alembic,
PostgreSQL, in service/ with its own environment. reference/ is deliberately
untouched: it is the format's conformance witness and stays dependency-light,
and the service is a separate consumer of the same package semantics.

CANNED_PROMPTS_DATABASE_URL has no default. A service that silently falls back
to a local database when its real one is misconfigured is worse than one that
refuses to start.

Health surface per RailianceAppDeploymentGuide.md: unauthenticated /healthz and
/readyz, plus /state/health for fleet consistency. /healthz deliberately checks
nothing beyond the process being up, so a database blip does not restart pods;
/readyz asks the database something it can fail to answer.

Migration 0001 creates package_versions, package_files and index_entries, every
one carrying a tenant key per business-app-service-contract section 1.3 — the
service is single-tenant today, and the key is present so a later consolidation
is a data copy rather than a rewrite. A test asserts every table in the metadata
is tenant-keyed, so adding an unkeyed table fails the suite rather than being
discovered at consolidation time. Uniqueness is (tenant, registry, package_id,
version): registry-scoped because identity is, tenant-scoped so two tenants may
hold the same id.

The schema keeps the format's three things distinct — an immutable package
version, its files as content rather than parsed rows, and an index entry
recording how a version arrived here.

Fixes a bug its own test caught: check_readiness first caught every failure in
one except and reported "database unreachable", so an unmigrated but perfectly
reachable database sent an operator to credentials and networking when the fix
was alembic upgrade. Connectivity and schema are now checked separately.

Service tests 11 passing; reference tests unaffected at 99.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Bjefh8NUiEiahN4JLwoSKM

Assistant: claude-code
Assistant-Model: opus
Assistant-Process: 388925@bnt-lap001
Assistant-Session: 3507023f-e0fd-4a1e-9d90-a0d4217d1502
2026-09-06 19:57:47 +02:00

94 lines
3.3 KiB
Python

"""Health surface.
The point of these tests is the negative cases. An endpoint that returns 200
under every condition tells an orchestrator nothing, and the failure is silent
exactly when it matters.
"""
from __future__ import annotations
from pathlib import Path
import pytest
from alembic import command
from alembic.config import Config
from fastapi.testclient import TestClient
from canned_prompts_service.api import create_app
from canned_prompts_service.db import check_readiness, make_engine
from canned_prompts_service.settings import Settings
ROOT = Path(__file__).resolve().parents[1]
def migrated_url(tmp_path: Path) -> str:
url = f"sqlite:///{tmp_path / 'svc.db'}"
config = Config(str(ROOT / "alembic.ini"))
config.set_main_option("script_location", str(ROOT / "migrations"))
config.set_main_option("sqlalchemy.url", url)
command.upgrade(config, "head")
return url
@pytest.fixture()
def ready_client(tmp_path: Path) -> TestClient:
url = migrated_url(tmp_path)
return TestClient(create_app(Settings(database_url=url), make_engine(url)))
def test_healthz_is_up_without_a_database() -> None:
"""Liveness must not depend on the database, or a DB blip restarts pods."""
client = TestClient(create_app(Settings(), None))
assert client.get("/healthz").json() == {"status": "ok"}
def test_readyz_fails_without_a_database() -> None:
client = TestClient(create_app(Settings(), None))
response = client.get("/readyz")
assert response.status_code == 503
assert response.json()["ready"] is False
assert "no database" in response.json()["detail"]
def test_readyz_fails_when_the_database_is_unreachable(tmp_path: Path) -> None:
engine = make_engine("sqlite:////nonexistent/dir/does-not-exist.db")
client = TestClient(create_app(Settings(database_url="x"), engine))
response = client.get("/readyz")
assert response.status_code == 503
assert response.json()["ready"] is False
def test_readyz_fails_when_the_schema_is_not_migrated(tmp_path: Path) -> None:
"""Reachable but unmigrated is not ready — it would 500 on the first query."""
engine = make_engine(f"sqlite:///{tmp_path / 'empty.db'}")
client = TestClient(create_app(Settings(database_url="x"), engine))
response = client.get("/readyz")
assert response.status_code == 503
assert response.json()["detail"] == "schema not migrated"
def test_readyz_reports_the_migration_when_ready(ready_client: TestClient) -> None:
body = ready_client.get("/readyz").json()
assert body["ready"] is True
assert body["migration"] == "0001"
def test_state_health_matches_the_fleet_shape(ready_client: TestClient) -> None:
body = ready_client.get("/state/health").json()
assert body["status"] == "ok"
assert body["service"] == "canned-prompts"
assert body["db"] == "connected"
assert body["migration"] == "0001"
def test_state_health_degrades_rather_than_lying() -> None:
client = TestClient(create_app(Settings(), None))
response = client.get("/state/health")
assert response.status_code == 503
assert response.json()["status"] == "degraded"
def test_settings_have_no_database_fallback() -> None:
"""Falling back to a local database when misconfigured hides the mistake."""
assert Settings().database_url == ""
assert Settings().configured is False