Files
NODEDC_MISSION_CORE/tests/test_scene_profiles.py

160 lines
6.4 KiB
Python

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
def test_observation_views_survive_new_clients_without_browser_storage(tmp_path):
camera = dict(longitude=37, latitude=55, height=600, heading=137, pitch=-28, roll=3)
document = {"schema": "missioncore.observation-map/v1", "camera": camera,
"layers": dict(imagery=True, terrain=True, buildings=False,
grid=False, targets=True)}
a = client(tmp_path)
url = "/api/v1/scene-profiles/observation-map?owner=rover-006"
assert a.put(url, json={"document": document, "expected_revision": 0}).status_code == 200
assert client(tmp_path).get(url).json()["document"] == document
assert client(tmp_path).get(url.replace("rover-006", "other")).json()["document"] is None
model = {"schema": "missioncore.rover-view/v1", "model": "dcd006-v022"}
url = "/api/v1/scene-profiles/rover-view?owner=rover-006"
assert a.put(url, json={"document": model, "expected_revision": 0}).status_code == 200
assert client(tmp_path).get(url).json()["document"] == model
model["armed"] = True
assert a.put(url, json={"document": model, "expected_revision": 1}).status_code == 422
@pytest.mark.parametrize("field,value", [("pitch", -100), ("height", True),
("longitude", 200), ("heading", "30")])
def test_observation_map_rejects_bad_pose(tmp_path, field, value):
camera = dict(longitude=37, latitude=55, height=600, heading=137, pitch=-28, roll=3)
camera[field] = value
document = {"schema": "missioncore.observation-map/v1", "camera": camera,
"layers": dict(imagery=True, terrain=True, buildings=False,
grid=False, targets=True)}
with pytest.raises(ValueError):
SceneProfileStore(tmp_path).save("observation-map", "rover", document, 0)
assert not SceneProfileStore(tmp_path).path("observation-map", "rover").exists()