""" tests/test_state_store.py — unit tests for billing/state_store.py, run against a real (throwaway, temp-file) SQLite database, not a mock — this is the one place the multi-tenant scoping guarantee actually matters, so it's worth proving against the real thing rather than trusting mocked calls. """ import pytest from billing.state_store import StateStore @pytest.fixture def db_path(tmp_path): return str(tmp_path / "state.db") def _state(roles, default_workspace=None): return {"roles": roles, "default_workspace": default_workspace} # --- construction ------------------------------------------------------------ def test_tenant_slug_is_required(): with pytest.raises(ValueError): StateStore(tenant_slug=None) with pytest.raises(ValueError): StateStore(tenant_slug="") def test_default_db_path_falls_back_to_state_store_path_env_var(monkeypatch, db_path): monkeypatch.setenv("STATE_STORE_PATH", db_path) store = StateStore(tenant_slug="acme") assert store.db_path == db_path assert store.get_snapshot() == {} def test_connect_rolls_back_and_reraises_on_failure(db_path): store = StateStore(tenant_slug="acme", db_path=db_path) with pytest.raises(RuntimeError): with store._connect(): raise RuntimeError("simulated failure mid-transaction") # the store is still usable afterward — the failed unit of work didn't corrupt anything assert store.get_snapshot() == {} # --- snapshot: basic read/write --------------------------------------------- def test_get_snapshot_is_empty_before_anything_is_saved(db_path): store = StateStore(tenant_slug="acme", db_path=db_path) assert store.get_snapshot() == {} def test_save_and_get_snapshot_round_trips(db_path): store = StateStore(tenant_slug="acme", db_path=db_path) store.save_snapshot({"alice": _state(["Stock User"], "Stock"), "bob": _state(["Stock Manager", "System Manager"])}) assert store.get_snapshot() == { "alice": _state(["Stock User"], "Stock"), "bob": _state(["Stock Manager", "System Manager"]), } def test_save_snapshot_replaces_the_previous_one(db_path): store = StateStore(tenant_slug="acme", db_path=db_path) store.save_snapshot({"alice": _state(["Stock User"]), "bob": _state(["Stock Manager"])}) store.save_snapshot({"carol": _state(["Stock User"])}) assert store.get_snapshot() == {"carol": _state(["Stock User"])} def test_clear_snapshot_empties_it(db_path): store = StateStore(tenant_slug="acme", db_path=db_path) store.save_snapshot({"alice": _state(["Stock User"])}) store.clear_snapshot() assert store.get_snapshot() == {} # --- the multi-tenant guarantee --------------------------------------------- def test_two_tenants_sharing_one_db_file_never_see_each_others_snapshot(db_path): acme = StateStore(tenant_slug="acme", db_path=db_path) beta = StateStore(tenant_slug="beta", db_path=db_path) acme.save_snapshot({"alice": _state(["Stock User"]), "bob": _state(["Stock Manager"])}) beta.save_snapshot({"carol": _state(["Stock User"])}) assert acme.get_snapshot() == {"alice": _state(["Stock User"]), "bob": _state(["Stock Manager"])} assert beta.get_snapshot() == {"carol": _state(["Stock User"])} def test_clearing_one_tenants_snapshot_does_not_touch_anothers(db_path): acme = StateStore(tenant_slug="acme", db_path=db_path) beta = StateStore(tenant_slug="beta", db_path=db_path) acme.save_snapshot({"alice": _state(["Stock User"])}) beta.save_snapshot({"carol": _state(["Stock User"])}) acme.clear_snapshot() assert acme.get_snapshot() == {} assert beta.get_snapshot() == {"carol": _state(["Stock User"])} def test_two_tenants_can_independently_store_the_same_username(db_path): acme = StateStore(tenant_slug="acme", db_path=db_path) beta = StateStore(tenant_slug="beta", db_path=db_path) acme.save_snapshot({"shared-name": _state(["Stock User"])}) beta.save_snapshot({"shared-name": _state(["Stock Manager"])}) assert acme.get_snapshot() == {"shared-name": _state(["Stock User"])} assert beta.get_snapshot() == {"shared-name": _state(["Stock Manager"])} # --- action_log -------------------------------------------------------------- def test_log_action_is_scoped_per_tenant(db_path): acme = StateStore(tenant_slug="acme", db_path=db_path) beta = StateStore(tenant_slug="beta", db_path=db_path) acme.log_action("trace-1", "user_locked", "success", username="alice") beta.log_action("trace-2", "user_locked", "success", username="carol") with acme._connect() as conn: acme_rows = conn.execute( "SELECT tenant_slug, trace_id, username FROM action_log WHERE tenant_slug = ?", ("acme",), ).fetchall() beta_rows = conn.execute( "SELECT tenant_slug, trace_id, username FROM action_log WHERE tenant_slug = ?", ("beta",), ).fetchall() assert acme_rows == [("acme", "trace-1", "alice")] assert beta_rows == [("beta", "trace-2", "carol")] def test_log_action_without_username_stores_null(db_path): store = StateStore(tenant_slug="acme", db_path=db_path) store.log_action("trace-1", "snapshot_save", "success") with store._connect() as conn: row = conn.execute("SELECT username FROM action_log").fetchone() assert row[0] is None # --- pre-multi-tenant schema migration --------------------------------------- def _create_pre_tenant_tables(db_path): """Recreates the exact single-tenant schema that predates tenant_slug scoping.""" import sqlite3 conn = sqlite3.connect(db_path) conn.execute("CREATE TABLE snapshot (username TEXT PRIMARY KEY)") conn.execute( "CREATE TABLE action_log (" "id INTEGER PRIMARY KEY AUTOINCREMENT, " "timestamp TEXT NOT NULL, " "trace_id TEXT NOT NULL, " "action TEXT NOT NULL, " "username TEXT, " "status TEXT NOT NULL" ")" ) conn.commit() conn.close() def test_init_migrates_empty_pre_tenant_tables_to_current_schema(db_path): _create_pre_tenant_tables(db_path) store = StateStore(tenant_slug="acme", db_path=db_path) # The old tenant_slug-less tables are gone, replaced by ones that work normally. store.save_snapshot({"alice": _state(["Stock User"])}) assert store.get_snapshot() == {"alice": _state(["Stock User"])} def test_init_refuses_to_touch_pre_tenant_table_with_existing_rows(db_path): _create_pre_tenant_tables(db_path) import sqlite3 conn = sqlite3.connect(db_path) conn.execute("INSERT INTO snapshot (username) VALUES ('orphaned-user')") conn.commit() conn.close() with pytest.raises(RuntimeError, match="snapshot.*predates the multi-tenant schema"): StateStore(tenant_slug="acme", db_path=db_path) def test_init_leaves_current_schema_table_untouched(db_path): store = StateStore(tenant_slug="acme", db_path=db_path) store.save_snapshot({"alice": _state(["Stock User"])}) # Re-initializing (as every request does) must not wipe existing data. StateStore(tenant_slug="acme", db_path=db_path) assert store.get_snapshot() == {"alice": _state(["Stock User"])} # --- pre-restore-state schema migrations ------------------------------------- # Two prior schemas both lack `restore_state` and must migrate the same way: # the pre-role-swap one (bare usernames only) and the intermediate role-swap # one (Roles but no default_workspace — what this project's own live site # actually ran until the default_workspace bug was caught). def _create_pre_role_swap_snapshot_table(db_path): """Recreates the multi-tenant, pre-role-swap snapshot schema (usernames only, no roles).""" import sqlite3 conn = sqlite3.connect(db_path) conn.execute( "CREATE TABLE snapshot (" "tenant_slug TEXT NOT NULL, username TEXT NOT NULL, PRIMARY KEY (tenant_slug, username))" ) conn.commit() conn.close() def test_init_migrates_empty_pre_role_swap_snapshot_to_current_schema(db_path): _create_pre_role_swap_snapshot_table(db_path) store = StateStore(tenant_slug="acme", db_path=db_path) store.save_snapshot({"alice": _state(["Stock User"])}) assert store.get_snapshot() == {"alice": _state(["Stock User"])} def test_init_refuses_to_touch_pre_role_swap_snapshot_with_existing_rows(db_path): _create_pre_role_swap_snapshot_table(db_path) import sqlite3 conn = sqlite3.connect(db_path) conn.execute("INSERT INTO snapshot (tenant_slug, username) VALUES ('acme', 'orphaned-user')") conn.commit() conn.close() with pytest.raises(RuntimeError, match="snapshot.*predates the current restore_state column"): StateStore(tenant_slug="acme", db_path=db_path) def _create_roles_only_snapshot_table(db_path): """Recreates the intermediate schema: Roles stored, but no default_workspace column at all.""" import sqlite3 conn = sqlite3.connect(db_path) conn.execute( "CREATE TABLE snapshot (tenant_slug TEXT NOT NULL, username TEXT NOT NULL, roles TEXT NOT NULL, " "PRIMARY KEY (tenant_slug, username))" ) conn.commit() conn.close() def test_init_migrates_empty_roles_only_snapshot_to_current_schema(db_path): _create_roles_only_snapshot_table(db_path) store = StateStore(tenant_slug="acme", db_path=db_path) store.save_snapshot({"alice": _state(["Stock User"], "Stock")}) assert store.get_snapshot() == {"alice": _state(["Stock User"], "Stock")} def test_init_refuses_to_touch_roles_only_snapshot_with_existing_rows(db_path): _create_roles_only_snapshot_table(db_path) import json import sqlite3 conn = sqlite3.connect(db_path) conn.execute( "INSERT INTO snapshot (tenant_slug, username, roles) VALUES (?, ?, ?)", ("acme", "orphaned-user", json.dumps(["Stock User"])), ) conn.commit() conn.close() with pytest.raises(RuntimeError, match="snapshot.*predates the current restore_state column"): StateStore(tenant_slug="acme", db_path=db_path)