|
| 1 | +# fmt: off |
| 2 | +""" |
| 3 | +History Chunking Tests |
| 4 | +
|
| 5 | +Tests for fetching long history windows from Home Assistant in time-ordered chunks |
| 6 | +rather than one request, so only one chunk's response is resident at a time: |
| 7 | +- get_history() splits long windows and covers them exactly |
| 8 | +- the synthesised record Home Assistant returns at each chunk start is dropped |
| 9 | +""" |
| 10 | + |
| 11 | +from datetime import datetime, timedelta, timezone |
| 12 | + |
| 13 | +from tests.test_hainterface_common import MockBase, create_ha_interface |
| 14 | + |
| 15 | + |
| 16 | +NOW = datetime(2026, 8, 16, 12, 0, 0, tzinfo=timezone.utc) |
| 17 | + |
| 18 | + |
| 19 | +def _interface(): |
| 20 | + """Build an HAInterface against the shared mock base.""" |
| 21 | + return create_ha_interface(MockBase(), ha_key="test_key", db_enable=False, db_mirror_ha=False, db_primary=False) |
| 22 | + |
| 23 | + |
| 24 | +def _record(stamp, state): |
| 25 | + """Build one history record.""" |
| 26 | + return {"state": state, "last_updated": stamp.isoformat(), "attributes": {"unit_of_measurement": "W"}} |
| 27 | + |
| 28 | + |
| 29 | +def _capture(interface, responder): |
| 30 | + """Point api_call at a responder and record the windows requested.""" |
| 31 | + calls = [] |
| 32 | + |
| 33 | + def api_call(endpoint, data_in=None, **kwargs): |
| 34 | + """Stand in for the REST call, recording the requested window.""" |
| 35 | + start = endpoint.rsplit("/", 1)[1] |
| 36 | + calls.append((start, data_in.get("end_time"))) |
| 37 | + return responder(start, data_in.get("end_time")) |
| 38 | + |
| 39 | + interface.api_call = api_call |
| 40 | + return calls |
| 41 | + |
| 42 | + |
| 43 | +def test_get_history_drops_synthesised_boundary_record(my_predbat=None): |
| 44 | + """Home Assistant's state-at-window-start record must not be added twice""" |
| 45 | + print("\n=== Testing get_history() boundary record handling ===") |
| 46 | + failed = 0 |
| 47 | + |
| 48 | + interface = _interface() |
| 49 | + |
| 50 | + def responder(start, end): |
| 51 | + """Return a synthesised record at the window start plus one real record.""" |
| 52 | + start_dt = datetime.fromisoformat(start) |
| 53 | + # Home Assistant reports the state in effect at start_time, exactly on the boundary |
| 54 | + # and with no sub-second precision, then any real changes within the window |
| 55 | + return [[_record(start_dt, "500"), _record(start_dt + timedelta(hours=1), "600")]] |
| 56 | + |
| 57 | + _capture(interface, responder) |
| 58 | + |
| 59 | + result = interface.get_history("sensor.load_power", NOW, days=9, chunk_days=3) |
| 60 | + |
| 61 | + if not result or not result[0]: |
| 62 | + print("ERROR: expected history back, got {}".format(result)) |
| 63 | + return failed + 1 |
| 64 | + |
| 65 | + items = result[0] |
| 66 | + stamps = [item["last_updated"] for item in items] |
| 67 | + if len(stamps) != len(set(stamps)): |
| 68 | + duplicates = sorted({s for s in stamps if stamps.count(s) > 1}) |
| 69 | + print("ERROR: chunk boundaries duplicated records: {}".format(duplicates)) |
| 70 | + failed += 1 |
| 71 | + else: |
| 72 | + print("✓ no duplicate timestamps across chunk boundaries") |
| 73 | + |
| 74 | + # 3 chunks: chunk 1 contributes both records, chunks 2 and 3 contribute only their real one |
| 75 | + if len(items) != 4: |
| 76 | + print("ERROR: expected 4 records (2 from the first chunk, 1 from each later chunk), got {}".format(len(items))) |
| 77 | + print(" records: {}".format(stamps)) |
| 78 | + failed += 1 |
| 79 | + else: |
| 80 | + print("✓ synthesised boundary record dropped for chunks after the first") |
| 81 | + |
| 82 | + if stamps != sorted(stamps): |
| 83 | + print("ERROR: records not in oldest-first order: {}".format(stamps)) |
| 84 | + failed += 1 |
| 85 | + else: |
| 86 | + print("✓ records stay oldest-first across chunks") |
| 87 | + |
| 88 | + return failed |
| 89 | + |
| 90 | + |
| 91 | +def test_get_history_short_window_makes_one_request(my_predbat=None): |
| 92 | + """A window inside the chunk size is fetched in a single request as before""" |
| 93 | + print("\n=== Testing get_history() short window ===") |
| 94 | + failed = 0 |
| 95 | + |
| 96 | + interface = _interface() |
| 97 | + calls = _capture(interface, lambda start, end: [[_record(NOW - timedelta(hours=1), "500")]]) |
| 98 | + |
| 99 | + interface.get_history("sensor.load_power", NOW, days=2, chunk_days=7) |
| 100 | + |
| 101 | + if len(calls) != 1: |
| 102 | + print("ERROR: expected 1 request for a 2 day window, got {}".format(len(calls))) |
| 103 | + failed += 1 |
| 104 | + else: |
| 105 | + print("✓ short window still fetched in one request") |
| 106 | + |
| 107 | + return failed |
| 108 | + |
| 109 | + |
| 110 | +def test_get_history_chunks_cover_the_window_exactly(my_predbat=None): |
| 111 | + """Chunks tile the requested window end to end with no gaps or overlap""" |
| 112 | + print("\n=== Testing get_history() window coverage ===") |
| 113 | + failed = 0 |
| 114 | + |
| 115 | + interface = _interface() |
| 116 | + calls = _capture(interface, lambda start, end: [[_record(datetime.fromisoformat(start) + timedelta(hours=1), "500")]]) |
| 117 | + |
| 118 | + interface.get_history("sensor.load_power", NOW, days=10, chunk_days=3) |
| 119 | + |
| 120 | + if len(calls) != 4: |
| 121 | + print("ERROR: expected 4 chunks for 10 days at 3 days each, got {}".format(len(calls))) |
| 122 | + return failed + 1 |
| 123 | + print("✓ 10 day window split into 4 chunks of at most 3 days") |
| 124 | + |
| 125 | + starts = [datetime.fromisoformat(start) for start, _ in calls] |
| 126 | + ends = [datetime.fromisoformat(end) for _, end in calls] |
| 127 | + |
| 128 | + if starts[0] != NOW - timedelta(days=10): |
| 129 | + print("ERROR: first chunk starts at {}, expected {}".format(starts[0], NOW - timedelta(days=10))) |
| 130 | + failed += 1 |
| 131 | + elif ends[-1] != NOW: |
| 132 | + print("ERROR: last chunk ends at {}, expected {}".format(ends[-1], NOW)) |
| 133 | + failed += 1 |
| 134 | + else: |
| 135 | + print("✓ chunks span exactly the requested window") |
| 136 | + |
| 137 | + for index in range(1, len(starts)): |
| 138 | + if starts[index] != ends[index - 1]: |
| 139 | + print("ERROR: chunk {} starts at {} but previous ended at {}".format(index, starts[index], ends[index - 1])) |
| 140 | + failed += 1 |
| 141 | + break |
| 142 | + else: |
| 143 | + print("✓ chunks are contiguous with no gaps or overlap") |
| 144 | + |
| 145 | + if max((ends[i] - starts[i]) for i in range(len(starts))) > timedelta(days=3): |
| 146 | + print("ERROR: a chunk exceeded the 3 day limit") |
| 147 | + failed += 1 |
| 148 | + else: |
| 149 | + print("✓ no chunk exceeds the requested chunk size") |
| 150 | + |
| 151 | + return failed |
| 152 | + |
| 153 | + |
| 154 | +def run_history_chunking_tests(my_predbat=None): |
| 155 | + """Run all history chunking tests""" |
| 156 | + print("\n" + "=" * 80) |
| 157 | + print("History Chunking Tests") |
| 158 | + print("=" * 80) |
| 159 | + |
| 160 | + failed = 0 |
| 161 | + failed += test_get_history_drops_synthesised_boundary_record(my_predbat) |
| 162 | + failed += test_get_history_short_window_makes_one_request(my_predbat) |
| 163 | + failed += test_get_history_chunks_cover_the_window_exactly(my_predbat) |
| 164 | + |
| 165 | + print("\n" + "=" * 80) |
| 166 | + if failed == 0: |
| 167 | + print("✅ All history chunking tests passed!") |
| 168 | + else: |
| 169 | + print(f"❌ {failed} history chunking test(s) failed") |
| 170 | + print("=" * 80) |
| 171 | + |
| 172 | + return failed |
0 commit comments