Platform v2 step 1.5 (APPS_PLATFORM D-7, D-17, §3, §6.1).
- user_permissions(user_id, key); revision 0005 copies existing v1 flags into
keys (frozen mapping) and drops the perm_* columns; can_cancel_orders gone
- core/access: check() = module effective + key held (superadmin implicit,
override keys wired for 1.9); holds()/can(); markers require/require_any/
public/require_device; role templates from manifests; queries.holders_filter
replaces User.perm_x == True; legacy.py projects/accepts the v1 booleans
for the current manager/waiter UIs only (§3.3, temporary)
- routers.deps: require_manager/... are now aliases of require("<key>");
history endpoints use history.view; superadmin-only = core.system.admin;
get_current_user carries the "signed_in" marker
- every inline perm_* read in routers/services converted to holds()
- staff API: permission catalogue by module with role templates, get/set a
user's keys, reset to role template; legacy flag toggles still work; a
non-superadmin can only grant keys they hold (access.cannot_grant)
- setup wizard creates the first account as owner (v1: store_manager, who
couldn't change settings); demo/seed manager is owner
- roles.py keeps only the role list and labels
- guards: every route has an access marker (19 open routes marked public()
on purpose; /waiters/roles now needs sign-in), no perm_* attribute reads
- tests: check matrix, templates, projection, staff permission API, grant
guard, 0005 data copy; pack rule CS-14
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
205 lines
7.6 KiB
Python
205 lines
7.6 KiB
Python
"""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 # 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 `_engine`) with the same
|
|
Alembic upgrade the app runs at startup, so tests see 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 models.all # noqa: E402,F401 every model registered before any test touches the ORM
|
|
|
|
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)
|
|
|
|
|
|
# ── venue time ──────────────────────────────────────────────────────────────
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _venue_time():
|
|
"""Every test runs in Europe/Athens with rollover 06:00 (D-11), venue language "en"
|
|
(D-12) and every module entitled without limits (D-3), without reading anything from a
|
|
database. Tests may call configure(...) / entitlements.set_current(...) to change them."""
|
|
from core import i18n, timeutil
|
|
from core.modules import entitlements
|
|
timeutil.configure(tz="Europe/Athens", rollover_hour=6)
|
|
i18n.configure(venue_language="en")
|
|
# Every module, no limits (like LICENSE_MODE=off). License tests install their own.
|
|
entitlements.set_current(entitlements.dev(), notify=False)
|
|
yield
|
|
entitlements.reset()
|
|
timeutil.invalidate()
|
|
i18n.invalidate()
|
|
from core.modules import state as module_state
|
|
module_state.invalidate() # module enablement is cached; each test starts from the DB
|
|
|
|
|
|
# ── schema + per-test transaction ───────────────────────────────────────────
|
|
|
|
def _build_schema(engine):
|
|
import main # noqa: F401 registers every model; also runs setup_logging() into LOG_DIR
|
|
from core.schema import upgrade_to_head
|
|
upgrade_to_head(engine)
|
|
|
|
|
|
@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`. Entitlements are "dev" (every module, no limits)
|
|
via the autouse `_venue_time` fixture; license tests install their own."""
|
|
from fastapi.testclient import TestClient
|
|
import main
|
|
from database import get_db
|
|
from services.license_state 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="store_manager", keys=None, add=(), remove=(), **fields) -> User.
|
|
|
|
Password is TEST_PASSWORD and PIN is TEST_PIN. Permission keys start from the role
|
|
template (manifests, core/access/templates.py); `keys` replaces them, `add`/`remove`
|
|
adjust them.
|
|
"""
|
|
from models.user import User
|
|
from core.access.templates import role_template, set_user_keys
|
|
|
|
pw_hash = bcrypt.hashpw(TEST_PASSWORD.encode(), _FAST_SALT).decode()
|
|
pin_hash = bcrypt.hashpw(TEST_PIN.encode(), _FAST_SALT).decode()
|
|
|
|
def _make(role="store_manager", keys=None, add=(), remove=(), **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(fields)
|
|
user = User(**values)
|
|
granted = set(role_template(role) if keys is None else keys)
|
|
set_user_keys(user, (granted | set(add)) - set(remove))
|
|
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
|