|
| 1 | +"""Unit tests for history time-bucket width helper. |
| 2 | +
|
| 3 | +Credit: javastraat/meshpoint ``b10610a``. |
| 4 | +""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import unittest |
| 9 | +from datetime import datetime, timedelta, timezone |
| 10 | + |
| 11 | +from src.models.telemetry import Telemetry |
| 12 | +from src.storage.database import DatabaseManager |
| 13 | +from src.storage.telemetry_repository import TelemetryRepository |
| 14 | +from src.storage.time_bucket import bucket_seconds |
| 15 | + |
| 16 | + |
| 17 | +class BucketSecondsTest(unittest.TestCase): |
| 18 | + def test_uses_actual_span_not_requested_hours(self): |
| 19 | + lo = datetime(2026, 1, 1, tzinfo=timezone.utc) |
| 20 | + hi = lo + timedelta(hours=2) |
| 21 | + secs = bucket_seconds( |
| 22 | + {"lo": lo.isoformat(), "hi": hi.isoformat()}, |
| 23 | + limit=10, |
| 24 | + hours=100000, |
| 25 | + ) |
| 26 | + self.assertEqual(secs, max(60, int((2 * 3600) / 10))) |
| 27 | + |
| 28 | + def test_falls_back_to_hours_when_no_span(self): |
| 29 | + self.assertEqual(bucket_seconds(None, limit=10, hours=1), 360) |
| 30 | + |
| 31 | + def test_floor_at_sixty_seconds(self): |
| 32 | + lo = datetime(2026, 1, 1, tzinfo=timezone.utc) |
| 33 | + hi = lo + timedelta(seconds=30) |
| 34 | + self.assertEqual( |
| 35 | + bucket_seconds( |
| 36 | + {"lo": lo.isoformat(), "hi": hi.isoformat()}, |
| 37 | + limit=100, |
| 38 | + hours=1, |
| 39 | + ), |
| 40 | + 60, |
| 41 | + ) |
| 42 | + |
| 43 | + |
| 44 | +class TelemetryHistoryBucketTest(unittest.IsolatedAsyncioTestCase): |
| 45 | + async def asyncSetUp(self): |
| 46 | + self.db = DatabaseManager(":memory:") |
| 47 | + await self.db.connect() |
| 48 | + self.repo = TelemetryRepository(self.db) |
| 49 | + |
| 50 | + async def asyncTearDown(self): |
| 51 | + await self.db.disconnect() |
| 52 | + |
| 53 | + async def test_hours_path_keeps_newest_when_over_limit(self): |
| 54 | + now = datetime.now(timezone.utc) |
| 55 | + for i in range(20): |
| 56 | + await self.repo.insert( |
| 57 | + Telemetry( |
| 58 | + node_id="n1", |
| 59 | + temperature=float(i), |
| 60 | + timestamp=now - timedelta(minutes=19 - i), |
| 61 | + ) |
| 62 | + ) |
| 63 | + rows = await self.repo.get_history("n1", limit=5, hours=24) |
| 64 | + self.assertLessEqual(len(rows), 5) |
| 65 | + self.assertGreaterEqual(rows[-1].temperature, 15.0) |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + unittest.main() |
0 commit comments