"""instance_dashboard_cache 单元测试."""
from __future__ import annotations

import time
import unittest

from lib.instance.instance_dashboard_cache import InstanceDashboardStore


class TestInstanceDashboardStore(unittest.TestCase):
    def test_snapshot_before_ready(self):
        store = InstanceDashboardStore()
        snap = store.snapshot_dict()
        self.assertFalse(snap["ok"])
        self.assertIn("尚未就绪", snap["msg"])

    def test_aggregate_and_snapshot(self):
        store = InstanceDashboardStore()
        calls = {"n": 0}

        def build():
            calls["n"] += 1
            return {"ok": True, "updated_at": "t1", "orders": {"count": 0, "items": []}}

        store.start(build)
        deadline = time.time() + 3
        while time.time() < deadline:
            snap = store.snapshot_dict()
            if snap.get("ok") and snap.get("dashboard_version", 0) >= 1:
                break
            time.sleep(0.05)
        snap = store.snapshot_dict()
        self.assertTrue(snap["ok"])
        self.assertGreaterEqual(snap["dashboard_version"], 1)
        self.assertGreaterEqual(calls["n"], 1)
        store.request_refresh()
        ver0 = snap["dashboard_version"]
        deadline = time.time() + 3
        while time.time() < deadline:
            if store.snapshot_dict().get("dashboard_version", 0) > ver0:
                break
            time.sleep(0.05)
        self.assertGreater(store.snapshot_dict()["dashboard_version"], ver0)
        store.stop()


if __name__ == "__main__":
    unittest.main()
