chore(backend): DB-backed pytest harness (temp SQLite, real app, per-test rollback)
Platform v2 step 0.5. conftest.py now points DATABASE_URL/LOG_DIR/TLS_DIR at a temp folder before anything imports config, builds the schema once per session, and gives each test a connection-level transaction that is rolled back (app commits become SAVEPOINT releases). Fixtures: db, client (TestClient with get_db overridden, license open, no lifespan), make_user, login. Tests using them are auto-marked `db`, so -m "not db" keeps the quick set. test_harness.py proves login -> /api/auth/me and the rollback. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,10 +1,182 @@
|
||||
"""Fast unit tests for local_backend — no server, no database, no network.
|
||||
"""Shared test setup for local_backend.
|
||||
|
||||
Two kinds of tests live here:
|
||||
* fast unit tests: no database, no server (license rules, LAN IP, TLS, logging)
|
||||
* DB tests (marker `db`): a real SQLite database + the real FastAPI app
|
||||
|
||||
Run from local_backend/:
|
||||
pip install -r requirements-dev.txt
|
||||
python -m pytest tests -q
|
||||
python -m pytest tests -q # everything
|
||||
python -m pytest tests -q -m "not db" # quick set only
|
||||
|
||||
How the DB tests are isolated (agent notes):
|
||||
* Before anything imports config/database, this file points DATABASE_URL,
|
||||
LOG_DIR and TLS_DIR at a fresh temp folder. Tests can never touch a dev or
|
||||
venue database.
|
||||
* The schema is built once per test session (fixture `_schema`).
|
||||
>>> Step 1.0 (Alembic) must replace the body of `_build_schema` with
|
||||
>>> `alembic upgrade head`, so tests run on exactly the migrated schema.
|
||||
* Each test gets one connection with an outer transaction that is rolled
|
||||
back at the end. App code may call db.commit() freely: the session uses
|
||||
join_transaction_mode="create_savepoint", so its commits only release
|
||||
SAVEPOINTs inside the outer transaction.
|
||||
* Only code that gets its session through `Depends(get_db)` sees the test
|
||||
session. Code that opens `SessionLocal()` itself (background threads, tz.py,
|
||||
printer_service retry sweep) sees the committed database only, which is
|
||||
empty-ish. Don't test those paths with `client`; call them with the `db`
|
||||
fixture's session passed in, or refactor them to take a session.
|
||||
* Any test that uses the `db`, `client`, `make_user` or `login` fixture is
|
||||
marked `db` automatically.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
# ── isolate from real data: must run before config/database are imported ──
|
||||
_TMP = Path(tempfile.mkdtemp(prefix="xenia-tests-"))
|
||||
os.environ["DATABASE_URL"] = f"sqlite:///{(_TMP / 'test.db').as_posix()}"
|
||||
os.environ["LOG_DIR"] = str(_TMP / "logs")
|
||||
os.environ["TLS_DIR"] = str(_TMP / "tls")
|
||||
os.environ.setdefault("MASTER_USERNAME", "")
|
||||
os.environ.setdefault("MASTER_PASSWORD", "")
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import itertools # noqa: E402
|
||||
|
||||
import bcrypt # noqa: E402
|
||||
import pytest # noqa: E402
|
||||
from sqlalchemy import event # noqa: E402
|
||||
from sqlalchemy.orm import Session # noqa: E402
|
||||
|
||||
DB_FIXTURES = {"db", "client", "make_user", "login"}
|
||||
TEST_PASSWORD = "password"
|
||||
TEST_PIN = "1234"
|
||||
|
||||
|
||||
def pytest_configure(config):
|
||||
config.addinivalue_line("markers", "db: uses the real SQLite database and app (slower)")
|
||||
|
||||
|
||||
def pytest_collection_modifyitems(config, items):
|
||||
for item in items:
|
||||
if DB_FIXTURES & set(getattr(item, "fixturenames", ())):
|
||||
item.add_marker(pytest.mark.db)
|
||||
|
||||
|
||||
# ── schema + per-test transaction ───────────────────────────────────────────
|
||||
|
||||
def _build_schema(engine):
|
||||
import main # registers every model; also runs setup_logging() into LOG_DIR
|
||||
from database import Base
|
||||
Base.metadata.create_all(bind=engine)
|
||||
main._run_migrations()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def _engine():
|
||||
from database import engine
|
||||
|
||||
# pysqlite starts transactions lazily and ignores SAVEPOINT semantics unless
|
||||
# we take over BEGIN ourselves (SQLAlchemy docs, "Serializable isolation /
|
||||
# Savepoints / Transactional DDL" for pysqlite).
|
||||
@event.listens_for(engine, "connect")
|
||||
def _no_pysqlite_tx(dbapi_conn, _):
|
||||
dbapi_conn.isolation_level = None
|
||||
|
||||
@event.listens_for(engine, "begin")
|
||||
def _begin(conn):
|
||||
conn.exec_driver_sql("BEGIN")
|
||||
|
||||
_build_schema(engine)
|
||||
return engine
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db(_engine):
|
||||
"""A session whose work is rolled back after the test, even after commit()."""
|
||||
conn = _engine.connect()
|
||||
outer = conn.begin()
|
||||
session = Session(bind=conn, autoflush=False, join_transaction_mode="create_savepoint")
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
session.close()
|
||||
outer.rollback()
|
||||
conn.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(db):
|
||||
"""FastAPI TestClient on the real app, using the test session.
|
||||
|
||||
The lifespan is NOT run (no cloud sync, print-retry thread or TLS work);
|
||||
the schema comes from `_engine`. The license middleware is forced open."""
|
||||
from fastapi.testclient import TestClient
|
||||
import main
|
||||
from database import get_db
|
||||
from middleware.license_check import license_state
|
||||
|
||||
saved = dict(license_state)
|
||||
license_state.update(licensed=True, locked=False)
|
||||
|
||||
def _get_db():
|
||||
yield db
|
||||
|
||||
main.app.dependency_overrides[get_db] = _get_db
|
||||
try:
|
||||
yield TestClient(main.app)
|
||||
finally:
|
||||
main.app.dependency_overrides.pop(get_db, None)
|
||||
license_state.clear()
|
||||
license_state.update(saved)
|
||||
|
||||
|
||||
# ── users ───────────────────────────────────────────────────────────────────
|
||||
|
||||
_FAST_SALT = bcrypt.gensalt(rounds=4) # tests only: real code uses the default cost
|
||||
_seq = itertools.count(1)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_user(db):
|
||||
"""make_user(role="manager", perms={"perm_view_reports": False}, **fields) -> User.
|
||||
|
||||
Password is TEST_PASSWORD and PIN is TEST_PIN. Permissions start from the
|
||||
role's defaults (roles.DEFAULT_PERMISSIONS).
|
||||
>>> Step 1.5 replaces `perms` with permission keys (user_permissions table).
|
||||
"""
|
||||
from models.user import User
|
||||
from roles import get_default_permissions
|
||||
|
||||
pw_hash = bcrypt.hashpw(TEST_PASSWORD.encode(), _FAST_SALT).decode()
|
||||
pin_hash = bcrypt.hashpw(TEST_PIN.encode(), _FAST_SALT).decode()
|
||||
|
||||
def _make(role="manager", perms=None, **fields):
|
||||
n = next(_seq)
|
||||
values = dict(
|
||||
username=f"{role}{n}", full_name=f"Test {role} {n}", role=role,
|
||||
is_active=True, password_hash=pw_hash, pin_hash=pin_hash,
|
||||
)
|
||||
values.update(get_default_permissions(role))
|
||||
values.update(perms or {})
|
||||
values.update(fields)
|
||||
user = User(**values)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
return user
|
||||
|
||||
return _make
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def login():
|
||||
"""login(user) -> {"Authorization": "Bearer ..."} without calling the API (fast).
|
||||
Tests about the login flow itself should POST /api/auth/login instead."""
|
||||
from routers.deps import make_token
|
||||
|
||||
def _login(user):
|
||||
return {"Authorization": f"Bearer {make_token(user)}"}
|
||||
|
||||
return _login
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Proves the DB test harness (plan step 0.5): real login, real app, rollback between tests."""
|
||||
from conftest import TEST_PASSWORD
|
||||
|
||||
|
||||
def test_manager_logs_in_and_reads_me(client, make_user):
|
||||
m = make_user(role="manager")
|
||||
r = client.post("/api/auth/login", json={"username": m.username, "password": TEST_PASSWORD})
|
||||
assert r.status_code == 200, r.text
|
||||
token = r.json()["access_token"]
|
||||
me = client.get("/api/auth/me", headers={"Authorization": f"Bearer {token}"})
|
||||
assert me.status_code == 200
|
||||
assert me.json()["username"] == m.username
|
||||
|
||||
|
||||
def test_wrong_password_is_rejected(client, make_user):
|
||||
m = make_user(role="manager")
|
||||
r = client.post("/api/auth/login", json={"username": m.username, "password": "nope"})
|
||||
assert r.status_code == 401
|
||||
|
||||
|
||||
def test_login_fixture_gives_working_headers(client, make_user, login):
|
||||
w = make_user(role="waiter")
|
||||
assert client.get("/api/auth/me", headers=login(w)).json()["role"] == "waiter"
|
||||
|
||||
|
||||
def test_commits_are_rolled_back_between_tests_part1(db, make_user):
|
||||
from models.user import User
|
||||
make_user(role="manager", username="rollback_probe")
|
||||
assert db.query(User).filter_by(username="rollback_probe").count() == 1
|
||||
|
||||
|
||||
def test_commits_are_rolled_back_between_tests_part2(db):
|
||||
from models.user import User
|
||||
assert db.query(User).filter_by(username="rollback_probe").count() == 0
|
||||
Reference in New Issue
Block a user