59 lines
2.9 KiB
Python
59 lines
2.9 KiB
Python
import os
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
import unittest
|
|
|
|
from app.analytics_cache import AnalyticsSnapshotCache, SUMMARY_WINDOWS
|
|
from app.live import TrafficHistory
|
|
from app.store import AlertStore
|
|
|
|
|
|
class AnalyticsCacheTests(unittest.TestCase):
|
|
def test_refresh_persists_all_dashboard_windows_in_history_cache(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
store = AlertStore(os.path.join(td, "ids.db"))
|
|
history = TrafficHistory("", retention_hours=24, max_events=1000, memory_events=1000)
|
|
history.add({"id":"a","ts_ms":int(time.time()*1000),"timestamp":"x","type":"flow","src_ip":"10.0.0.2","dest_ip":"1.1.1.1","proto":"TCP","app_proto":"tls","direction":"outbound","bytes":50})
|
|
cache = AnalyticsSnapshotCache(store, history, threading.Event(), interval_seconds=60)
|
|
cache.refresh_all()
|
|
status = cache.status()
|
|
self.assertEqual({row["window_seconds"] for row in status["persisted"]}, set(SUMMARY_WINDOWS))
|
|
snapshot = cache.get(900)
|
|
self.assertEqual(snapshot["events"], 1)
|
|
self.assertEqual(snapshot["snapshot_source"], "redis-cache")
|
|
store.close()
|
|
|
|
def test_legacy_sqlite_snapshot_is_not_used_for_dashboard_history(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
store = AlertStore(os.path.join(td, "ids.db"))
|
|
history = TrafficHistory("", retention_hours=24, max_events=1000, memory_events=1000)
|
|
store.save_traffic_snapshot(900, {"events": 7, "timeline": [{"bucket": 1, "events": 7}]})
|
|
cache = AnalyticsSnapshotCache(store, history, threading.Event(), interval_seconds=60)
|
|
cache.refresh_all()
|
|
snapshot = cache.get(900)
|
|
self.assertIsNotNone(snapshot)
|
|
self.assertEqual(snapshot["events"], 0)
|
|
# The in-memory backend is test/dev-only, so it intentionally marks
|
|
# analytics incomplete. The important regression is that SQLite's
|
|
# stale value is not selected as the dashboard snapshot.
|
|
self.assertFalse(snapshot["analytics_complete"])
|
|
self.assertEqual(snapshot["snapshot_source"], "redis-cache")
|
|
# Old SQLite traffic snapshots may exist after an upgrade, but they
|
|
# are no longer a data source for the dashboard.
|
|
self.assertEqual(store.traffic_snapshot(900)["events"], 7)
|
|
store.close()
|
|
|
|
def test_clear_traffic_snapshots_removes_persisted_windows(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
store = AlertStore(os.path.join(td, "ids.db"))
|
|
store.save_traffic_snapshot(900, {"events": 1})
|
|
store.save_traffic_snapshot(3600, {"events": 2})
|
|
self.assertEqual(store.clear_traffic_snapshots(), 2)
|
|
self.assertEqual(store.traffic_snapshot_status()["windows"], [])
|
|
store.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|