Debian Codegraph @

tests/test_iotawatt_update.py

raw
1 """Tests for Iotawatt.update() against a mocked device."""
2
3 from __future__ import annotations
4
5 from typing import TYPE_CHECKING, Any
6
7 import httpx
8 import pytest
9 import respx
10
11 from iotawattpy.iotawatt import Iotawatt
12
13 if TYPE_CHECKING:
14 from collections.abc import AsyncIterator
15
16 HOST = "192.0.2.1"
17
18 STATUS_WIFI = {"wifi": {"mac": "de:ad:be:ef:00:01"}}
19 STATUS_INPUTS_OUTPUTS = {
20 "inputs": [{"channel": 0, "Watts": "123"}],
21 "outputs": [],
22 }
23 STATUS_DATALOGS = {
24 "datalogs": [
25 {"id": "Current", "firstkey": 1750000000, "lastkey": 1751000000},
26 {"id": "History", "firstkey": 1600000000, "lastkey": 1751000000},
27 ]
28 }
29 SHOW_SERIES = {"series": [{"name": "Main", "unit": "Watts"}]}
30
31 CURRENT_RESULT = [[123.4]]
32 INTEGRATED_RESULT: list[list[str | float]] = [["2024-09-02T00:00:00", 4567]]
33 LIFETIME_RESULT: list[list[str | float]] = [["2020-09-13T14:26:40", 12345678.912]]
34
35 STATUS_INPUTS_OUTPUTS_REACTIVE = {
36 "inputs": [{"channel": 0, "Watts": "123"}],
37 "outputs": [{"name": "reactive", "units": "VARh"}],
38 }
39 SHOW_SERIES_REACTIVE = {
40 "series": [
41 {"name": "Main", "unit": "Watts"},
42 {"name": "reactive", "unit": "VARh"},
43 ]
44 }
45 CURRENT_RESULT_REACTIVE = [[123.4, 55.5]]
46 LIFETIME_RESULT_REACTIVE: list[list[str | float]] = [
47 ["2020-09-13T14:26:40", 12345678.912, 4321.5]
48 ]
49
50
51 @pytest.fixture
52 async def websession() -> AsyncIterator[httpx.AsyncClient]:
53 async with httpx.AsyncClient() as client:
54 yield client
55
56
57 def _mock_device(
58 integrated_result: list[list[str | float]],
59 datalogs: dict[str, Any] | None = None,
60 inputs_outputs: dict[str, Any] | None = None,
61 show_series: dict[str, Any] | None = None,
62 current_result: list[list[float]] | None = None,
63 lifetime_result: list[list[str | float]] | None = None,
64 ) -> list[dict[str, str]]:
65 """Mock the device HTTP endpoints.
66
67 Returns a list capturing the parameters of every integrated
68 (time.iso) query the library performs.
69 """
70 if datalogs is None:
71 datalogs = STATUS_DATALOGS
72 if inputs_outputs is None:
73 inputs_outputs = STATUS_INPUTS_OUTPUTS
74 if show_series is None:
75 show_series = SHOW_SERIES
76 if current_result is None:
77 current_result = CURRENT_RESULT
78 if lifetime_result is None:
79 lifetime_result = LIFETIME_RESULT
80 respx.get(f"http://{HOST}/status", params={"wifi": "yes"}).respond(json=STATUS_WIFI)
81 respx.get(
82 f"http://{HOST}/status", params={"inputs": "yes", "outputs": "yes"}
83 ).respond(json=inputs_outputs)
84 respx.get(f"http://{HOST}/status", params={"datalogs": "yes"}).respond(
85 json=datalogs
86 )
87
88 integrated_queries: list[dict[str, str]] = []
89
90 def query(request: httpx.Request) -> httpx.Response:
91 params = request.url.params
92 if params.get("show") == "series":
93 return httpx.Response(200, json=show_series)
94 if params["select"].startswith("[time.iso"):
95 integrated_queries.append(dict(params))
96 if params["begin"] == "d":
97 return httpx.Response(200, json=integrated_result)
98 return httpx.Response(200, json=lifetime_result)
99 return httpx.Response(200, json=current_result)
100
101 respx.get(f"http://{HOST}/query").mock(side_effect=query)
102 return integrated_queries
103
104
105 @respx.mock
106 async def test_update(websession: httpx.AsyncClient) -> None:
107 """A normal update populates current and integrated sensor values."""
108 _mock_device(INTEGRATED_RESULT)
109 iotawatt = Iotawatt(
110 "test", HOST, websession, integratedInterval="d", includeNonTotalSensors=False
111 )
112
113 await iotawatt.update()
114
115 sensors = iotawatt.getSensors()["sensors"]
116 assert sensors["input_0"].getValue() == 123.4
117 assert sensors["input_0_total_energy"].getValue() == 4567
118 assert sensors["input_0_total_energy"].getBegin() == "2024-09-02T00:00:00"
119 assert "input_0_lifetime_energy" not in sensors
120
121
122 @respx.mock
123 async def test_update_empty_integrated_result(websession: httpx.AsyncClient) -> None:
124 """An empty integrated query result is skipped instead of raising.
125
126 The device returns [] for a zero-length interval, e.g. when queried
127 with begin=d within the first seconds after midnight.
128 """
129 _mock_device([])
130 iotawatt = Iotawatt(
131 "test", HOST, websession, integratedInterval="d", includeNonTotalSensors=False
132 )
133
134 await iotawatt.update()
135
136 sensors = iotawatt.getSensors()["sensors"]
137 assert sensors["input_0"].getValue() == 123.4
138 assert sensors["input_0_total_energy"].getValue() is None
139 assert sensors["input_0_total_energy"].getBegin() is None
140
141
142 @respx.mock
143 async def test_update_lifetime_sensors(websession: httpx.AsyncClient) -> None:
144 """Lifetime sensors integrate since the datalog start."""
145 integrated_queries = _mock_device(INTEGRATED_RESULT)
146 iotawatt = Iotawatt(
147 "test",
148 HOST,
149 websession,
150 integratedInterval="d",
151 includeNonTotalSensors=False,
152 includeLifetimeSensors=True,
153 )
154
155 await iotawatt.update()
156
157 sensors = iotawatt.getSensors()["sensors"]
158 sensor = sensors["input_0_lifetime_energy"]
159 assert sensor.getName() == "Main.wh_lifetime"
160 assert sensor.getLifetime() is True
161 assert sensor.getValue() == 12345678.912
162 assert sensor.getBegin() == "2020-09-13T14:26:40"
163 assert sensors["input_0_total_energy"].getValue() == 4567
164
165 lifetime_query = next(q for q in integrated_queries if q["begin"] != "d")
166 assert lifetime_query["begin"] == "1600000000"
167 assert "Main.wh.d3" in lifetime_query["select"]
168
169
170 @respx.mock
171 async def test_update_lifetime_datalog_start_cached(
172 websession: httpx.AsyncClient,
173 ) -> None:
174 """The datalog start is only fetched once across updates."""
175 _mock_device(INTEGRATED_RESULT)
176 iotawatt = Iotawatt(
177 "test",
178 HOST,
179 websession,
180 integratedInterval="d",
181 includeNonTotalSensors=False,
182 includeLifetimeSensors=True,
183 )
184
185 await iotawatt.update()
186 await iotawatt.update()
187
188 datalogs_route = respx.get(f"http://{HOST}/status", params={"datalogs": "yes"})
189 assert datalogs_route.call_count == 1
190
191
192 @respx.mock
193 async def test_update_lifetime_only(websession: httpx.AsyncClient) -> None:
194 """Without total sensors, the period query is not issued at all."""
195 integrated_queries = _mock_device(INTEGRATED_RESULT)
196 iotawatt = Iotawatt(
197 "test",
198 HOST,
199 websession,
200 integratedInterval="d",
201 includeNonTotalSensors=False,
202 includeLifetimeSensors=True,
203 includeTotalSensors=False,
204 )
205
206 await iotawatt.update()
207
208 sensors = iotawatt.getSensors()["sensors"]
209 assert "input_0_total_energy" not in sensors
210 assert sensors["input_0"].getValue() == 123.4
211 assert sensors["input_0_lifetime_energy"].getValue() == 12345678.912
212 assert [q["begin"] for q in integrated_queries] == ["1600000000"]
213
214
215 @pytest.mark.parametrize(
216 ("datalogs", "expected_begin"),
217 [
218 pytest.param(STATUS_DATALOGS, "1600000000", id="prefer-history"),
219 pytest.param(
220 {
221 "datalogs": [
222 {"id": "Current", "firstkey": 1750000000},
223 {"id": "History", "firstkey": 0},
224 ]
225 },
226 "1750000000",
227 id="empty-history",
228 ),
229 pytest.param(
230 {"datalogs": [{"id": "Current", "firstkey": 999999999}]},
231 "2000-01-01",
232 id="clock-not-set",
233 ),
234 pytest.param({"datalogs": []}, "2000-01-01", id="no-datalogs"),
235 pytest.param({}, "2000-01-01", id="firmware-without-datalogs-support"),
236 ],
237 )
238 @respx.mock
239 async def test_update_lifetime_begin_selection(
240 websession: httpx.AsyncClient,
241 datalogs: dict[str, Any],
242 expected_begin: str,
243 ) -> None:
244 """The lifetime query begin is derived from the datalog status."""
245 integrated_queries = _mock_device(INTEGRATED_RESULT, datalogs=datalogs)
246 iotawatt = Iotawatt(
247 "test",
248 HOST,
249 websession,
250 integratedInterval="d",
251 includeNonTotalSensors=False,
252 includeLifetimeSensors=True,
253 )
254
255 await iotawatt.update()
256
257 lifetime_query = next(q for q in integrated_queries if q["begin"] != "d")
258 assert lifetime_query["begin"] == expected_begin
259
260
261 @respx.mock
262 async def test_update_reactive_sensor_default(websession: httpx.AsyncClient) -> None:
263 """By default, VARh sensors report the last update interval."""
264 integrated_queries = _mock_device(
265 INTEGRATED_RESULT,
266 inputs_outputs=STATUS_INPUTS_OUTPUTS_REACTIVE,
267 show_series=SHOW_SERIES_REACTIVE,
268 current_result=CURRENT_RESULT_REACTIVE,
269 )
270 iotawatt = Iotawatt(
271 "test", HOST, websession, integratedInterval="d", includeNonTotalSensors=False
272 )
273
274 await iotawatt.update()
275
276 sensors = iotawatt.getSensors()["sensors"]
277 assert sensors["output_reactive"].getName() == "reactive"
278 assert sensors["output_reactive"].getValue() == 55.5
279 assert sensors["output_reactive"].getBegin() is None
280 assert not any("varh" in query["select"] for query in integrated_queries)
281
282
283 @respx.mock
284 async def test_update_reactive_sensor_integrated(
285 websession: httpx.AsyncClient,
286 ) -> None:
287 """With integrateReactiveSensors, VARh sensors become meter readings."""
288 integrated_queries = _mock_device(
289 INTEGRATED_RESULT,
290 inputs_outputs=STATUS_INPUTS_OUTPUTS_REACTIVE,
291 show_series=SHOW_SERIES_REACTIVE,
292 lifetime_result=LIFETIME_RESULT_REACTIVE,
293 )
294 iotawatt = Iotawatt(
295 "test",
296 HOST,
297 websession,
298 integratedInterval="d",
299 includeNonTotalSensors=False,
300 includeLifetimeSensors=True,
301 includeTotalSensors=False,
302 integrateReactiveSensors=True,
303 )
304
305 await iotawatt.update()
306
307 sensors = iotawatt.getSensors()["sensors"]
308 assert sensors["output_reactive"].getName() == "reactive"
309 assert sensors["output_reactive"].getValue() == 4321.5
310 assert sensors["output_reactive"].getBegin() == "2020-09-13T14:26:40"
311 assert sensors["input_0_lifetime_energy"].getValue() == 12345678.912
312
313 # All lifetime series are fetched with a single query.
314 assert len(integrated_queries) == 1
315 assert integrated_queries[0]["begin"] == "1600000000"
316 assert integrated_queries[0]["select"] == "[time.iso,Main.wh.d3,reactive.varh.d3]"