import json from concurrent.futures import ThreadPoolExecutor from types import SimpleNamespace import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from k1link.scene_profiles import ProfileConflict, SceneProfileStore from k1link.web.scene_profiles_api import build_scene_profiles_router def scene(color="#ffffff"): return { "schema": "missioncore.battery-scene/v1", "model": "catl-r04/v1", "materials": {"case": {"color": color}}, "postFx": {"grid": {"enabled": False}}, "assignments": {}, "camera": {"distance": 1.2}, "editorLayout": {"windows": {}}, } def test_persistent_roundtrip_and_backup(tmp_path): store = SceneProfileStore(tmp_path) assert store.read("battery", "device")["document"] is None assert not tmp_path.joinpath("battery").exists() first = store.save("battery", "device", scene(), 0) assert SceneProfileStore(tmp_path).read("battery", "device") == first second = store.save("battery", "device", scene("#aaaaaa"), 1) assert second["revision"] == 2 assert ( json.loads(store.path("battery", "device").with_name("meta.previous.json").read_text()) == first ) assert store.save("battery", "device", scene("#aaaaaa"), 2) == second with pytest.raises(ProfileConflict): store.save("battery", "device", scene(), 1) assert store.read("battery", "device") == second def test_corrupt_profile_never_becomes_defaults(tmp_path): store = SceneProfileStore(tmp_path) store.save("battery", "device", scene(), 0) path = store.path("battery", "device") path.write_text("broken file") with pytest.raises(ValueError): store.read("battery", "device") with pytest.raises(ValueError): store.save("battery", "device", scene(), 0) assert path.read_text() == "broken file" def test_atomic_failure_preserves_last_saved_document(tmp_path, monkeypatch): store = SceneProfileStore(tmp_path) first = store.save("battery", "a", scene(), 0) import k1link.scene_profiles as module replace = module.os.replace def fail(source, destination): if destination.name == "meta.json": raise OSError("disk full") return replace(source, destination) monkeypatch.setattr(module.os, "replace", fail) with pytest.raises(OSError): store.save("battery", "a", scene("#111111"), 1) assert store.read("battery", "a") == first assert not list(tmp_path.rglob("*.tmp")) def test_competing_browsers_cannot_overwrite_each_other(tmp_path): store = SceneProfileStore(tmp_path) store.save("battery", "device", scene(), 0) def writer(color): try: return store.save("battery", "device", scene(color), 1)["revision"] except ProfileConflict: return "conflict" with ThreadPoolExecutor(max_workers=2) as pool: results = list(pool.map(writer, ["#aaaaaa", "#bbbbbb"])) assert sorted(map(str, results)) == ["2", "conflict"] def test_path_isolation_and_schema_checks(tmp_path): store = SceneProfileStore(tmp_path) store.save("battery", "../anything", scene(), 0) assert store.path("battery", "../anything").is_relative_to(tmp_path) assert store.read("battery", "other")["document"] is None assert store.read("rover", "../anything")["document"] is None with pytest.raises(ValueError): store.save("rover", "a", scene(), 0) with pytest.raises(ValueError): store.save("battery", "a", scene(), True) def client(root): app = FastAPI() app.state.fleet = SimpleNamespace() app.include_router(build_scene_profiles_router(lambda: root)) return TestClient(app, base_url="http://127.0.0.1:8000", client=("127.0.0.1", 5555)) def test_api_cross_browser_read_and_stale_write(tmp_path): a = client(tmp_path) b = client(tmp_path) url = "/api/v1/scene-profiles/battery?owner=device" assert a.get(url).json() == {"revision": 0, "document": None} saved = a.put(url, json={"document": scene(), "expected_revision": 0}) assert saved.status_code == 200 assert b.get(url).json() == saved.json() assert ( b.put(url, json={"document": scene("#000000"), "expected_revision": 0}).status_code == 409 ) assert a.get(url).headers["cache-control"] == "no-store" assert ( a.put( url, json={"document": scene(), "expected_revision": 1}, headers={"Origin": "https://evil.invalid"}, ).status_code == 403 ) assert a.get(url, headers={"Sec-Fetch-Site": "cross-site"}).status_code == 403