pywmswebcontrolpro 0.4.0__tar.gz → 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/CHANGELOG.md +13 -1
  2. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/PKG-INFO +14 -1
  3. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/README.md +13 -0
  4. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/destination.py +26 -14
  5. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/refresh.py +65 -4
  6. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/webcontrol.py +11 -4
  7. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/tests/test_refresh.py +155 -0
  8. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/.github/workflows/release.yaml +0 -0
  9. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/.github/workflows/validate.yaml +0 -0
  10. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/.gitignore +0 -0
  11. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/.python-version +0 -0
  12. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/LICENSE +0 -0
  13. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/mypy.ini +0 -0
  14. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/pyproject.toml +0 -0
  15. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/pytest.ini +0 -0
  16. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/__init__.py +0 -0
  17. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/action.py +0 -0
  18. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/const.py +0 -0
  19. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/exceptions.py +0 -0
  20. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/py.typed +0 -0
  21. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/room.py +0 -0
  22. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/scene.py +0 -0
  23. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/store.py +0 -0
  24. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/pywmswebcontrolpro/travel.py +0 -0
  25. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/requirements_lint.txt +0 -0
  26. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/requirements_test.txt +0 -0
  27. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/ruff.toml +0 -0
  28. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/simulator/simulator.py +0 -0
  29. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/tests/__init__.py +0 -0
  30. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/tests/conftest.py +0 -0
  31. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/tests/test_client.py +0 -0
  32. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/tests/test_configuration.py +0 -0
  33. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/tests/test_import.py +0 -0
  34. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/tests/test_rotation.py +0 -0
  35. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/tests/test_settings.py +0 -0
  36. {pywmswebcontrolpro-0.4.0 → pywmswebcontrolpro-0.5.0}/tests/test_travel.py +0 -0
@@ -1,6 +1,18 @@
1
1
  # Changelog
2
2
 
3
- ## 0.4.0 (unreleased)
3
+ ## 0.5.0 (unreleased)
4
+
5
+ Added:
6
+
7
+ - `RefreshStats.last_duration`, the seconds the hub took to answer the last status
8
+ request of a destination.
9
+ - `RefreshStats.recent_success_rate`, the share of refreshes with data within the last
10
+ `stats_window` (new argument of `WebControlPro`, default 24 hours).
11
+ - `RefreshStats.causes` and the argument `cause` of `Destination.refresh()`: the
12
+ results are counted separately for regular requests and requests after a command.
13
+ - The three values are part of `diag()`.
14
+
15
+ ## 0.4.0
4
16
 
5
17
  Breaking changes:
6
18
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pywmswebcontrolpro
3
- Version: 0.4.0
3
+ Version: 0.5.0
4
4
  Summary: Python library for the Warema WMS WebControl pro API
5
5
  Author-email: Marc Hoersken <info@marc-hoersken.de>
6
6
  Maintainer: zomtec
@@ -49,6 +49,19 @@ refreshes with data in percent, `RefreshStats.last_ok` the time of the last one,
49
49
  destination has failed continuously for `stale_warning_after` (default 24 hours) and
50
50
  once when it delivers data again.
51
51
 
52
+ The statistics also tell:
53
+
54
+ - `RefreshStats.last_duration`: the seconds the hub took to answer the last status
55
+ request, whatever the answer was. The pause before the request does not count. It is
56
+ `None` when the hub did not answer. The value belongs to one destination,
57
+ `WebControlPro.stats` does not have it.
58
+ - `RefreshStats.recent_success_rate`: the share of refreshes with data within the last
59
+ `stats_window` (`WebControlPro(stats_window=...)`, default 24 hours), `None` without
60
+ a refresh in that time.
61
+ - `RefreshStats.causes`: the results counted for each cause.
62
+ `Destination.refresh(cause=RefreshCause.SCHEDULED)` marks a regular request, the
63
+ default `RefreshCause.COMMAND` one that follows a command.
64
+
52
65
  ## Errors
53
66
 
54
67
  All errors of the library derive from `WebControlProError`
@@ -35,6 +35,19 @@ refreshes with data in percent, `RefreshStats.last_ok` the time of the last one,
35
35
  destination has failed continuously for `stale_warning_after` (default 24 hours) and
36
36
  once when it delivers data again.
37
37
 
