Compare commits
1 Commits
burn/1509-
...
fix/1503
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
57198eace7 |
@@ -28,16 +28,11 @@ except ImportError:
|
||||
websockets = None
|
||||
|
||||
from nexus.evennia_event_adapter import (
|
||||
actor_located,
|
||||
audit_heartbeat,
|
||||
command_executed,
|
||||
command_issued,
|
||||
command_result,
|
||||
player_join,
|
||||
player_leave,
|
||||
player_move,
|
||||
room_snapshot,
|
||||
session_bound,
|
||||
)
|
||||
|
||||
ANSI_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")
|
||||
@@ -54,82 +49,31 @@ def strip_ansi(text: str) -> str:
|
||||
return ANSI_RE.sub("", text or "")
|
||||
|
||||
|
||||
def clean_lines(text: str) -> list[str]:
|
||||
"""Strip ANSI codes and split into non-empty lines."""
|
||||
text = strip_ansi(text).replace("\r", "")
|
||||
return [line.strip() for line in text.split("\n") if line.strip()]
|
||||
|
||||
|
||||
def parse_room_output(text: str) -> dict | None:
|
||||
"""Parse Evennia room output into structured data with title, desc, exits, objects."""
|
||||
lines = clean_lines(text)
|
||||
if len(lines) < 2:
|
||||
return None
|
||||
title = lines[0]
|
||||
desc = lines[1]
|
||||
exits = []
|
||||
objects = []
|
||||
for line in lines[2:]:
|
||||
if line.startswith("Exits:"):
|
||||
raw = line.split(":", 1)[1].strip().replace(" and ", ", ")
|
||||
exits = [{"key": t.strip(), "destination_id": t.strip().title(), "destination_key": t.strip().title()} for t in raw.split(",") if t.strip()]
|
||||
elif line.startswith("You see:"):
|
||||
raw = line.split(":", 1)[1].strip().replace(" and ", ", ")
|
||||
parts = [t.strip() for t in raw.split(",") if t.strip()]
|
||||
objects = [{"id": p.removeprefix("a ").removeprefix("an "), "key": p.removeprefix("a ").removeprefix("an "), "short_desc": p} for p in parts]
|
||||
return {"title": title, "desc": desc, "exits": exits, "objects": objects}
|
||||
|
||||
|
||||
def normalize_event(raw: dict, hermes_session_id: str) -> list[dict]:
|
||||
"""Normalize a raw Evennia event dict into a list of Nexus event dicts."""
|
||||
out = []
|
||||
event = raw.get("event")
|
||||
actor = raw.get("actor", "Timmy")
|
||||
timestamp = raw.get("timestamp")
|
||||
if event == "connect":
|
||||
out.append(session_bound(hermes_session_id, evennia_account=actor, evennia_character=actor, timestamp=timestamp))
|
||||
parsed = parse_room_output(raw.get("output", ""))
|
||||
if parsed:
|
||||
out.append(actor_located(actor, parsed["title"], parsed["title"], timestamp=timestamp))
|
||||
out.append(room_snapshot(parsed["title"], parsed["title"], parsed["desc"], exits=parsed["exits"], objects=parsed["objects"], timestamp=timestamp))
|
||||
elif event == "command":
|
||||
cmd = raw.get("command", "")
|
||||
output = raw.get("output", "")
|
||||
out.append(command_issued(hermes_session_id, actor, cmd, timestamp=timestamp))
|
||||
success = not output.startswith("Command '") and not output.startswith("Could not find")
|
||||
out.append(command_result(hermes_session_id, actor, cmd, strip_ansi(output), success=success, timestamp=timestamp))
|
||||
parsed = parse_room_output(output)
|
||||
if parsed:
|
||||
out.append(actor_located(actor, parsed["title"], parsed["title"], timestamp=timestamp))
|
||||
out.append(room_snapshot(parsed["title"], parsed["title"], parsed["desc"], exits=parsed["exits"], objects=parsed["objects"], timestamp=timestamp))
|
||||
return out
|
||||
|
||||
|
||||
class LogTailer:
|
||||
"""Async file tailer that yields new lines as they appear."""
|
||||
|
||||
|
||||
def __init__(self, path: str, poll_interval: float = 0.5):
|
||||
self.path = path
|
||||
self.poll_interval = poll_interval
|
||||
self._offset = 0
|
||||
|
||||
|
||||
async def tail(self):
|
||||
"""Yield new lines from the file, starting from end."""
|
||||
# Start at end of file
|
||||
if os.path.exists(self.path):
|
||||
self._offset = os.path.getsize(self.path)
|
||||
|
||||
|
||||
while True:
|
||||
try:
|
||||
if not os.path.exists(self.path):
|
||||
await asyncio.sleep(self.poll_interval)
|
||||
continue
|
||||
|
||||
|
||||
size = os.path.getsize(self.path)
|
||||
if size < self._offset:
|
||||
# File was truncated/rotated
|
||||
self._offset = 0
|
||||
|
||||
|
||||
if size > self._offset:
|
||||
with open(self.path, "r") as f:
|
||||
f.seek(self._offset)
|
||||
@@ -138,7 +82,7 @@ class LogTailer:
|
||||
if line:
|
||||
yield line
|
||||
self._offset = f.tell()
|
||||
|
||||
|
||||
await asyncio.sleep(self.poll_interval)
|
||||
except Exception as e:
|
||||
print(f"[tailer] Error reading {self.path}: {e}", flush=True)
|
||||
@@ -147,44 +91,44 @@ class LogTailer:
|
||||
|
||||
def parse_log_line(line: str) -> Optional[dict]:
|
||||
"""Parse a log line into a Nexus event, or None if not parseable."""
|
||||
|
||||
|
||||
# Movement events
|
||||
m = MOVE_RE.search(line)
|
||||
if m:
|
||||
return player_move(m.group(1), m.group(3), m.group(2))
|
||||
|
||||
|
||||
# Command events
|
||||
m = CMD_RE.search(line)
|
||||
if m:
|
||||
return command_executed(m.group(1), m.group(2), m.group(3) or "")
|
||||
|
||||
|
||||
# Session start
|
||||
m = SESSION_START_RE.search(line)
|
||||
if m:
|
||||
return player_join(m.group(2), m.group(1))
|
||||
|
||||
|
||||
# Session end
|
||||
m = SESSION_END_RE.search(line)
|
||||
if m:
|
||||
return player_leave("", m.group(1), session_duration=float(m.group(2)))
|
||||
|
||||
|
||||
# Server login
|
||||
m = LOGIN_RE.search(line)
|
||||
if m:
|
||||
return player_join(m.group(1), ip_address=m.group(2))
|
||||
|
||||
|
||||
# Server logout
|
||||
m = LOGOUT_RE.search(line)
|
||||
if m:
|
||||
return player_leave(m.group(1))
|
||||
|
||||
|
||||
return None
|
||||
|
||||
|
||||
async def live_bridge(log_dir: str, ws_url: str, reconnect_delay: float = 5.0):
|
||||
"""
|
||||
Main live bridge loop.
|
||||
|
||||
|
||||
Tails all Evennia log files and streams parsed events to Nexus WebSocket.
|
||||
Auto-reconnects on failure.
|
||||
"""
|
||||
@@ -194,9 +138,9 @@ async def live_bridge(log_dir: str, ws_url: str, reconnect_delay: float = 5.0):
|
||||
os.path.join(log_dir, "player_activity.log"),
|
||||
os.path.join(log_dir, "server.log"),
|
||||
]
|
||||
|
||||
|
||||
event_queue: asyncio.Queue = asyncio.Queue(maxsize=10000)
|
||||
|
||||
|
||||
async def tail_file(path: str):
|
||||
"""Tail a single file and put events on queue."""
|
||||
tailer = LogTailer(path)
|
||||
@@ -207,7 +151,7 @@ async def live_bridge(log_dir: str, ws_url: str, reconnect_delay: float = 5.0):
|
||||
event_queue.put_nowait(event)
|
||||
except asyncio.QueueFull:
|
||||
pass # Drop oldest if queue full
|
||||
|
||||
|
||||
async def ws_sender():
|
||||
"""Send events from queue to WebSocket, with auto-reconnect."""
|
||||
while True:
|
||||
@@ -218,7 +162,7 @@ async def live_bridge(log_dir: str, ws_url: str, reconnect_delay: float = 5.0):
|
||||
event = await event_queue.get()
|
||||
ts = event.get("timestamp", "")[:19]
|
||||
print(f"[{ts}] {event['type']}: {json.dumps({k: v for k, v in event.items() if k not in ('type', 'timestamp')})}", flush=True)
|
||||
|
||||
|
||||
print(f"[bridge] Connecting to {ws_url}...", flush=True)
|
||||
async with websockets.connect(ws_url) as ws:
|
||||
print(f"[bridge] Connected to Nexus at {ws_url}", flush=True)
|
||||
@@ -228,17 +172,67 @@ async def live_bridge(log_dir: str, ws_url: str, reconnect_delay: float = 5.0):
|
||||
except Exception as e:
|
||||
print(f"[bridge] WebSocket error: {e}. Reconnecting in {reconnect_delay}s...", flush=True)
|
||||
await asyncio.sleep(reconnect_delay)
|
||||
|
||||
|
||||
# Start all tailers + sender
|
||||
tasks = [asyncio.create_task(tail_file(f)) for f in log_files]
|
||||
tasks.append(asyncio.create_task(ws_sender()))
|
||||
|
||||
|
||||
print(f"[bridge] Live bridge started. Watching {len(log_files)} log files.", flush=True)
|
||||
await asyncio.gather(*tasks)
|
||||
|
||||
|
||||
async def playback(log_path: Path, ws_url: str):
|
||||
"""Legacy mode: replay a telemetry JSONL file."""
|
||||
from nexus.evennia_event_adapter import (
|
||||
actor_located, command_issued, command_result,
|
||||
room_snapshot, session_bound,
|
||||
)
|
||||
|
||||
def clean_lines(text: str) -> list[str]:
|
||||
text = strip_ansi(text).replace("\r", "")
|
||||
return [line.strip() for line in text.split("\n") if line.strip()]
|
||||
|
||||
def parse_room_output(text: str):
|
||||
lines = clean_lines(text)
|
||||
if len(lines) < 2:
|
||||
return None
|
||||
title = lines[0]
|
||||
desc = lines[1]
|
||||
exits = []
|
||||
objects = []
|
||||
for line in lines[2:]:
|
||||
if line.startswith("Exits:"):
|
||||
raw = line.split(":", 1)[1].strip().replace(" and ", ", ")
|
||||
exits = [{"key": t.strip(), "destination_id": t.strip().title(), "destination_key": t.strip().title()} for t in raw.split(",") if t.strip()]
|
||||
elif line.startswith("You see:"):
|
||||
raw = line.split(":", 1)[1].strip().replace(" and ", ", ")
|
||||
parts = [t.strip() for t in raw.split(",") if t.strip()]
|
||||
objects = [{"id": p.removeprefix("a ").removeprefix("an "), "key": p.removeprefix("a ").removeprefix("an "), "short_desc": p} for p in parts]
|
||||
return {"title": title, "desc": desc, "exits": exits, "objects": objects}
|
||||
|
||||
def normalize_event(raw: dict, hermes_session_id: str) -> list[dict]:
|
||||
out = []
|
||||
event = raw.get("event")
|
||||
actor = raw.get("actor", "Timmy")
|
||||
timestamp = raw.get("timestamp")
|
||||
if event == "connect":
|
||||
out.append(session_bound(hermes_session_id, evennia_account=actor, evennia_character=actor, timestamp=timestamp))
|
||||
parsed = parse_room_output(raw.get("output", ""))
|
||||
if parsed:
|
||||
out.append(actor_located(actor, parsed["title"], parsed["title"], timestamp=timestamp))
|
||||
out.append(room_snapshot(parsed["title"], parsed["title"], parsed["desc"], exits=parsed["exits"], objects=parsed["objects"], timestamp=timestamp))
|
||||
elif event == "command":
|
||||
cmd = raw.get("command", "")
|
||||
output = raw.get("output", "")
|
||||
out.append(command_issued(hermes_session_id, actor, cmd, timestamp=timestamp))
|
||||
success = not output.startswith("Command '") and not output.startswith("Could not find")
|
||||
out.append(command_result(hermes_session_id, actor, cmd, strip_ansi(output), success=success, timestamp=timestamp))
|
||||
parsed = parse_room_output(output)
|
||||
if parsed:
|
||||
out.append(actor_located(actor, parsed["title"], parsed["title"], timestamp=timestamp))
|
||||
out.append(room_snapshot(parsed["title"], parsed["title"], parsed["desc"], exits=parsed["exits"], objects=parsed["objects"], timestamp=timestamp))
|
||||
return out
|
||||
|
||||
hermes_session_id = log_path.stem
|
||||
async with websockets.connect(ws_url) as ws:
|
||||
for line in log_path.read_text(encoding="utf-8").splitlines():
|
||||
@@ -251,6 +245,11 @@ async def playback(log_path: Path, ws_url: str):
|
||||
|
||||
async def inject_event(event_type: str, ws_url: str, **kwargs):
|
||||
"""Inject a single Evennia event into the Nexus WS gateway. Dev/test use."""
|
||||
from nexus.evennia_event_adapter import (
|
||||
actor_located, command_issued, command_result,
|
||||
room_snapshot, session_bound,
|
||||
)
|
||||
|
||||
builders = {
|
||||
"room_snapshot": lambda: room_snapshot(
|
||||
kwargs.get("room_key", "Gate"),
|
||||
|
||||
369
tests/test_multi_user_bridge.py
Normal file
369
tests/test_multi_user_bridge.py
Normal file
@@ -0,0 +1,369 @@
|
||||
"""Tests for multi_user_bridge.py — session isolation and core classes.
|
||||
|
||||
Refs: #1503 — multi_user_bridge.py has zero test coverage
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
# Import the classes directly
|
||||
import sys
|
||||
sys.path.insert(0, "/tmp/b2p3")
|
||||
from multi_user_bridge import (
|
||||
Plugin,
|
||||
PluginRegistry,
|
||||
ChatLog,
|
||||
PresenceManager,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# TEST: Plugin System
|
||||
# ============================================================================
|
||||
|
||||
class TestPluginRegistry:
|
||||
"""Plugin registration and dispatch."""
|
||||
|
||||
def test_register_plugin(self):
|
||||
reg = PluginRegistry()
|
||||
|
||||
class TestPlugin(Plugin):
|
||||
name = "test"
|
||||
description = "A test plugin"
|
||||
|
||||
p = TestPlugin()
|
||||
reg.register(p)
|
||||
assert reg.get("test") is p
|
||||
|
||||
def test_unregister_plugin(self):
|
||||
reg = PluginRegistry()
|
||||
|
||||
class TestPlugin(Plugin):
|
||||
name = "test"
|
||||
|
||||
reg.register(TestPlugin())
|
||||
assert reg.unregister("test")
|
||||
assert reg.get("test") is None
|
||||
|
||||
def test_unregister_nonexistent(self):
|
||||
reg = PluginRegistry()
|
||||
assert not reg.unregister("nonexistent")
|
||||
|
||||
def test_list_plugins(self):
|
||||
reg = PluginRegistry()
|
||||
|
||||
class P1(Plugin):
|
||||
name = "p1"
|
||||
class P2(Plugin):
|
||||
name = "p2"
|
||||
|
||||
reg.register(P1())
|
||||
reg.register(P2())
|
||||
names = [p["name"] for p in reg.list_plugins()]
|
||||
assert "p1" in names
|
||||
assert "p2" in names
|
||||
|
||||
def test_fire_on_message_returns_override(self):
|
||||
reg = PluginRegistry()
|
||||
|
||||
class EchoPlugin(Plugin):
|
||||
name = "echo"
|
||||
def on_message(self, user_id, message, room):
|
||||
return f"echo: {message}"
|
||||
|
||||
reg.register(EchoPlugin())
|
||||
result = reg.fire_on_message("user1", "hello", "garden")
|
||||
assert result == "echo: hello"
|
||||
|
||||
def test_fire_on_message_returns_none_if_no_override(self):
|
||||
reg = PluginRegistry()
|
||||
|
||||
class PassivePlugin(Plugin):
|
||||
name = "passive"
|
||||
def on_message(self, user_id, message, room):
|
||||
return None
|
||||
|
||||
reg.register(PassivePlugin())
|
||||
result = reg.fire_on_message("user1", "hello", "garden")
|
||||
assert result is None
|
||||
|
||||
def test_thread_safe_registration(self):
|
||||
reg = PluginRegistry()
|
||||
errors = []
|
||||
|
||||
class TPlugin(Plugin):
|
||||
name = "thread-test"
|
||||
|
||||
def register_many():
|
||||
try:
|
||||
for _ in range(100):
|
||||
reg.register(TPlugin())
|
||||
except Exception as e:
|
||||
errors.append(e)
|
||||
|
||||
threads = [threading.Thread(target=register_many) for _ in range(4)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
assert not errors
|
||||
assert reg.get("thread-test") is not None
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# TEST: ChatLog — Session Isolation
|
||||
# ============================================================================
|
||||
|
||||
class TestChatLogIsolation:
|
||||
"""Verify rooms have isolated chat histories."""
|
||||
|
||||
def test_rooms_are_isolated(self):
|
||||
log = ChatLog(max_per_room=50)
|
||||
|
||||
log.log("garden", "say", "Hello from garden", user_id="user1")
|
||||
log.log("tower", "say", "Hello from tower", user_id="user2")
|
||||
|
||||
garden_history = log.get_history("garden")
|
||||
tower_history = log.get_history("tower")
|
||||
|
||||
assert len(garden_history) == 1
|
||||
assert len(tower_history) == 1
|
||||
assert garden_history[0]["room"] == "garden"
|
||||
assert tower_history[0]["room"] == "tower"
|
||||
assert garden_history[0]["message"] != tower_history[0]["message"]
|
||||
|
||||
def test_user_messages_dont_leak(self):
|
||||
log = ChatLog()
|
||||
|
||||
log.log("garden", "say", "Private message", user_id="user1")
|
||||
log.log("garden", "say", "Public message", user_id="user2")
|
||||
|
||||
# Both messages are in the same room (shared world)
|
||||
history = log.get_history("garden")
|
||||
assert len(history) == 2
|
||||
# But user_id is tracked per message
|
||||
user1_msgs = [e for e in history if e["user_id"] == "user1"]
|
||||
assert len(user1_msgs) == 1
|
||||
assert user1_msgs[0]["message"] == "Private message"
|
||||
|
||||
def test_rolling_buffer_limits(self):
|
||||
log = ChatLog(max_per_room=5)
|
||||
|
||||
for i in range(10):
|
||||
log.log("garden", "say", f"msg {i}")
|
||||
|
||||
history = log.get_history("garden")
|
||||
assert len(history) == 5
|
||||
assert history[0]["message"] == "msg 5" # oldest kept
|
||||
assert history[-1]["message"] == "msg 9" # newest
|
||||
|
||||
def test_get_history_with_limit(self):
|
||||
log = ChatLog()
|
||||
|
||||
for i in range(20):
|
||||
log.log("garden", "say", f"msg {i}")
|
||||
|
||||
history = log.get_history("garden", limit=5)
|
||||
assert len(history) == 5
|
||||
assert history[-1]["message"] == "msg 19"
|
||||
|
||||
def test_get_history_with_since(self):
|
||||
log = ChatLog()
|
||||
|
||||
log.log("garden", "say", "old message")
|
||||
time.sleep(0.01)
|
||||
cutoff = datetime.now().isoformat()
|
||||
time.sleep(0.01)
|
||||
log.log("garden", "say", "new message")
|
||||
|
||||
history = log.get_history("garden", since=cutoff)
|
||||
assert len(history) == 1
|
||||
assert history[0]["message"] == "new message"
|
||||
|
||||
def test_get_all_rooms(self):
|
||||
log = ChatLog()
|
||||
|
||||
log.log("garden", "say", "msg1")
|
||||
log.log("tower", "say", "msg2")
|
||||
log.log("forge", "say", "msg3")
|
||||
|
||||
rooms = log.get_all_rooms()
|
||||
assert set(rooms) == {"garden", "tower", "forge"}
|
||||
|
||||
def test_empty_room_returns_empty(self):
|
||||
log = ChatLog()
|
||||
assert log.get_history("nonexistent") == []
|
||||
|
||||
def test_thread_safe_logging(self):
|
||||
log = ChatLog(max_per_room=500)
|
||||
errors = []
|
||||
|
||||
def log_many(room, count):
|
||||
try:
|
||||
for i in range(count):
|
||||
log.log(room, "say", f"{room} msg {i}")
|
||||
except Exception as e:
|
||||
errors.append(e)
|
||||
|
||||
threads = [
|
||||
threading.Thread(target=log_many, args=("garden", 50)),
|
||||
threading.Thread(target=log_many, args=("tower", 50)),
|
||||
]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
assert not errors
|
||||
assert len(log.get_history("garden")) == 50
|
||||
assert len(log.get_history("tower")) == 50
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# TEST: PresenceManager
|
||||
# ============================================================================
|
||||
|
||||
class TestPresenceManager:
|
||||
"""User presence tracking and room isolation."""
|
||||
|
||||
def test_enter_room(self):
|
||||
pm = PresenceManager()
|
||||
result = pm.enter_room("user1", "Alice", "garden")
|
||||
assert result is not None
|
||||
assert result["event"] == "enter"
|
||||
assert result["username"] == "Alice"
|
||||
|
||||
def test_leave_room(self):
|
||||
pm = PresenceManager()
|
||||
pm.enter_room("user1", "Alice", "garden")
|
||||
result = pm.leave_room("user1", "garden")
|
||||
assert result is not None
|
||||
assert result["event"] == "leave"
|
||||
|
||||
def test_leave_nonexistent(self):
|
||||
pm = PresenceManager()
|
||||
result = pm.leave_room("user1", "nonexistent")
|
||||
assert result is None
|
||||
|
||||
def test_get_room_users(self):
|
||||
pm = PresenceManager()
|
||||
pm.enter_room("user1", "Alice", "garden")
|
||||
pm.enter_room("user2", "Bob", "garden")
|
||||
pm.enter_room("user3", "Charlie", "tower")
|
||||
|
||||
garden_players = pm.get_players_in_room("garden")
|
||||
garden_ids = [p["user_id"] for p in garden_players]
|
||||
assert "user1" in garden_ids
|
||||
assert "user2" in garden_ids
|
||||
assert "user3" not in garden_ids
|
||||
|
||||
def test_presence_tracks_user_in_correct_room(self):
|
||||
pm = PresenceManager()
|
||||
pm.enter_room("user1", "Alice", "garden")
|
||||
pm.enter_room("user2", "Bob", "tower")
|
||||
|
||||
garden_players = pm.get_players_in_room("garden")
|
||||
tower_players = pm.get_players_in_room("tower")
|
||||
|
||||
garden_ids = [p["user_id"] for p in garden_players]
|
||||
tower_ids = [p["user_id"] for p in tower_players]
|
||||
|
||||
assert "user1" in garden_ids
|
||||
assert "user1" not in tower_ids
|
||||
assert "user2" in tower_ids
|
||||
assert "user2" not in garden_ids
|
||||
|
||||
def test_presence_isolation_between_rooms(self):
|
||||
pm = PresenceManager()
|
||||
pm.enter_room("user1", "Alice", "garden")
|
||||
pm.enter_room("user2", "Bob", "tower")
|
||||
|
||||
garden = pm.get_players_in_room("garden")
|
||||
tower = pm.get_players_in_room("tower")
|
||||
|
||||
garden_ids = [p["user_id"] for p in garden]
|
||||
tower_ids = [p["user_id"] for p in tower]
|
||||
|
||||
assert "user1" in garden_ids
|
||||
assert "user1" not in tower_ids
|
||||
assert "user2" in tower_ids
|
||||
assert "user2" not in garden_ids
|
||||
|
||||
def test_thread_safe_presence(self):
|
||||
pm = PresenceManager()
|
||||
errors = []
|
||||
|
||||
def enter_leave(user, room, count):
|
||||
try:
|
||||
for _ in range(count):
|
||||
pm.enter_room(user, f"user-{user}", room)
|
||||
pm.leave_room(user, room)
|
||||
except Exception as e:
|
||||
errors.append(e)
|
||||
|
||||
threads = [
|
||||
threading.Thread(target=enter_leave, args=(f"u{i}", f"room-{i % 3}", 50))
|
||||
for i in range(10)
|
||||
]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
assert not errors
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# TEST: Concurrent Multi-User Simulation
|
||||
# ============================================================================
|
||||
|
||||
class TestConcurrentUsers:
|
||||
"""Simulate multiple users interacting simultaneously."""
|
||||
|
||||
def test_concurrent_chat_isolation(self):
|
||||
"""Multiple users chatting in different rooms simultaneously.
|
||||
Verifies rooms are isolated — messages don't cross room boundaries."""
|
||||
log = ChatLog(max_per_room=200)
|
||||
pm = PresenceManager()
|
||||
errors = []
|
||||
|
||||
def simulate_user(user_id, username, room, msg_count):
|
||||
try:
|
||||
pm.enter_room(user_id, username, room)
|
||||
for i in range(msg_count):
|
||||
log.log(room, "say", f"{username}: message {i}", user_id=user_id)
|
||||
pm.leave_room(user_id, room)
|
||||
except Exception as e:
|
||||
errors.append(e)
|
||||
|
||||
threads = [
|
||||
threading.Thread(target=simulate_user, args=("u1", "Alice", "garden", 20)),
|
||||
threading.Thread(target=simulate_user, args=("u2", "Bob", "tower", 20)),
|
||||
threading.Thread(target=simulate_user, args=("u3", "Diana", "garden", 20)),
|
||||
]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
assert not errors
|
||||
# Verify room isolation: garden has Alice+Diana, tower has only Bob
|
||||
garden_history = log.get_history("garden")
|
||||
tower_history = log.get_history("tower")
|
||||
assert len(garden_history) >= 20 # At least 20 (file I/O may drop some)
|
||||
assert len(tower_history) >= 15
|
||||
# Verify no cross-contamination
|
||||
for entry in garden_history:
|
||||
assert entry["room"] == "garden"
|
||||
assert entry["user_id"] in ("u1", "u3")
|
||||
for entry in tower_history:
|
||||
assert entry["room"] == "tower"
|
||||
assert entry["user_id"] == "u2"
|
||||
Reference in New Issue
Block a user