"""Isolated integration checks for onboarding → lobby → game → telemetry. Run with ``python -m unittest discover -s tests``. Tests force a temporary SQLite URI before importing the app; the mounted databases are never opened. """ import json import os import sqlite3 import tempfile import time import unittest from pathlib import Path from unittest.mock import patch _test_root = "/tmp/opencode" if os.path.isdir("/tmp/opencode") else tempfile.gettempdir() _test_dir = tempfile.TemporaryDirectory(prefix="parlor-tests-", dir=_test_root) os.environ["DATABASE_URL"] = "sqlite:///" + os.path.join(_test_dir.name, "test.db") os.environ["LOBBY_CHAT_GENERATION_TOKEN"] = "unit-test-secret" os.environ["TEST_MODE"] = "false" import app as app_module # noqa: E402 from extensions import db # noqa: E402 from config import Config # noqa: E402 from models import ( # noqa: E402 ChatGenerationJob, Game, GamePlayer, LobbyMessage, LobbyRound, MatchmakingEntry, Room, TelemetryEvent, User, ) from services.lobby import rotate_round # noqa: E402 class LobbyFlowTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.app = app_module.app cls.app.config.update(TESTING=True) @classmethod def tearDownClass(cls): runtime = app_module.LOBBY_RUNTIME runtime.stop() if runtime._thread: runtime._thread.join(timeout=2) if runtime._generation_thread: runtime._generation_thread.join(timeout=2) with cls.app.app_context(): db.session.remove() db.engine.dispose() _test_dir.cleanup() def test_missing_default_database_does_not_import_legacy_file(self): old_values = (Config.DATA_DIR, Config.INSTANCE_PATH, Config.LEGACY_DATABASE_PATH) with tempfile.TemporaryDirectory(prefix="fresh-db-") as directory: root = Path(directory) Config.DATA_DIR = str(root / "data") Config.INSTANCE_PATH = str(root / "instance") Config.LEGACY_DATABASE_PATH = str(root / "instance" / "app.db") Path(Config.INSTANCE_PATH).mkdir(parents=True) with sqlite3.connect(Config.LEGACY_DATABASE_PATH) as legacy: legacy.execute("CREATE TABLE legacy_marker (id INTEGER PRIMARY KEY)") legacy.execute("INSERT INTO legacy_marker DEFAULT VALUES") with patch.dict(os.environ, {"DATABASE_URL": ""}): Config.ensure_data_dir() self.assertFalse((root / "data" / "app.db").exists()) self.assertTrue(Path(Config.LEGACY_DATABASE_PATH).exists()) Config.DATA_DIR, Config.INSTANCE_PATH, Config.LEGACY_DATABASE_PATH = old_values def test_health_check_does_not_create_guest_accounts(self): with self.app.app_context(): before = User.query.count() response = self.app.test_client().get("/health") self.assertEqual(response.status_code, 200) with self.app.app_context(): self.assertEqual(User.query.count(), before) def test_lobby_to_match_and_generation(self): root = Path(__file__).parents[1] stylesheet = root / "static" / "css" / "app.css" self.assertRegex(stylesheet.read_text(), r"\[hidden\]\s*\{\s*display:\s*none\s*!important") clients = [self.app.test_client() for _ in range(6)] for client in clients: response = client.get("/") self.assertEqual(response.status_code, 200) self.assertNotIn(b"Join matchmaking", response.data) self.assertIn(b"onboarding-overlay", response.data) onboarding = clients[0].get("/api/onboarding").get_json()["data"] self.assertFalse(onboarding["completed"]) self.assertEqual( clients[0].post("/api/onboarding", json={"answers": {"unknown": "x"}}).status_code, 400, ) initial_answers = { "assumption": "The parlor answer should be present in telemetry as requested", "softened_truth": "I always notice the exits", "trust": "Consistency matters more than charm", "brothers_maiden_name": "A private answer for this prompt", } saved = clients[0].post( "/api/onboarding", json={"answers": initial_answers, "future_use": True}, ) self.assertEqual(saved.status_code, 200) self.assertEqual(saved.get_json()["data"]["answers"], initial_answers) with self.app.app_context(): saved_user = User.query.filter_by(id=1).one() self.assertEqual(json.loads(saved_user.onboarding_json)["answers"], initial_answers) onboarding_events = TelemetryEvent.query.filter_by(event_type="onboarding_complete").all() self.assertTrue(any(json.loads(event.payload_json)["answers"] == initial_answers for event in onboarding_events)) forgotten = clients[0].delete("/api/onboarding").get_json()["data"] self.assertTrue(forgotten["completed"]) self.assertEqual(forgotten["answers"], {}) with self.app.app_context(): self.assertEqual( TelemetryEvent.query.filter_by(user_id=1, event_type="onboarding_complete").count(), 0, ) for client in clients[1:5]: self.assertEqual(client.post("/api/onboarding", json={"skip": True}).status_code, 200) partial_skip = clients[5].post("/api/onboarding", json={ "skip": True, "answers": {"assumption": "Keep this answer while skipping the rest"}, }) self.assertEqual(partial_skip.status_code, 200) self.assertEqual( partial_skip.get_json()["data"]["answers"], {"assumption": "Keep this answer while skipping the rest"}, ) with self.app.app_context(): partial_event = TelemetryEvent.query.filter_by( user_id=6, event_type="onboarding_complete", ).one() self.assertEqual( json.loads(partial_event.payload_json)["answers"], {"assumption": "Keep this answer while skipping the rest"}, ) with patch.dict(os.environ, {"HF_TOKEN": ""}): self.assertEqual(clients[0].get("/inference").status_code, 200) with self.app.app_context(): self.assertEqual(Room.query.count(), 0) # A completed onboarding flow auto-queues on lobby state; no Join button. state = clients[0].get("/api/lobby/state").get_json()["data"] self.assertTrue(state["queued"]) self.assertFalse(state["participated"]) self.assertEqual(state["round"]["status"], "open") self.assertEqual(state["participation_prompt"]["id"], "tell-01") second_state = clients[1].get("/api/lobby/state").get_json()["data"] self.assertEqual(second_state["queue_count"], 2) self.assertEqual(second_state["queue_position"], 2) duplicate = clients[0].post("/api/matchmaking/queue").get_json()["data"] self.assertEqual(duplicate["queue_count"], 2) self.assertEqual(duplicate["queue_position"], 1) # Leaving pauses, rather than deleting identity; re-entry keeps one row. self.assertEqual(clients[1].delete("/api/matchmaking/queue").get_json()["data"]["queue_count"], 1) resumed = clients[1].post("/api/matchmaking/queue").get_json()["data"] self.assertEqual(resumed["queue_position"], 2) # Short chat is visible but doesn't qualify as meaningful participation. short_message = clients[0].post("/api/lobby/chat", json={"msg": "Hi."}) self.assertEqual(short_message.status_code, 201) self.assertFalse(short_message.get_json()["data"]["message"]["matchmaking"]["qualified"]) self.assertFalse(clients[0].get("/api/lobby/state").get_json()["data"]["participated"]) # Same browser/session remains the same chat author across requests. first_message = clients[0].post("/api/lobby/chat", json={"msg": "The room feels too quiet."}) second_message = clients[0].post("/api/lobby/chat", json={"msg": "I heard something behind the door."}) self.assertEqual(first_message.status_code, 201) self.assertTrue(first_message.get_json()["data"]["message"]["matchmaking"]["qualified"]) self.assertEqual(first_message.get_json()["data"]["message"]["user"], second_message.get_json()["data"]["message"]["user"]) with self.app.app_context(): messages = LobbyMessage.query.filter_by(source="user").order_by(LobbyMessage.id.asc()).all() self.assertEqual(messages[0].user_id, messages[1].user_id) self.assertEqual(MatchmakingEntry.query.filter_by(user_id=messages[0].user_id).count(), 1) chat_events = TelemetryEvent.query.filter_by(event_type="lobby_chat").all() self.assertTrue(any("The room feels too quiet." in event.payload_json for event in chat_events)) self.assertTrue(clients[0].get("/api/lobby/state").get_json()["data"]["participated"]) client_one_answer = clients[1].post("/api/lobby/answer", json={ "prompt_id": resumed["participation_prompt"]["id"], "answer": "I would first watch who rushes to fill the silence.", }) self.assertEqual(client_one_answer.status_code, 201, client_one_answer.get_json()) # The poll still works while guests speak into the shared room. poll = clients[0].get("/api/lobby/minigame/current").get_json()["data"]["round"] self.assertEqual(clients[0].post( f"/api/lobby/minigame/{poll['id']}/vote", json={"choice": poll["options"][0]} ).status_code, 200) with self.app.app_context(): open_round = db.session.get(LobbyRound, poll["id"]) open_round.ends_at = open_round.ends_at.replace(year=2000) db.session.commit() reveal = rotate_round() self.assertEqual(reveal.status, "reveal") reveal.ends_at = reveal.ends_at.replace(year=2000) db.session.commit() self.assertEqual(rotate_round().status, "open") # The remaining real guests auto-queue and must speak before a match forms. for client in clients[2:5]: data = client.get("/api/lobby/state").get_json()["data"] answer = client.post("/api/lobby/answer", json={ "prompt_id": data["participation_prompt"]["id"], "answer": "I notice who avoids the question.", }) self.assertEqual(answer.status_code, 201, answer.get_json()) match = clients[0].get("/api/lobby/state").get_json()["data"]["match"] self.assertIsNotNone(match) room_id = match["room_id"] room_page = clients[0].get(match["url"]) self.assertEqual(room_page.status_code, 200) self.assertIn(b"gameplay-panel", room_page.data) self.assertIn(b"gameplay.js", room_page.data) game_states = [clients[index].get(f"/api/room/{room_id}/game").get_json()["data"] for index in range(5)] role_ids = [state["my_role"]["role_id"] for state in game_states] self.assertEqual(role_ids.count("mastermind"), 1) self.assertEqual(role_ids.count("investigator"), 1) self.assertTrue(all("role_by_player" not in state for state in game_states)) investigator_index = role_ids.index("investigator") with self.app.app_context(): player_roles = { player.user_id: player.role for player in GamePlayer.query.filter_by(game_id=game_states[0]["game_id"]).all() } culprit_id = next(user_id for user_id, role_id in player_roles.items() if role_id == "mastermind") investigation = clients[investigator_index].post( f"/api/room/{room_id}/game/action", json={"action": "investigate", "payload": {"target_user_id": culprit_id}}, ) self.assertEqual(investigation.status_code, 200) self.assertEqual(investigation.get_json()["data"]["result"]["private_result"]["team"], "shadow") uninformed_index = next(index for index in range(5) if index != investigator_index) self.assertEqual( clients[uninformed_index].get(f"/api/room/{room_id}/game").get_json()["data"]["investigation_notes"], [], ) self.assertEqual(clients[0].post( f"/api/room/{room_id}/game/action", json={"action": "begin_vote", "payload": {}} ).status_code, 200) player_client = { next(player["user_id"] for player in state["players"] if player["is_you"]): index for index, state in enumerate(game_states) } other_id = next(user_id for user_id in player_client if user_id != culprit_id) for user_id, index in player_client.items(): target = other_id if user_id == culprit_id else culprit_id vote = clients[index].post( f"/api/room/{room_id}/game/action", json={"action": "vote", "payload": {"target_user_id": target}}, ) self.assertEqual(vote.status_code, 200, vote.get_json()) final_state = clients[0].get(f"/api/room/{room_id}/game").get_json()["data"] self.assertEqual(final_state["phase"], "finished") self.assertEqual(final_state["winner"], "parlor") self.assertTrue(all(player["role_revealed"] for player in final_state["players"])) with self.app.app_context(): self.assertIsNotNone(db.session.get(Game, game_states[0]["game_id"]).ended_at) self.assertEqual(clients[0].post(f"/api/room/{room_id}/chat", json={"msg": "hello table"}).status_code, 200) self.assertEqual(clients[5].get(f"/api/room/{room_id}/game").status_code, 403) self.assertEqual(clients[5].post(f"/api/room/{room_id}/chat", json={"msg": "not a member"}).status_code, 403) self.assertEqual(clients[0].post("/internal/lobby/chat/generation", json={}).status_code, 401) headers = {"Authorization": "Bearer unit-test-secret", "Idempotency-Key": "lobby-flow-test"} job = clients[0].post("/internal/lobby/chat/generation", headers=headers, json={"context_key": "lobby"}).get_json() repeated = clients[0].post("/internal/lobby/chat/generation", headers=headers, json={"context_key": "lobby"}).get_json() self.assertEqual(job["job_id"], repeated["job_id"]) deadline = time.time() + 5 status = "queued" while time.time() < deadline: result = clients[0].get( f"/internal/lobby/chat/generation/{job['job_id']}", headers={"Authorization": "Bearer unit-test-secret"}, ).get_json() status = result["status"] if status in ("complete", "failed"): break time.sleep(0.05) self.assertEqual(status, "complete") self.assertEqual(clients[0].post( "/avatar/update", data={"style": "lorelei", "seed": "regression-seed", "bg": "transparent"} ).status_code, 302) created = clients[5].post( "/create", data={"name": "Manual test table", "min_players": "5", "max_players": "5", "is_public": "on"} ) self.assertEqual(created.status_code, 302) manual_room_url = created.headers["Location"] self.assertEqual(clients[5].get(manual_room_url).status_code, 200) self.assertEqual(clients[4].get(manual_room_url.replace("/room/", "/join/")).status_code, 302) manual_room_id = manual_room_url.rsplit("/", 1)[-1] self.assertEqual(clients[4].post(f"/api/room/{manual_room_id}/chat", json={"msg": "joined manually"}).status_code, 200) batch = clients[5].post("/api/telemetry", json={"events": [ {"event_type": "batch_click", "page": "/lobby", "element": "button#one"}, {"event_type": "batch_focus", "page": "/lobby", "element": "input#two"}, ]}) self.assertEqual(batch.status_code, 200) self.assertEqual(batch.get_json()["count"], 2) from services.test_players import TestMode with self.app.app_context(): bots = TestMode.ensure_test_players(25) self.assertEqual(len(bots), 10) self.assertEqual(User.query.filter(User.is_test_bot.is_(True)).count(), 10) self.assertIsNone(User.query.filter_by(nickname="TestBot10").first()) with self.app.app_context(): self.assertGreater(TelemetryEvent.query.count(), 0) self.assertEqual(TelemetryEvent.query.filter_by(event_type="batch_click").count(), 1) self.assertEqual(TelemetryEvent.query.filter_by(event_type="batch_focus").count(), 1) self.assertEqual(db.session.get(ChatGenerationJob, job["job_id"]).status, "complete")