nomadro/apps/api/tests/test_public_config_snapshot.py
Eric 308974bf5e Harden platform upgrade: ops admin, live config, shared service proxy, and smoke deploys.
Ship Operations console polish, PocketBase social fixtures, and portal join-leads without local DBs or probe scripts.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 01:20:55 +08:00

116 lines
5.5 KiB
Python

"""Isolated tests: temporary JSON only, no app startup or database connections."""
import json
import asyncio
import importlib.util
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from unittest.mock import AsyncMock, Mock
from types import SimpleNamespace
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "services"))
from ebook_svc.services.public_config_snapshot import PublicConfigSnapshot
class PublicConfigSnapshotTests(unittest.TestCase):
def test_websocket_disconnect_cancels_output_task(self):
router = self.load_router()
from fastapi import WebSocketDisconnect
async def run():
queue = asyncio.Queue()
fanout = SimpleNamespace(register=lambda: queue, unregister=Mock())
ws = SimpleNamespace(accept=AsyncMock(), send_text=AsyncMock(), receive_text=AsyncMock(side_effect=WebSocketDisconnect()), close=AsyncMock())
with patch.object(router, 'fanout', fanout), patch.object(router, 'read_config_meta', return_value={'version': 1}), patch.object(router, 'notify_config_changed', side_effect=lambda meta, **kwargs: meta):
await asyncio.wait_for(router.public_remote_config_ws(ws), timeout=1)
fanout.unregister.assert_called_once_with(queue)
self.assertFalse(any('pump_out' in task.get_coro().__qualname__ for task in asyncio.all_tasks()))
asyncio.run(run())
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.path = Path(self.directory.name) / "config.json"
self.reader = PublicConfigSnapshot()
def write(self, value):
self.path.write_text(json.dumps(value), encoding="utf-8")
def test_unchanged_file_is_not_parsed_again(self):
self.write({"version": 10, "flags": {"payEnabled": False}})
first = self.reader.read(self.path)
first["flags"]["payEnabled"] = True
with patch.object(Path, "read_text", side_effect=AssertionError("read again")):
self.assertFalse(self.reader.read(self.path)["flags"]["payEnabled"])
def test_update_visible_immediately(self):
self.write({"version": 1})
self.assertEqual(self.reader.read(self.path)["version"], 1)
replacement = self.path.with_suffix(".new")
replacement.write_text('{"version": 222}', encoding="utf-8")
replacement.replace(self.path)
self.assertEqual(self.reader.read(self.path)["version"], 222)
def test_partial_write_and_missing_file_keep_last_good_config(self):
self.write({"version": 9, "modules": {"vip": {"enabled": False}}})
expected = self.reader.read(self.path)
for text in ('{"version":', '[]', '\ufffd'):
self.path.write_text(text, encoding="utf-8")
self.assertEqual(self.reader.read(self.path), expected)
self.path.unlink()
self.assertEqual(self.reader.read(self.path), expected)
self.write({"version": 123})
self.assertEqual(self.reader.read(self.path)["version"], 123)
def test_new_path_does_not_reuse_old_config(self):
self.write({"version": 99})
self.reader.read(self.path)
empty = self.reader.read(self.path.with_name("missing.json"))
self.assertEqual(empty["version"], 1)
self.assertEqual(empty["modules"], {})
def test_changing_file_during_read_does_not_replace_snapshot(self):
self.write({"version": 9})
self.reader.read(self.path)
self.write({"version": 100})
with patch.object(self.reader, "_stat", side_effect=[(1, 2, 3), (4, 5, 6)]):
self.assertEqual(self.reader.read(self.path)["version"], 9)
def load_router(self):
# Avoid importing settings/app startup: neither real databases nor live APIs.
target = Path(__file__).resolve().parents[1] / "services/ebook_svc/routers/public_config.py"
spec = importlib.util.spec_from_file_location("public_config_under_test", target)
module = importlib.util.module_from_spec(spec)
with patch.dict(sys.modules, {
"ebook_svc.services.tt_platform_config": SimpleNamespace(resolve_config_file=lambda: self.path),
}):
spec.loader.exec_module(module)
return module
def test_public_response_preserves_envelope_headers_and_aliases(self):
config = {"version": 7, "updatedAt": "now", "flags": {"payEnabled": False}}
self.write(config)
router = self.load_router()
response = asyncio.run(router.public_remote_config())
self.assertEqual(json.loads(response.body), {"ok": True, "source": "file", "config": config})
self.assertIn("no-store", response.headers["cache-control"])
self.assertEqual(response.headers["access-control-allow-origin"], "*")
self.assertEqual({route.path for route in router.router.routes}, {
"/api/config", "/api/ebook/config", "/api/config/meta", "/api/ebook/config/meta",
"/api/config/pull", "/api/ebook/config/pull", "/api/config/stream", "/api/ebook/config/stream",
"/api/config/ws", "/api/ebook/config/ws",
})
def test_meta_handles_malformed_version_without_server_error(self):
self.write({"version": {"unexpected": True}})
router = self.load_router()
response = asyncio.run(router.public_remote_config_meta())
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.body)["version"], 0)
if __name__ == "__main__":
unittest.main()