38
+ The statistics also tell:
39
+
40
+ - `RefreshStats.last_duration`: the seconds the hub took to answer the last status
41
+ request, whatever the answer was. The pause before the request does not count. It is
42
+ `None` when the hub did not answer. The value belongs to one destination,
43
+ `WebControlPro.stats` does not have it.
44
+ - `RefreshStats.recent_success_rate`: the share of refreshes with data within the last
45
+ `stats_window` (`WebControlPro(stats_window=...)`, default 24 hours), `None` without
46
+ a refresh in that time.
47
+ - `RefreshStats.causes`: the results counted for each cause.
48
+ `Destination.refresh(cause=RefreshCause.SCHEDULED)` marks a regular request, the
49
+ default `RefreshCause.COMMAND` one that follows a command.
50
+
38
51
  ## Errors
39
52
 
40
53
  All errors of the library derive from `WebControlProError`
@@ -17,6 +17,7 @@ from .const import (
17
17
  from .exceptions import WebControlProError
18
18
  from .refresh import (
19
19
  ERROR_RADIO_BUSY,
20
+ RefreshCause,
20
21
  RefreshOutcome,
21
22
  RefreshResult,
22
23
  RefreshStats,
@@ -55,7 +56,7 @@ class Destination:
55
56
  self._heartbeatError = None
56
57
  self._blocking = None
57
58
  self._status: dict[str, Any] = {}
58
- self._stats = RefreshStats()
59
+ self._stats = RefreshStats(window=control.stats_window.total_seconds())
59
60
 
60
61
  def __str__(self) -> str:
61
62
  return self.name
@@ -139,7 +140,11 @@ class Destination:
139
140
  await self._control._store.flush()
140
141
 
141
142
  async def refresh(
142
- self, retries: int = DEFAULT_REFRESH_RETRIES, *, raise_on_error: bool = False
143
+ self,
144
+ retries: int = DEFAULT_REFRESH_RETRIES,
145
+ *,
146
+ raise_on_error: bool = False,
147
+ cause: RefreshCause = RefreshCause.COMMAND,
143
148
  ) -> RefreshOutcome:
144
149
  """Request the status once and retry up to retries times if radio busy.
145
150
 
@@ -147,46 +152,49 @@ class Destination:
147
152
  previously known values stay unchanged. The outcome is counted in
148
153
  stats instead of being logged for every failure. With raise_on_error
149
154
  a WebControlProError of the request is raised instead of counted.
155
+ cause tells the statistics a regular request from one after a command.
150
156
  """
151
157
  await self.sync()
152
158
 
153
- outcome = await self._request_status(retries, raise_on_error)
154
- self._record(outcome.result)
155
- return outcome
159
+ result, values, duration = await self._request_status(retries, raise_on_error)
160
+ self._record(result, cause, duration)
161
+ return RefreshOutcome(result, values)
156
162
 
157
163
  async def _request_status(
158
164
  self, retries: int, raise_on_error: bool
159
- ) -> RefreshOutcome:
165
+ ) -> tuple[RefreshResult, dict[int, dict[str, Any]], float | None]:
166
+ """Return the result, the values and the answer time of the last request."""
160
167
  status: dict[str, Any] = {}
168
+ duration: float | None = None
161
169
  for attempt in range(retries + 1):
162
170
  try:
163
- status = await self._control._getStatus(self._id)
171
+ status, duration = await self._control._getStatus(self._id)
164
172
  except WebControlProError:
165
173
  if raise_on_error:
166
174
  raise
167
- return RefreshOutcome(RefreshResult.ERROR)
175
+ return RefreshResult.ERROR, {}, None
168
176
  if ERROR_RADIO_BUSY not in (status.get("errors") or ()):
169
177
  break
170
178
  if attempt < retries:
171
179
  await asyncio.sleep(self._control.retry_delay)
172
180
  else:
173
- return RefreshOutcome(RefreshResult.BUSY)
181
+ return RefreshResult.BUSY, {}, duration
174
182
 
175
183
  if not status:
176
- return RefreshOutcome(RefreshResult.EMPTY)
184
+ return RefreshResult.EMPTY, {}, duration
177
185
 
178
186
  try:
179
187
  values = self._apply_status(status)
180
188
  except (AttributeError, KeyError, TypeError) as err:
181
189
  _LOGGER.debug("Unexpected status for %s (%s): %r", self, self._id, err)
182
- return RefreshOutcome(RefreshResult.ERROR)
190
+ return RefreshResult.ERROR, {}, duration
183
191
  if values is None:
184
192
  result = (
185
193
  RefreshResult.ERROR if status.get("errors") else RefreshResult.EMPTY
186
194
  )
187
- return RefreshOutcome(result)
195
+ return result, {}, duration
188
196
  self._status = status
189
- return RefreshOutcome(RefreshResult.OK, values)
197
+ return RefreshResult.OK, values, duration
190
198
 
191
199
  def _apply_status(self, status: dict[str, Any]) -> dict[int, dict[str, Any]] | None:
192
200
  values: dict[int, dict[str, Any]] = {}
@@ -223,11 +231,15 @@ class Destination:
223
231
 
224
232
  return values if refreshed else None
225
233
 
226
- def _record(self, result: RefreshResult) -> None:
234
+ def _record(
235
+ self, result: RefreshResult, cause: RefreshCause, duration: float | None
236
+ ) -> None:
227
237
  change = self._stats.record(
228
238
  result,
229
239
  now=time.monotonic(),
230
240
  stale_after=self._control.stale_warning_after.total_seconds(),
241
+ cause=cause,
242
+ duration=duration,
231
243
  )
232
244
  if change is StaleChange.STALE:
233
245
  _LOGGER.warning(
@@ -1,5 +1,7 @@
1
1
  """Result and statistics of status requests to a destination."""
2
2
 
3
+ import time
4
+ from collections import deque
3
5
  from collections.abc import Iterable
4
6
  from dataclasses import dataclass, field, replace
5
7
  from datetime import UTC, datetime
@@ -9,6 +11,9 @@ from typing import Any
9
11
  # Error code of the hub: the radio channel is occupied and nothing was sent.
10
12
  ERROR_RADIO_BUSY = 0x50005
11
13
 
14
+ # Seconds that the recent success rate looks back.
15
+ DEFAULT_STATS_WINDOW = 24 * 60 * 60.0
16
+
12
17
 
13
18
  class RefreshResult(StrEnum):
14
19
  """Outcome of one status refresh of a destination."""
@@ -19,6 +24,13 @@ class RefreshResult(StrEnum):
19
24
  ERROR = "error"
20
25
 
21
26
 
27
+ class RefreshCause(StrEnum):
28
+ """Reason why the status of a destination was requested."""
29
+
30
+ SCHEDULED = "scheduled"
31
+ COMMAND = "command"
32
+
33
+
22
34
  class StaleChange(StrEnum):
23
35
  """Change of the silent state of a destination."""
24
36
 
@@ -51,19 +63,39 @@ class RefreshStats:
51
63
  error: int = 0
52
64
  last_ok: datetime | None = None
53
65
  last_result: RefreshResult | None = None
66
+ last_duration: float | None = None
67
+ window: float = DEFAULT_STATS_WINDOW
68
+ causes: dict[RefreshCause, dict[RefreshResult, int]] = field(
69
+ default_factory=dict, repr=False
70
+ )
71
+ recent: deque[tuple[float, bool]] = field(default_factory=deque, repr=False)
54
72
  failing_since: float | None = field(default=None, repr=False)
55
73
  stale_reported: bool = field(default=False, repr=False)
56
74
 
57
75
  def record(
58
- self, result: RefreshResult, *, now: float, stale_after: float
76
+ self,
77
+ result: RefreshResult,
78
+ *,
79
+ now: float,
80
+ stale_after: float,
81
+ cause: RefreshCause = RefreshCause.COMMAND,
82
+ duration: float | None = None,
59
83
  ) -> StaleChange | None:
60
84
  """Count a result and report when the silent state changes.
61
85
 
62
86
  now is a monotonic time in seconds. A destination is stale when its
63
- refreshes have failed continuously for stale_after seconds.
87
+ refreshes have failed continuously for stale_after seconds. duration
88
+ is the time in seconds that the hub took to answer, None without an
89
+ answer.
64
90
  """
65
91
  setattr(self, result.value, getattr(self, result.value) + 1)
66
92
  self.last_result = result
93
+ self.last_duration = duration
94
+ by_result = self.causes.setdefault(cause, {})
95
+ by_result[result] = by_result.get(result, 0) + 1
96
+ self.recent.append((now, result is RefreshResult.OK))
97
+ while self.recent[0][0] < now - self.window:
98
+ self.recent.popleft()
67
99
 
68
100
  if result is RefreshResult.OK:
69
101
  self.last_ok = datetime.now(UTC)
@@ -86,11 +118,30 @@ class RefreshStats:
86
118
  total = self.ok + self.busy + self.empty + self.error
87
119
  return 100 * self.ok / total if total else None
88
120
 
121
+ @property
122
+ def recent_success_rate(self) -> float | None:
123
+ """Return the share of refreshes with data within the window in percent.
124
+
125
+ None without a refresh in the last window seconds.
126
+ """
127
+ start = time.monotonic() - self.window
128
+ results = [ok for at, ok in self.recent if at >= start]
129
+ return 100 * sum(results) / len(results) if results else None
130
+
89
131
  @classmethod
90
132
  def combined(cls, stats: Iterable[RefreshStats]) -> RefreshStats:
91
- """Return the sum of the counters and the latest refresh with data."""
133
+ """Return the sum of the counters and the latest refresh with data.
134
+
135
+ The answer time belongs to one destination and is not combined.
136
+ """
92
137
  total = cls()
93
138
  for part in stats:
139
+ total.window = part.window
140
+ total.recent.extend(part.recent)
141
+ for cause, by_result in part.causes.items():
142
+ counts = total.causes.setdefault(cause, {})
143
+ for result, count in by_result.items():
144
+ counts[result] = counts.get(result, 0) + count
94
145
  total.ok += part.ok
95
146
  total.busy += part.busy
96
147
  total.empty += part.empty
@@ -101,7 +152,11 @@ class RefreshStats:
101
152
 
102
153
  def snapshot(self) -> RefreshStats:
103
154
  """Return a copy that does not change with later refreshes."""
104
- return replace(self)
155
+ return replace(
156
+ self,
157
+ causes={cause: dict(counts) for cause, counts in self.causes.items()},
158
+ recent=deque(self.recent),
159
+ )
105
160
 
106
161
  def as_dict(self) -> dict[str, Any]:
107
162
  """Return the counters for diagnostics."""
@@ -112,4 +167,10 @@ class RefreshStats:
112
167
  "error": self.error,
113
168
  "last_ok": self.last_ok.isoformat() if self.last_ok else None,
114
169
  "last_result": self.last_result.value if self.last_result else None,
170
+ "last_duration": self.last_duration,
171
+ "recent_success_rate": self.recent_success_rate,
172
+ "causes": {
173
+ cause.value: {result.value: count for result, count in counts.items()}
174
+ for cause, counts in self.causes.items()
175
+ },
115
176
  }
@@ -31,7 +31,7 @@ from .exceptions import (
31
31
  WebControlProConnectionError,
32
32
  WebControlProResponseError,
33
33
  )
34
- from .refresh import RefreshStats
34
+ from .refresh import DEFAULT_STATS_WINDOW, RefreshStats
35
35
  from .room import Room
36
36
  from .scene import Scene
37
37
  from .store import HubStore
@@ -69,6 +69,7 @@ class WebControlPro:
69
69
  stale_warning_after: timedelta = DEFAULT_STALE_WARNING_AFTER,
70
70
  retry_delay: float = DEFAULT_RETRY_DELAY,
71
71
  request_spacing: float = DEFAULT_REQUEST_SPACING,
72
+ stats_window: timedelta = timedelta(seconds=DEFAULT_STATS_WINDOW),
72
73
  ) -> None:
