Server: basic implementation. Not tested => no python installed; bugfix in ESP (uvicorn on port 8090)
This commit is contained in:
1 parent
3694cdf207
commit
8a51e3d95e
38 files changed
+2442
-21
No files matched your search
@@ -0,0 +1,40 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
# Set before anything imports poorbird.config, whose Settings are cached.
|
||||
os.environ.setdefault("POORBIRD_LOG_LEVEL", "WARNING")
|
||||
os.environ.setdefault("POORBIRD_IMAGE_ROOT", "/tmp/poorbird-test/images")
|
||||
os.environ.setdefault("POORBIRD_THUMB_ROOT", "/tmp/poorbird-test/thumbs")
|
||||
os.environ.setdefault("POORBIRD_STATE_DIR", "/tmp/poorbird-test/state")
|
||||
|
||||
|
||||
def database_is_reachable() -> bool:
|
||||
try:
|
||||
from sqlalchemy import text
|
||||
|
||||
from poorbird.db import engine
|
||||
|
||||
with engine.connect() as conn:
|
||||
conn.execute(text("SELECT 1"))
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
needs_db = pytest.mark.skipif(
|
||||
not database_is_reachable(),
|
||||
reason="no reachable PostgreSQL (set POORBIRD_DATABASE_URL)",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def client():
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from poorbird.api.app import create_app
|
||||
|
||||
with TestClient(create_app()) as c:
|
||||
yield c
|
||||
@@ -0,0 +1,30 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from poorbird.config import Settings
|
||||
|
||||
|
||||
def test_every_setting_reads_from_the_environment(monkeypatch):
|
||||
"""Phase 1.2: no path, host or secret may be baked into code."""
|
||||
monkeypatch.setenv("POORBIRD_DATABASE_URL", "postgresql+psycopg://u:p@10.0.0.5:5432/db")
|
||||
monkeypatch.setenv("POORBIRD_IMAGE_ROOT", "/mnt/elsewhere/images")
|
||||
monkeypatch.setenv("POORBIRD_API_PORT", "9999")
|
||||
monkeypatch.setenv("POORBIRD_ENROLL_SECRET", "deadbeef")
|
||||
|
||||
s = Settings(_env_file=None)
|
||||
|
||||
assert s.database_url.endswith("@10.0.0.5:5432/db")
|
||||
assert str(s.image_root).endswith("images")
|
||||
assert s.api_port == 9999
|
||||
assert s.enroll_secret_is_set
|
||||
|
||||
|
||||
def test_database_url_is_tcp_not_a_unix_socket():
|
||||
"""A Unix socket is the one genuinely container-hostile choice."""
|
||||
s = Settings(_env_file=None)
|
||||
assert "@" in s.database_url and ":" in s.database_url.rpartition("@")[2]
|
||||
assert "/var/run/postgresql" not in s.database_url
|
||||
|
||||
|
||||
def test_enroll_secret_is_not_leaked_by_repr():
|
||||
s = Settings(_env_file=None, enroll_secret="hunter2")
|
||||
assert "hunter2" not in repr(s)
|
||||
@@ -0,0 +1,30 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from conftest import needs_db
|
||||
|
||||
|
||||
def test_health_answers_even_without_a_database(client):
|
||||
"""The WebUI banner must be able to render a degraded system."""
|
||||
r = client.get("/api/v1/health")
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["status"] in {"ok", "degraded"}
|
||||
assert "database" in body
|
||||
assert "disk" in body
|
||||
assert body["version"]
|
||||
|
||||
|
||||
@needs_db
|
||||
def test_health_is_ok_with_a_database(client):
|
||||
body = client.get("/api/v1/health").json()
|
||||
assert body["status"] == "ok"
|
||||
assert body["database"]["ok"] is True
|
||||
|
||||
|
||||
@needs_db
|
||||
def test_healthz_is_200_when_the_database_is_up(client):
|
||||
assert client.get("/healthz").status_code == 200
|
||||
|
||||
|
||||
def test_openapi_is_served(client):
|
||||
assert client.get("/openapi.json").status_code == 200
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Queue behaviour. Needs a real PostgreSQL: SKIP LOCKED has no equivalent
|
||||
anywhere else, and mocking it would test nothing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from conftest import needs_db
|
||||
|
||||
pytestmark = [pytest.mark.db, needs_db]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def session():
|
||||
from poorbird.db import SessionLocal
|
||||
from poorbird.models import Job
|
||||
|
||||
with SessionLocal() as s:
|
||||
yield s
|
||||
s.query(Job).filter(Job.kind.like("test_%")).delete(synchronize_session=False)
|
||||
s.commit()
|
||||
|
||||
|
||||
def test_claim_returns_a_queued_job_then_nothing(session):
|
||||
from poorbird.worker import queue
|
||||
|
||||
queue.enqueue(session, "test_noop", {"n": 1})
|
||||
session.commit()
|
||||
|
||||
claimed = queue.claim(session)
|
||||
assert claimed is not None
|
||||
assert claimed["kind"] == "test_noop"
|
||||
assert claimed["payload"] == {"n": 1}
|
||||
assert claimed["attempts"] == 1
|
||||
|
||||
queue.complete(session, claimed["id"])
|
||||
|
||||
# Same job must not come back.
|
||||
again = queue.claim(session)
|
||||
assert again is None or again["kind"] != "test_noop"
|
||||
|
||||
|
||||
def test_a_second_worker_skips_a_locked_row_instead_of_blocking(session):
|
||||
"""The whole point of FOR UPDATE SKIP LOCKED."""
|
||||
from poorbird.db import SessionLocal
|
||||
from poorbird.worker import queue
|
||||
|
||||
queue.enqueue(session, "test_only_one")
|
||||
session.commit()
|
||||
|
||||
first = queue.claim(session)
|
||||
assert first is not None
|
||||
|
||||
with SessionLocal() as other:
|
||||
assert queue.claim(other) is None
|
||||
|
||||
queue.complete(session, first["id"])
|
||||
|
||||
|
||||
def test_failure_retries_until_max_attempts_then_parks(session):
|
||||
from poorbird.models import Job
|
||||
from poorbird.worker import queue
|
||||
|
||||
job = queue.enqueue(session, "test_doomed", max_attempts=2)
|
||||
session.commit()
|
||||
job_id = job.id
|
||||
|
||||
for _ in range(2):
|
||||
claimed = queue.claim(session)
|
||||
assert claimed is not None
|
||||
queue.fail(session, claimed["id"], "boom", retry_in_s=0)
|
||||
|
||||
session.expire_all()
|
||||
parked = session.get(Job, job_id)
|
||||
assert parked.status == "failed"
|
||||
assert parked.attempts == 2
|
||||
assert "boom" in parked.last_error
|
||||
|
||||
|
||||
def test_stale_running_jobs_are_reclaimed(session):
|
||||
from sqlalchemy import text
|
||||
|
||||
from poorbird.models import Job
|
||||
from poorbird.worker import queue
|
||||
|
||||
job = queue.enqueue(session, "test_orphan")
|
||||
session.commit()
|
||||
claimed = queue.claim(session)
|
||||
assert claimed is not None
|
||||
|
||||
# Pretend the worker died an hour ago.
|
||||
session.execute(
|
||||
text("UPDATE jobs SET locked_at = now() - interval '1 hour' WHERE id = :id"),
|
||||
{"id": job.id},
|
||||
)
|
||||
session.commit()
|
||||
|
||||
assert queue.requeue_stale(session, older_than_s=60) >= 1
|
||||
session.expire_all()
|
||||
assert session.get(Job, job.id).status == "queued"
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Guard the baseline migration against the models.
|
||||
|
||||
Migration 0001 builds the schema from ``Base.metadata`` (see its docstring).
|
||||
That is only safe if something checks it, so: migrate a scratch database, then
|
||||
ask Alembic to autogenerate against it and assert the diff is empty.
|
||||
|
||||
This test keeps working after 0001 is replaced by explicit DDL, and it is what
|
||||
catches "added a column to the model, forgot the migration" from Phase 2 on.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from conftest import needs_db
|
||||
|
||||
pytestmark = [pytest.mark.db, needs_db]
|
||||
|
||||
|
||||
def test_migrated_schema_matches_the_models():
|
||||
from alembic.autogenerate import compare_metadata
|
||||
from alembic.migration import MigrationContext
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from poorbird.config import get_settings
|
||||
from poorbird.db import engine
|
||||
from poorbird.models import Base
|
||||
|
||||
scratch = "poorbird_schema_check"
|
||||
|
||||
# CREATE DATABASE cannot run inside a transaction block.
|
||||
with engine.connect().execution_options(isolation_level="AUTOCOMMIT") as conn:
|
||||
conn.execute(text(f'DROP DATABASE IF EXISTS "{scratch}"'))
|
||||
conn.execute(text(f'CREATE DATABASE "{scratch}"'))
|
||||
|
||||
url = get_settings().database_url
|
||||
scratch_url = url.rsplit("/", 1)[0] + "/" + scratch
|
||||
scratch_engine = create_engine(scratch_url)
|
||||
|
||||
try:
|
||||
# Apply the real migration chain, exactly as `poorbird migrate` would.
|
||||
with scratch_engine.begin() as conn:
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
|
||||
cfg = Config()
|
||||
cfg.set_main_option(
|
||||
"script_location", str(Path(__file__).resolve().parents[1] / "migrations")
|
||||
)
|
||||
cfg.set_main_option("sqlalchemy.url", scratch_url)
|
||||
cfg.attributes["connection"] = conn
|
||||
command.upgrade(cfg, "head")
|
||||
|
||||
with scratch_engine.connect() as conn:
|
||||
ctx = MigrationContext.configure(
|
||||
conn,
|
||||
opts={"compare_type": True, "compare_server_default": True},
|
||||
)
|
||||
diff = compare_metadata(ctx, Base.metadata)
|
||||
|
||||
# alembic_version is Alembic's own bookkeeping, not part of the models.
|
||||
diff = [d for d in diff if "alembic_version" not in str(d)]
|
||||
assert diff == [], f"schema has drifted from the models:\n{diff}"
|
||||
finally:
|
||||
scratch_engine.dispose()
|
||||
with engine.connect().execution_options(isolation_level="AUTOCOMMIT") as conn:
|
||||
conn.execute(text(f'DROP DATABASE IF EXISTS "{scratch}"'))
|
||||
Reference in new issue
Block a user