Files
praxis/tests/test_pg_store.py
T
Praxis CI 00e39a3f85 feat(milestone): merge phase/01 operator-foundation → milestone/v0.4-operator-tier
Phase 1 complete — Operator Foundation:
- Postgres 16 in Docker-in-LXC (asyncpg pool, 5-table schema, PgStore, migrations)
- Operator auth (argon2id, signed stateless cookies, slowapi 5/min rate limit)
- VC issuer key migration SQLite→Postgres (archive-before-active, R-VC-MIG-01)
- Operator bootstrap CLI (create-operator.py, idempotent)
- Backup cron script + G-008 restore drill
- Graceful degradation (server starts without Postgres)
- 272 tests pass, 33 skip (Postgres-requiring), 0 fail

---ci---
project: praxis
phase: 1
milestone: v0.4
status: complete
requirements:
  covered: [REQ-MT-01, REQ-AUTH-01, REQ-NFR-AUTH-01, REQ-NFR-MT-01, REQ-MT-02]
  partial: []
---/ci---
2026-08-04 01:41:06 +00:00

221 lines
7.1 KiB
Python

"""PgStore + asyncpg pool integration test (TASK-01-07).
Requires a live Postgres instance. Skips gracefully when PRAXIS_PG_DSN is
unset so the test suite has no hard CI dependency on Postgres.
"""
from __future__ import annotations
import os
import uuid
from datetime import date
import asyncpg
import pytest
from db.pg_migrate import apply_pg_migrations
from db.pg_store import PgStore
pytestmark = pytest.mark.skipif(
"PRAXIS_PG_DSN" not in os.environ,
reason="PRAXIS_PG_DSN not set — Postgres integration tests skipped (dev mode).",
)
@pytest.fixture(scope="module")
async def pool() -> asyncpg.Pool:
p = await asyncpg.create_pool(
dsn=os.environ["PRAXIS_PG_DSN"],
min_size=1,
max_size=5,
command_timeout=10,
)
try:
await apply_pg_migrations(p)
yield p
finally:
await p.close()
@pytest.fixture(autouse=True)
async def _clean_tables(pool: asyncpg.Pool):
async with pool.acquire() as conn:
await conn.execute(
"TRUNCATE operators, issued_credentials, mastery_gate_events, "
"cohort_aggregates, issuer_keys RESTART IDENTITY CASCADE"
)
yield
@pytest.mark.asyncio
async def test_migration_creates_tables(pool: asyncpg.Pool):
async with pool.acquire() as conn:
tables = await conn.fetch(
"SELECT tablename FROM pg_tables WHERE schemaname = 'public' "
"ORDER BY tablename"
)
names = {r["tablename"] for r in tables}
assert {"operators", "issued_credentials", "mastery_gate_events",
"cohort_aggregates", "issuer_keys"}.issubset(names)
@pytest.mark.asyncio
async def test_migration_idempotent(pool: asyncpg.Pool):
applied = await apply_pg_migrations(pool)
assert applied == []
@pytest.mark.asyncio
async def test_operator_insert_and_lookup(pool: asyncpg.Pool):
store = PgStore(pool)
oid = await store.insert_operator(
"alice", "$argon2id$fakehash", "Alice"
)
assert oid is not None
op = await store.get_operator_by_username("alice")
assert op is not None
assert op["username"] == "alice"
assert op["display_name"] == "Alice"
assert op["is_active"] is True
by_id = await store.get_operator_by_id(oid)
assert by_id is not None
assert by_id["id"] == op["id"]
@pytest.mark.asyncio
async def test_operator_insert_idempotent(pool: asyncpg.Pool):
store = PgStore(pool)
first = await store.insert_operator("bob", "$argon2id$h1", "Bob")
assert first is not None
second = await store.insert_operator("bob", "$argon2id$h2", "Bob")
assert second is None
@pytest.mark.asyncio
async def test_operator_on_conflict_update(pool: asyncpg.Pool):
store = PgStore(pool)
await store.insert_operator("carol", "$argon2id$old", "Carol")
updated = await store.insert_operator(
"carol", "$argon2id$new", "Carol", on_conflict_update=True
)
assert updated is not None
op = await store.get_operator_by_username("carol")
assert op["password_hash"] == "$argon2id$new"
@pytest.mark.asyncio
async def test_update_last_login(pool: asyncpg.Pool):
store = PgStore(pool)
oid = await store.insert_operator("dave", "$argon2id$h", "Dave")
assert oid is not None
assert (await store.get_operator_by_id(oid))["last_login_at"] is None
await store.update_last_login(oid)
assert (await store.get_operator_by_id(oid))["last_login_at"] is not None
@pytest.mark.asyncio
async def test_cohort_aggregate_upsert_idempotent(pool: asyncpg.Pool):
store = PgStore(pool)
ws, we = date(2026, 8, 1), date(2026, 8, 7)
await store.upsert_cohort_aggregate(
"cs-refund", "sessions_count", ws, we, 42.0, 15, False
)
await store.upsert_cohort_aggregate(
"cs-refund", "sessions_count", ws, we, 42.0, 15, False
)
rows = await store.get_cohort_aggregates(
"cs-refund", "sessions_count", date(2026, 7, 1)
)
assert len(rows) == 1
assert rows[0]["value"] == 42.0
assert rows[0]["cell_count"] == 15
@pytest.mark.asyncio
async def test_cohort_aggregate_suppressed_cell(pool: asyncpg.Pool):
store = PgStore(pool)
ws, we = date(2026, 8, 1), date(2026, 8, 7)
await store.upsert_cohort_aggregate(
"cs-refund", "active_learners", ws, we, None, 9, True
)
rows = await store.get_cohort_aggregates(
"cs-refund", "active_learners", date(2026, 7, 1)
)
assert len(rows) == 1
assert rows[0]["cell_suppressed"] is True
assert rows[0]["value"] is None
@pytest.mark.asyncio
async def test_issuer_key_init_active_then_superseded(pool: asyncpg.Pool):
store = PgStore(pool)
kid = f"key-{uuid.uuid4().hex[:12]}"
await store.init_issuer_key(kid, "pub-b64-aaa", b"\x01\x02\x03")
active = await store.get_active_signing_key_row()
assert active is not None
assert active["id"] == kid
assert active["status"] == "active"
await store.set_issuer_key_superseded(kid)
assert await store.get_active_signing_key_row() is None
archived = await store.get_public_key_row(kid)
assert archived is not None
assert archived["status"] == "superseded"
assert archived["public_key"] == "pub-b64-aaa"
@pytest.mark.asyncio
async def test_get_public_key_row_finds_superseded(pool: asyncpg.Pool):
store = PgStore(pool)
kid = f"key-{uuid.uuid4().hex[:12]}"
await store.init_issuer_key(kid, "pub-b64-bbb", b"\x04\x05")
await store.set_issuer_key_superseded(kid)
row = await store.get_public_key_row(kid)
assert row is not None
assert row["status"] == "superseded"
@pytest.mark.asyncio
async def test_credential_insert_and_get(pool: asyncpg.Pool):
store = PgStore(pool)
oid = await store.insert_operator("ed", "$argon2id$h", "Ed")
cid = f"vc-{uuid.uuid4().hex[:16]}"
await store.insert_credential(
cid, "learner-1", '{"id":"vc-x"}', "sig-b64",
operator_id=oid,
)
row = await store.get_credential(cid)
assert row is not None
assert row["id"] == cid
assert row["learner_ref"] == "learner-1"
assert row["signature_b64"] == "sig-b64"
assert row["status"] == "active"
assert row["vc_payload_json"] == '{"id":"vc-x"}'
@pytest.mark.asyncio
async def test_credential_status_revoke(pool: asyncpg.Pool):
store = PgStore(pool)
cid = f"vc-{uuid.uuid4().hex[:16]}"
await store.insert_credential(cid, "learner-2", "{}", "sig")
await store.set_credential_status(cid, "revoked")
row = await store.get_credential(cid)
assert row["status"] == "revoked"
assert row["revoked_at"] is not None
@pytest.mark.asyncio
async def test_record_gate_event(pool: asyncpg.Pool):
store = PgStore(pool)
eid = await store.record_gate_event(
"learner-3", "cs-refund", scenario_id="sc-1",
gate_outcome="open", rubric_scores_jsonb=[{"c": "x", "l": 4}],
)
assert eid is not None
async with pool.acquire() as conn:
row = await conn.fetchrow(
"SELECT * FROM mastery_gate_events WHERE id = $1", eid
)
assert row is not None
assert row["learner_ref"] == "learner-3"
assert row["gate_outcome"] == "open"
assert row["source"] == "sync"