73
74
  """Create a client.
74
75
 
@@ -77,9 +78,11 @@ class WebControlPro:
77
78
  sets how long a destination may stay silent before a warning is
78
79
  logged, retry_delay the pause in seconds between retries after a
79
80
  radio busy answer and request_spacing the minimum pause in seconds
80
- between two status requests.
81
+ between two status requests. stats_window is the time that the recent
82
+ success rate of the statistics looks back.
81
83
  """
82
84
  self.stale_warning_after = stale_warning_after
85
+ self.stats_window = stats_window
83
86
  self.retry_delay = retry_delay
84
87
  self._common_lock = asyncio.Lock()
85
88
  self._status_lock = asyncio.Lock()
@@ -138,18 +141,22 @@ class WebControlPro:
138
141
  WMS_WebControl_pro_API_command_getConfiguration
139
142
  )
140
143
 
141
- async def _getStatus(self, destinationId: int) -> Any:
144
+ async def _getStatus(self, destinationId: int) -> tuple[Any, float]:
145
+ """Return the status answer and the seconds the hub took for it."""
142
146
  async with self._status_lock:
143
147
  elapsed_time = time.monotonic() - self._status_last
144
148
  if elapsed_time < self.request_spacing:
145
149
  await asyncio.sleep(self.request_spacing - elapsed_time)
