from __future__ import annotations import pytest from django.core.cache import cache from odm import PropagationError from yksa_orbital import model_config as mc @pytest.fixture(autouse=True) def _clear_cache(): cache.delete(mc.CACHE_KEY) yield cache.delete(mc.CACHE_KEY) class _Backend: def __init__(self, result=None, error=None): self.result = result self.error = error self.calls = 0 def model_config(self): self.calls += 1 if self.error: raise self.error return self.result def test_the_model_is_read_once_and_cached(monkeypatch): backend = _Backend({"decay": {"altitude_km": 105.0}}) monkeypatch.setattr(mc, "get_backend", lambda name=None: backend) assert mc.model_config()["decay"]["altitude_km"] == 105.0 mc.model_config() assert backend.calls == 1 def test_an_unreachable_sidecar_falls_back_without_raising(monkeypatch): backend = _Backend(error=PropagationError("unreachable")) monkeypatch.setattr(mc, "get_backend", lambda name=None: backend) assert mc.model_config()["unavailable"] is True def test_the_failure_is_cached_too(monkeypatch): """Otherwise a sidecar that is down costs a connection attempt on every page render -- and against an unresolvable hostname each one is a DNS timeout, so a caption takes the page down instead of degrading.""" backend = _Backend(error=PropagationError("unreachable")) monkeypatch.setattr(mc, "get_backend", lambda name=None: backend) mc.model_config() mc.model_config() mc.model_config() assert backend.calls == 1 def test_a_local_override_wins_over_the_sidecar(monkeypatch, settings): """When this deployment overrides a knob it really is flying something else, and a caption reading the sidecar's value would describe a different run.""" backend = _Backend({"decay": {"altitude_km": 105.0}}) monkeypatch.setattr(mc, "get_backend", lambda name=None: backend) settings.DECAY_ALTITUDE_KM = 120.0 assert mc.setting("decay", "altitude_km") == 120.0 def test_an_unset_override_reads_the_sidecar(monkeypatch, settings): backend = _Backend({"decay": {"altitude_km": 105.0}}) monkeypatch.setattr(mc, "get_backend", lambda name=None: backend) settings.DECAY_ALTITUDE_KM = None assert mc.setting("decay", "altitude_km") == 105.0