150
+ # The wait for the lock and the spacing is not part of the answer time.
151
+ started = time.monotonic()
146
152
  try:
147
- return await self._commonCommand(
153
+ answer = await self._commonCommand(
148
154
  WMS_WebControl_pro_API_command_getStatus,
149
155
  destinations=[destinationId],
150
156
  )
151
157
  finally:
152
158
  self._status_last = time.monotonic()
159
+ return answer, self._status_last - started
153
160
 
154
161
  async def _action(
155
162
  self,
@@ -1,5 +1,6 @@
1
1
  """Tests for the status refresh of a destination."""
2
2
 
3
+ import time
3
4
  from collections.abc import Callable
4
5
  from datetime import timedelta
5
6
  from typing import Any
@@ -10,6 +11,7 @@ import pytest
10
11
  from pywmswebcontrolpro.destination import Destination
11
12
  from pywmswebcontrolpro.exceptions import WebControlProConnectionError
12
13
  from pywmswebcontrolpro.refresh import (
14
+ RefreshCause,
13
15
  RefreshResult,
14
16
  RefreshStats,
15
17
  StaleChange,
@@ -281,3 +283,156 @@ async def test_request_spacing_delays_the_next_status_request(
281
283
 
282
284
  assert len(sleeps) == 1
283
285
  assert 0 < sleeps[0] <= 0.25
286
+
287
+
288
+ @pytest.mark.parametrize(
289
+ ("answer", "answered"),
290
+ [
291
+ (status_ok(), True),
292
+ (STATUS_BUSY, True),
293
+ (STATUS_EMPTY, True),
294
+ (TimeoutError(), False),
295
+ ],
296
+ )
297
+ async def test_last_duration_is_the_answer_time_of_the_last_request(
298
+ dest: Destination,
299
+ gateway: FakeGateway,
300
+ answer: dict[str, Any] | Exception,
301
+ answered: bool,
302
+ ) -> None:
303
+ """Every answer of the hub has a duration, a request without answer has none."""
304
+ gateway.status_answers = [status_ok(), answer]
305
+ await dest.refresh()
306
+
307
+ await dest.refresh()
308
+
309
+ assert (dest.stats.last_duration is not None) is answered
310
+ assert dest.diag()["stats"]["last_duration"] == dest.stats.last_duration
311
+
312
+
313
+ async def test_last_duration_excludes_the_request_spacing(
314
+ make_control: Callable[..., WebControlPro],
315
+ gateway: FakeGateway,
316
+ monkeypatch: pytest.MonkeyPatch,
317
+ ) -> None:
318
+ """The pause before a request does not count as answer time of the hub."""
319
+ control = make_control(request_spacing=60)
320
+ await control.refresh()
321
+ clock = [1000.0]
322
+
323
+ async def fake_sleep(delay: float) -> None:
324
+ clock[0] += delay
325
+
326
+ monkeypatch.setattr("pywmswebcontrolpro.webcontrol.asyncio.sleep", fake_sleep)
327
+ monkeypatch.setattr(
328
+ "pywmswebcontrolpro.webcontrol.time.monotonic", lambda: clock[0]
329
+ )
330
+ gateway.status_answers = [status_ok(), status_ok()]
331
+ await control.dests[7].refresh()
332
+
333
+ await control.dests[7].refresh()
334
+
335
+ assert clock[0] == 1060.0
336
+ assert control.dests[7].stats.last_duration == 0.0
337
+
338
+
339
+ async def test_results_are_counted_for_each_cause(
340
+ dest: Destination, gateway: FakeGateway
341
+ ) -> None:
342
+ """Regular requests and requests after a command have their own counters."""
343
+ gateway.status_answers = [status_ok(), STATUS_BUSY, STATUS_BUSY]
344
+
345
+ await dest.refresh(cause=RefreshCause.SCHEDULED)
346
+ await dest.refresh(cause=RefreshCause.SCHEDULED)
347
+ await dest.refresh()
348
+
349
+ assert dest.stats.causes == {
350
+ RefreshCause.SCHEDULED: {RefreshResult.OK: 1, RefreshResult.BUSY: 1},
351
+ RefreshCause.COMMAND: {RefreshResult.BUSY: 1},
352
+ }
353
+ assert dest.stats.busy == 2
354
+ assert dest.diag()["stats"]["causes"] == {
355
+ "scheduled": {"ok": 1, "busy": 1},
356
+ "command": {"busy": 1},
357
+ }
358
+
359
+
360
+ def test_recent_success_rate_is_unknown_without_a_refresh() -> None:
361
+ """Without a request in the window there is no recent rate."""
362
+ assert RefreshStats().recent_success_rate is None
363
+
364
+
365
+ def test_recent_success_rate_forgets_results_older_than_the_window() -> None:
366
+ """Only the refreshes of the last window seconds count."""
367
+ stats = RefreshStats(window=100.0)
368
+ now = time.monotonic()
369
+
370
+ stats.record(RefreshResult.BUSY, now=now - 150, stale_after=1e9)
371
+ stats.record(RefreshResult.BUSY, now=now - 50, stale_after=1e9)
372
+ stats.record(RefreshResult.OK, now=now, stale_after=1e9)
373
+
374
+ assert stats.recent_success_rate == 50.0
375
+ assert stats.success_rate == pytest.approx(100 / 3)
376
+ assert len(stats.recent) == 2
377
+
378
+
379
+ def test_recent_success_rate_ends_when_the_last_refresh_is_too_old() -> None:
380
+ """A destination that was not asked within the window has no recent rate."""
381
+ stats = RefreshStats(window=100.0)
382
+
383
+ stats.record(RefreshResult.OK, now=time.monotonic() - 150, stale_after=1e9)
384
+
385
+ assert stats.recent_success_rate is None
386
+
387
+
388
+ async def test_stats_window_of_the_client_is_used_by_its_destinations(
389
+ make_control: Callable[..., WebControlPro],
390
+ ) -> None:
391
+ """The window of the recent rate is set when the client is created."""
392
+ control = make_control(stats_window=timedelta(hours=1))
393
+ await control.refresh()
394
+
395
+ assert control.dests[7].stats.window == 3600.0
396
+ assert control.stats.window == 3600.0
397
+
398
+
399
+ async def test_stats_of_the_client_combine_causes_and_recent_results(
400
+ make_control: Callable[..., WebControlPro], gateway: FakeGateway
401
+ ) -> None:
402
+ """The client sums the counters of the causes and the recent results."""
403
+ gateway.config = {
404
+ **gateway.config,
405
+ "destinations": [
406
+ gateway.config["destinations"][0],
407
+ {**gateway.config["destinations"][0], "id": 8},
408
+ ],
409
+ }
410
+ control = make_control()
411
+ await control.refresh()
412
+ assert control.stats.recent_success_rate is None
413
+ gateway.status_answers = [status_ok(), STATUS_BUSY, STATUS_BUSY, STATUS_BUSY]
414
+
415
+ for dest in control.dests.values():
416
+ await dest.refresh(cause=RefreshCause.SCHEDULED)
417
+ await dest.refresh(cause=RefreshCause.SCHEDULED)
418
+
419
+ assert control.stats.causes == {
420
+ RefreshCause.SCHEDULED: {RefreshResult.OK: 1, RefreshResult.BUSY: 3}
421
+ }
422
+ assert control.stats.recent_success_rate == 25.0
423
+ assert control.stats.last_duration is None
424
+
425
+
426
+ async def test_stats_snapshot_keeps_its_causes_and_recent_results(
427
+ dest: Destination, gateway: FakeGateway
428
+ ) -> None:
429
+ """Later refreshes do not change the causes and recent results of a snapshot."""
430
+ gateway.status_answers = [status_ok(), STATUS_BUSY]
431
+ await dest.refresh()
432
+ snapshot = dest.stats
433
+
434
+ await dest.refresh()
435
+
436
+ assert snapshot.causes == {RefreshCause.COMMAND: {RefreshResult.OK: 1}}
437
+ assert snapshot.recent_success_rate == 100.0
438
+ assert dest.stats.recent_success_rate == 50.0