teslemetry-stream 1.2.0__tar.gz → 1.3.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 (37) hide show
  1. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/PKG-INFO +4 -1
  2. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/README.md +3 -0
  3. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/pyproject.toml +1 -1
  4. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/teslemetry_stream/const.py +43 -0
  5. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/teslemetry_stream/energysite.py +23 -2
  6. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/teslemetry_stream/stream.py +20 -4
  7. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/teslemetry_stream.egg-info/PKG-INFO +4 -1
  8. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/teslemetry_stream.egg-info/SOURCES.txt +1 -0
  9. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_energysite_events.py +67 -1
  10. teslemetry_stream-1.3.0/tests/test_no_token_in_logs.py +244 -0
  11. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/LICENSE +0 -0
  12. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/setup.cfg +0 -0
  13. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/teslemetry_stream/__init__.py +0 -0
  14. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/teslemetry_stream/exception.py +0 -0
  15. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/teslemetry_stream/py.typed +0 -0
  16. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/teslemetry_stream/vehicle.py +0 -0
  17. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/teslemetry_stream.egg-info/dependency_links.txt +0 -0
  18. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/teslemetry_stream.egg-info/requires.txt +0 -0
  19. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/teslemetry_stream.egg-info/top_level.txt +0 -0
  20. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_active_route.py +0 -0
  21. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_auth_failure.py +0 -0
  22. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_batch_retry_storm.py +0 -0
  23. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_charger_power.py +0 -0
  24. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_clean_stream_end.py +0 -0
  25. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_config_events.py +0 -0
  26. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_config_listener_lifecycle.py +0 -0
  27. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_config_update.py +0 -0
  28. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_connect_failure_notifies.py +0 -0
  29. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_enum_tables.py +0 -0
  30. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_external_ingest.py +0 -0
  31. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_field_type_coercion.py +0 -0
  32. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_library_header.py +0 -0
  33. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_listen_early_exit.py +0 -0
  34. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_reconnect_config_window.py +0 -0
  35. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_sse_topics.py +0 -0
  36. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_stream_lifecycle.py +0 -0
  37. {teslemetry_stream-1.2.0 → teslemetry_stream-1.3.0}/tests/test_tpms_warnings.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: teslemetry_stream
3
- Version: 1.2.0
3
+ Version: 1.3.0
4
4
  Summary: Teslemetry Streaming API library for Python
5
5
  Author-email: Brett Adams <hello@teslemetry.com>
6
6
  License-Expression: Apache-2.0
@@ -382,5 +382,8 @@ Listen for energy site info events. The callback receives the `site_info` docume
382
382
  ### `listen_TariffContentV2(callback: Callable[[dict | None], None]) -> Callable[[],None]`
383
383
  Listen for the site's V2 tariff document. The callback receives the `tariff_content_v2` document verbatim, or `None` when the server sends an explicit removal signal. Published only when it changes.
384
384
 
385
+ ### `listen_WallConnectorTotals(callback: Callable[[WallConnectorTotalsEvent], None]) -> Callable[[],None]`
386
+ Listen for `wall_connector_totals` notifications. The callback receives a `WallConnectorTotalsEvent` with `date` (the installation-local day, verbatim), `created_at`, `is_cache` and `totals`, a dict of Wall Connector DIN to Wh delivered on `date` (a Wall Connector with no session that day is absent). Published while any Wall Connector is charging and once more after charging stops; a connect-time snapshot has `is_cache=True` and may be an earlier date. Key updates by `(site id, din, date)` and use `created_at` to reject an older replay.
387
+
385
388
  ### `listen_EnergyTotals(callback: Callable[[EnergyHistoryTotals], None]) -> Callable[[],None]`
386
389
  Listen for `energy_totals` refresh notifications. The callback receives an `EnergyHistoryTotals` dataclass of cumulative per-type totals - never the full time series. Fires only when the server's periodic history poll detects a change; a consumer wanting the full series should GET the underlying event's `url` via their own REST client.
@@ -366,5 +366,8 @@ Listen for energy site info events. The callback receives the `site_info` docume
366
366
  ### `listen_TariffContentV2(callback: Callable[[dict | None], None]) -> Callable[[],None]`
367
367
  Listen for the site's V2 tariff document. The callback receives the `tariff_content_v2` document verbatim, or `None` when the server sends an explicit removal signal. Published only when it changes.
368
368
 
369
+ ### `listen_WallConnectorTotals(callback: Callable[[WallConnectorTotalsEvent], None]) -> Callable[[],None]`
370
+ Listen for `wall_connector_totals` notifications. The callback receives a `WallConnectorTotalsEvent` with `date` (the installation-local day, verbatim), `created_at`, `is_cache` and `totals`, a dict of Wall Connector DIN to Wh delivered on `date` (a Wall Connector with no session that day is absent). Published while any Wall Connector is charging and once more after charging stops; a connect-time snapshot has `is_cache=True` and may be an earlier date. Key updates by `(site id, din, date)` and use `created_at` to reject an older replay.
371
+
369
372
  ### `listen_EnergyTotals(callback: Callable[[EnergyHistoryTotals], None]) -> Callable[[],None]`
370
373
  Listen for `energy_totals` refresh notifications. The callback receives an `EnergyHistoryTotals` dataclass of cumulative per-type totals - never the full time series. Fires only when the server's periodic history poll detects a change; a consumer wanting the full series should GET the underlying event's `url` via their own REST client.
@@ -4,7 +4,7 @@ requires = ["setuptools>=77.0"]
4
4
 
5
5
  [project]
6
6
  name = "teslemetry_stream"
7
- version = "1.2.0"
7
+ version = "1.3.0"
8
8
  license = "Apache-2.0"
9
9
  description = "Teslemetry Streaming API library for Python"
10
10
  readme = "README.md"
@@ -378,6 +378,7 @@ class SseTopic(StrEnum):
378
378
  SITE_INFO = "site_info"
379
379
  TARIFF_CONTENT_V2 = "tariff_content_v2"
380
380
  ENERGY_TOTALS = "energy_totals"
381
+ WALL_CONNECTOR_TOTALS = "wall_connector_totals"
381
382
  CREDITS = "credits"
382
383
 
383
384
 
@@ -400,6 +401,7 @@ SSE_ENERGY_TOPICS: tuple[SseTopic, ...] = (
400
401
  SseTopic.SITE_INFO,
401
402
  SseTopic.TARIFF_CONTENT_V2,
402
403
  SseTopic.ENERGY_TOTALS,
404
+ SseTopic.WALL_CONNECTOR_TOTALS,
403
405
  )
404
406
 
405
407
  #: Convenience preset - every account-wide topic.
@@ -491,6 +493,47 @@ class EnergyTotalsEvent:
491
493
  )
492
494
 
493
495
 
496
+ def is_energy_totals(totals: dict[str, Any]) -> bool:
497
+ """Tell an `energy_totals` payload from a `wall_connector_totals` one.
498
+
499
+ Both events share the `{id, date, createdAt, isCache?, totals}` envelope
500
+ and the decoded event carries no topic name, so the `totals` keys decide:
501
+ `energy_totals` always carries the fixed `EnergyHistoryTotals` names
502
+ (null when the day is empty), while `wall_connector_totals` is keyed by
503
+ Wall Connector DIN and may be empty.
504
+ """
505
+ return any(field in totals for field in EnergyHistoryTotals.__dataclass_fields__)
506
+
507
+
508
+ @dataclass
509
+ class WallConnectorTotalsEvent:
510
+ """A `wall_connector_totals` notification.
511
+
512
+ `totals` maps Wall Connector DIN to Wh delivered on `date`; a Wall
513
+ Connector with no session that day is absent. `date` is the
514
+ installation-local day, passed through exactly as sent - never
515
+ reinterpreted in the client's own timezone. Key updates by
516
+ `(site_id, din, date)` and use `created_at` to reject an older replay.
517
+ `is_cache` is `True` only for the connect-time snapshot, which may be
518
+ an earlier date.
519
+ """
520
+
521
+ date: str
522
+ created_at: datetime
523
+ is_cache: bool
524
+ totals: dict[str, float]
525
+
526
+ @classmethod
527
+ def from_dict(cls, data: dict[str, Any]) -> WallConnectorTotalsEvent:
528
+ """Build from the event's top-level dict."""
529
+ return cls(
530
+ date=data[Key.DATE],
531
+ created_at=parse_created_at(data[Key.CREATED_AT]),
532
+ is_cache=bool(data.get(Key.IS_CACHE, False)),
533
+ totals=dict(data[Key.TOTALS]),
534
+ )
535
+
536
+
494
537
  @dataclass
495
538
  class CreditsEvent:
496
539
  """A credits accounting event.
@@ -5,7 +5,7 @@ from __future__ import annotations
5
5
  from collections.abc import Callable
6
6
  from typing import TYPE_CHECKING, Any
7
7
 
8
- from .const import EnergyTotalsEvent, Key
8
+ from .const import EnergyTotalsEvent, Key, WallConnectorTotalsEvent, is_energy_totals
9
9
 
10
10
  if TYPE_CHECKING:
11
11
  from .stream import TeslemetryStream
@@ -98,7 +98,28 @@ class TeslemetryStreamEnergySite:
98
98
  wrapping it under `.totals`.
99
99
  """
100
100
  def _handler(x: dict[str, Any]) -> None:
101
- if int(x[Key.ID]) == self.site_id:
101
+ if int(x[Key.ID]) == self.site_id and is_energy_totals(x[Key.TOTALS]):
102
102
  callback(EnergyTotalsEvent.from_dict(x))
103
103
 
104
104
  return self.stream.async_add_listener(_handler, {Key.TOTALS: None})
105
+
106
+ def listen_WallConnectorTotals(
107
+ self, callback: Callable[[WallConnectorTotalsEvent], None]
108
+ ) -> Callable[[], None]:
109
+ """Listen for wall_connector_totals notifications.
110
+
111
+ The callback receives a `WallConnectorTotalsEvent`: `totals` maps
112
+ Wall Connector DIN to Wh delivered on `date`, the installation-local
113
+ day, verbatim. A Wall Connector with no session that day is absent.
114
+ The server delivers a connect-time snapshot (`is_cache: True`, which
115
+ may be an earlier date), publishes while any Wall Connector is
116
+ charging and once more after charging stops - that closing event
117
+ carries the session's final total. Key updates by
118
+ `(site_id, din, date)` and use `created_at` to reject an older
119
+ replay. Like `energy_totals`, the site id rides `id`, not `site_id`.
120
+ """
121
+ def _handler(x: dict[str, Any]) -> None:
122
+ if int(x[Key.ID]) == self.site_id and not is_energy_totals(x[Key.TOTALS]):
123
+ callback(WallConnectorTotalsEvent.from_dict(x))
124
+
125
+ return self.stream.async_add_listener(_handler, {Key.TOTALS: None})
@@ -377,18 +377,18 @@ class TeslemetryStream:
377
377
  # A rejected token is a definitive answer, not a transient
378
378
  # blip - retrying it can never succeed, and doing so masks
379
379
  # a bad credential as an indefinitely quiet stream.
380
- LOGGER.error("Authentication failed, not retrying: %s", repr(error))
380
+ LOGGER.error("Authentication failed, not retrying: %s", _describe(error))
381
381
  self.active = False
382
382
  self._connection_failed()
383
383
  raise TeslemetryStreamAuthenticationError() from error
384
- LOGGER.warning("Client error: %s", repr(error))
384
+ LOGGER.warning("Client error: %s", _describe(error))
385
385
  self._connection_failed()
386
386
  delay = min(2**self.retries, 600)
387
387
  LOGGER.debug("Reconnecting in %s seconds", delay)
388
388
  await asyncio.sleep(delay)
389
389
  self.retries += 1
390
390
  except Exception as error:
391
- LOGGER.error("Unexpected error: %s", repr(error))
391
+ LOGGER.error("Unexpected error: %s", _describe(error))
392
392
  self._connection_failed()
393
393
  LOGGER.debug("Reconnecting in %s seconds", 1)
394
394
  await asyncio.sleep(1)
@@ -481,7 +481,9 @@ class TeslemetryStream:
481
481
  self._dispatch(event)
482
482
  except BaseException as error:
483
483
  if not connected_once:
484
- LOGGER.warning("Listen task ended before its first connect: %r", error)
484
+ LOGGER.warning(
485
+ "Listen task ended before its first connect: %s", _describe(error)
486
+ )
485
487
  raise
486
488
  if not connected_once:
487
489
  LOGGER.warning("Listen task ended before its first connect")
@@ -646,6 +648,20 @@ def _parse_created_at(created_at: str) -> int:
646
648
  return int(dt.timestamp()) * 1000 + dt.microsecond // 1000
647
649
 
648
650
 
651
+ def _describe(error: BaseException) -> str:
652
+ """
653
+ Describe an exception for the log without its repr.
654
+
655
+ The repr of an aiohttp.ClientResponseError embeds its RequestInfo, including the
656
+ request headers - the Authorization header carries the access token. str() of the
657
+ aiohttp errors has the status, message and URL only.
658
+
659
+ :param error: The exception to describe.
660
+ :return: "<ExceptionType>: <message>".
661
+ """
662
+ return f"{type(error).__name__}: {error}"
663
+
664
+
649
665
  def _now() -> str:
650
666
  """Current time in the same format the stream sends `createdAt` in."""
651
667
  return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: teslemetry_stream
3
- Version: 1.2.0
3
+ Version: 1.3.0
4
4
  Summary: Teslemetry Streaming API library for Python
5
5
  Author-email: Brett Adams <hello@teslemetry.com>
6
6
  License-Expression: Apache-2.0
@@ -382,5 +382,8 @@ Listen for energy site info events. The callback receives the `site_info` docume
382
382
  ### `listen_TariffContentV2(callback: Callable[[dict | None], None]) -> Callable[[],None]`
383
383
  Listen for the site's V2 tariff document. The callback receives the `tariff_content_v2` document verbatim, or `None` when the server sends an explicit removal signal. Published only when it changes.
384
384
 
385
+ ### `listen_WallConnectorTotals(callback: Callable[[WallConnectorTotalsEvent], None]) -> Callable[[],None]`
386
+ Listen for `wall_connector_totals` notifications. The callback receives a `WallConnectorTotalsEvent` with `date` (the installation-local day, verbatim), `created_at`, `is_cache` and `totals`, a dict of Wall Connector DIN to Wh delivered on `date` (a Wall Connector with no session that day is absent). Published while any Wall Connector is charging and once more after charging stops; a connect-time snapshot has `is_cache=True` and may be an earlier date. Key updates by `(site id, din, date)` and use `created_at` to reject an older replay.
387
+
385
388
  ### `listen_EnergyTotals(callback: Callable[[EnergyHistoryTotals], None]) -> Callable[[],None]`
386
389
  Listen for `energy_totals` refresh notifications. The callback receives an `EnergyHistoryTotals` dataclass of cumulative per-type totals - never the full time series. Fires only when the server's periodic history poll detects a change; a consumer wanting the full series should GET the underlying event's `url` via their own REST client.
@@ -28,6 +28,7 @@ tests/test_external_ingest.py
28
28
  tests/test_field_type_coercion.py
29
29
  tests/test_library_header.py
30
30
  tests/test_listen_early_exit.py
31
+ tests/test_no_token_in_logs.py
31
32
  tests/test_reconnect_config_window.py
32
33
  tests/test_sse_topics.py
33
34
  tests/test_stream_lifecycle.py
@@ -12,7 +12,11 @@ from __future__ import annotations
12
12
  from datetime import datetime, timezone
13
13
  from typing import Any
14
14
 
15
- from teslemetry_stream.const import EnergyHistoryTotals, EnergyTotalsEvent
15
+ from teslemetry_stream.const import (
16
+ EnergyHistoryTotals,
17
+ EnergyTotalsEvent,
18
+ WallConnectorTotalsEvent,
19
+ )
16
20
  from teslemetry_stream.stream import TeslemetryStream, recursive_match
17
21
 
18
22
  SITE_A = "12345"
@@ -75,6 +79,13 @@ TARIFF_CONTENT_V2_NUMERIC_ID: dict[str, Any] = {
75
79
  "site_id": int(SITE_A),
76
80
  }
77
81
 
82
+ WALL_CONNECTOR_TOTALS_EVENT: dict[str, Any] = {
83
+ "id": SITE_A,
84
+ "date": "2026-07-29",
85
+ "createdAt": "2026-07-29T10:16:00.000Z",
86
+ "totals": {"DIN-1": 12500.5, "DIN-2": 800},
87
+ }
88
+
78
89
  OTHER_SITE_LIVE_STATUS: dict[str, Any] = {
79
90
  "createdAt": "2026-07-28T10:16:00.000Z",
80
91
  "site_id": SITE_B,
@@ -384,6 +395,61 @@ def main() -> None:
384
395
  )
385
396
  )
386
397
 
398
+ # listen_WallConnectorTotals delivers per-DIN totals with date, created_at, is_cache.
399
+ stream = make_stream()
400
+ site = stream.get_energysite(SITE_A)
401
+ wc_received: list[WallConnectorTotalsEvent] = []
402
+ site.listen_WallConnectorTotals(wc_received.append)
403
+ dispatch(stream, WALL_CONNECTOR_TOTALS_EVENT)
404
+ dispatch(
405
+ stream,
406
+ {
407
+ **WALL_CONNECTOR_TOTALS_EVENT,
408
+ "id": int(SITE_A),
409
+ "isCache": True,
410
+ "date": "2026-07-28",
411
+ },
412
+ )
413
+ dispatch(stream, {**WALL_CONNECTOR_TOTALS_EVENT, "id": SITE_B})
414
+ results.append(
415
+ check(
416
+ "listen_WallConnectorTotals parses totals, matches str/int id, filters other site",
417
+ wc_received
418
+ == [
419
+ WallConnectorTotalsEvent(
420
+ date="2026-07-29",
421
+ created_at=datetime(2026, 7, 29, 10, 16, 0, tzinfo=timezone.utc),
422
+ is_cache=False,
423
+ totals={"DIN-1": 12500.5, "DIN-2": 800},
424
+ ),
425
+ WallConnectorTotalsEvent(
426
+ date="2026-07-28",
427
+ created_at=datetime(2026, 7, 29, 10, 16, 0, tzinfo=timezone.utc),
428
+ is_cache=True,
429
+ totals={"DIN-1": 12500.5, "DIN-2": 800},
430
+ ),
431
+ ],
432
+ f"got {wc_received}",
433
+ )
434
+ )
435
+
436
+ # The two totals events share an envelope; each listener ignores the other's.
437
+ stream = make_stream()
438
+ site = stream.get_energysite(SITE_A)
439
+ wc_received = []
440
+ totals_received = []
441
+ site.listen_WallConnectorTotals(wc_received.append)
442
+ site.listen_EnergyTotals(totals_received.append)
443
+ dispatch(stream, ENERGY_TOTALS_EVENT)
444
+ dispatch(stream, {**WALL_CONNECTOR_TOTALS_EVENT, "totals": {}})
445
+ results.append(
446
+ check(
447
+ "energy_totals and wall_connector_totals do not cross-deliver",
448
+ len(totals_received) == 1 and len(wc_received) == 1 and wc_received[0].totals == {},
449
+ f"energy={totals_received} wc={wc_received}",
450
+ )
451
+ )
452
+
387
453
  # get_energysite is idempotent per id, mirroring get_vehicle.
388
454
  stream = make_stream()
389
455
  results.append(
@@ -0,0 +1,244 @@
1
+ """Regression tests: the access token must never reach the log.
2
+
3
+ aiohttp.ClientResponseError's repr embeds its RequestInfo, and with it the
4
+ request headers - including "Authorization: Bearer <token>". Logging
5
+ repr(error) on a stream error (e.g. a 5xx from the SSE endpoint) wrote the
6
+ token into every Home Assistant log that shipped it anywhere. These tests
7
+ fail any log record that contains the token, on the retry path (5xx), the
8
+ auth-failure path (401) and the listen-task path, and check _describe itself.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import contextlib
14
+ import logging
15
+ from typing import Any
16
+
17
+ import aiohttp
18
+ from multidict import CIMultiDict, CIMultiDictProxy
19
+ from yarl import URL
20
+
21
+ from teslemetry_stream.exception import TeslemetryStreamAuthenticationError
22
+ from teslemetry_stream.stream import LOGGER, TeslemetryStream, _describe
23
+
24
+ TOKEN = "s3cr3t-access-token-value"
25
+ REQUEST_INFO = aiohttp.RequestInfo(
26
+ url=URL("https://fake.teslemetry.com/sse"),
27
+ method="GET",
28
+ headers=CIMultiDictProxy(CIMultiDict({"Authorization": f"Bearer {TOKEN}"})),
29
+ real_url=URL("https://fake.teslemetry.com/sse"),
30
+ )
31
+
32
+
33
+ class FakeContent:
34
+ """Async-iterable response body that blocks until failed or cancelled."""
35
+
36
+ def __init__(self) -> None:
37
+ self._blocker: asyncio.Future[None] = asyncio.get_running_loop().create_future()
38
+
39
+ def __aiter__(self) -> FakeContent:
40
+ return self
41
+
42
+ async def __anext__(self) -> bytes:
43
+ await self._blocker
44
+ raise AssertionError("unreachable - blocker only resolves via an exception")
45
+
46
+ def fail(self, exc: BaseException) -> None:
47
+ if not self._blocker.done():
48
+ self._blocker.set_exception(exc)
49
+
50
+
51
+ class FakeResponse:
52
+ def __init__(self) -> None:
53
+ self.url = "https://fake.teslemetry.com/sse"
54
+ self.status = 200
55
+ self.content = FakeContent()
56
+ self.closed = False
57
+
58
+ def close(self) -> None:
59
+ self.closed = True
60
+
61
+
62
+ class FakeSession:
63
+ """Each `get()` raises or returns the next queued result."""
64
+
65
+ def __init__(self, get_results: list[Any]) -> None:
66
+ self.calls = 0
67
+ self._get_results = list(get_results)
68
+ self.responses: list[FakeResponse] = []
69
+
70
+ async def get(self, url: str, **kwargs: Any) -> FakeResponse:
71
+ self.calls += 1
72
+ result = self._get_results.pop(0)
73
+ if isinstance(result, BaseException):
74
+ raise result
75
+ self.responses.append(result)
76
+ return result
77
+
78
+
79
+ def make_stream(session: FakeSession) -> TeslemetryStream:
80
+ return TeslemetryStream(
81
+ session=session, # type: ignore[arg-type]
82
+ access_token=TOKEN,
83
+ server="api.teslemetry.com",
84
+ manual=True,
85
+ )
86
+
87
+
88
+ def response_error(status: int, message: str) -> aiohttp.ClientResponseError:
89
+ return aiohttp.ClientResponseError(
90
+ request_info=REQUEST_INFO, history=(), status=status, message=message
91
+ )
92
+
93
+
94
+ def check(label: str, ok: bool, detail: str = "") -> bool:
95
+ print(f"{label:<72} {'PASS' if ok else 'FAIL'}{' ' + detail if detail else ''}")
96
+ return ok
97
+
98
+
99
+ def leaked(records: list[logging.LogRecord]) -> list[str]:
100
+ return [r.getMessage() for r in records if TOKEN in r.getMessage()]
101
+
102
+
103
+ async def drain_cancelled(task: asyncio.Task[Any]) -> None:
104
+ with contextlib.suppress(asyncio.CancelledError):
105
+ await task
106
+
107
+
108
+ async def test_fixture_would_leak_through_repr(results: list[bool]) -> None:
109
+ """Guard: the fixture really carries the token in its repr, so the
110
+ other tests would catch a regression back to repr(error)."""
111
+ results.append(
112
+ check(
113
+ "repr(ClientResponseError) contains the token",
114
+ TOKEN in repr(response_error(500, "x")),
115
+ )
116
+ )
117
+
118
+
119
+ async def test_describe_omits_headers(results: list[bool]) -> None:
120
+ described = _describe(response_error(400, "Bad Request"))
121
+ results.append(check("_describe omits the token", TOKEN not in described, described))
122
+ results.append(
123
+ check(
124
+ "_describe keeps the type, status and message",
125
+ described.startswith("ClientResponseError: 400")
126
+ and "Bad Request" in described,
127
+ described,
128
+ )
129
+ )
130
+
131
+
132
+ async def test_server_error_does_not_log_token(results: list[bool]) -> None:
133
+ session = FakeSession([FakeResponse(), FakeResponse()])
134
+ stream = make_stream(session)
135
+
136
+ with CaptureLogs() as records:
137
+ task = asyncio.create_task(stream.listen())
138
+ await asyncio.sleep(0)
139
+ await asyncio.sleep(0)
140
+ session.responses[0].content.fail(response_error(502, "Bad Gateway"))
141
+ # retries starts at 0, so the first backoff delay is 2**0 == 1 second.
142
+ await asyncio.sleep(1.2)
143
+
144
+ warnings = [r for r in records if "Client error" in r.getMessage()]
145
+ results.append(
146
+ check("a 502 logs a Client error warning", len(warnings) == 1, f"got {warnings}")
147
+ )
148
+ results.append(
149
+ check(
150
+ "the warning keeps the status and message",
151
+ bool(warnings) and "502" in warnings[0].getMessage()
152
+ and "Bad Gateway" in warnings[0].getMessage(),
153
+ )
154
+ )
155
+ results.append(check("no log record contains the token (502)", not leaked(records)))
156
+
157
+ stream.close()
158
+ await drain_cancelled(task)
159
+
160
+
161
+ async def test_auth_failure_does_not_log_token(results: list[bool]) -> None:
162
+ session = FakeSession([response_error(401, "Unauthorized")])
163
+ stream = make_stream(session)
164
+
165
+ with CaptureLogs() as records, contextlib.suppress(TeslemetryStreamAuthenticationError):
166
+ await stream.listen()
167
+
168
+ auth_logs = [r.getMessage() for r in records if "Authentication failed" in r.getMessage()]
169
+ results.append(check("a 401 logs the authentication failure", len(auth_logs) == 1))
170
+ results.append(
171
+ check(
172
+ "the authentication log keeps the status and message",
173
+ bool(auth_logs) and "401" in auth_logs[0] and "Unauthorized" in auth_logs[0],
174
+ f"got {auth_logs}",
175
+ )
176
+ )
177
+ results.append(check("no log record contains the token (401)", not leaked(records)))
178
+
179
+
180
+ async def test_listen_ended_before_connect_does_not_log_token(results: list[bool]) -> None:
181
+ """A connection listener that raises while the first connect is failing
182
+ ends the listen task, which logs the escaping error."""
183
+ session = FakeSession([response_error(502, "Bad Gateway")])
184
+ stream = make_stream(session)
185
+
186
+ def failing_listener(connected: bool) -> None:
187
+ raise response_error(500, "listener failed")
188
+
189
+ stream.async_add_connection_listener(failing_listener)
190
+
191
+ with CaptureLogs() as records, contextlib.suppress(aiohttp.ClientResponseError):
192
+ await stream.listen()
193
+
194
+ ended = [r.getMessage() for r in records if "ended before its first connect" in r.getMessage()]
195
+ results.append(
196
+ check("the listen task logs ending before its first connect", len(ended) == 1)
197
+ )
198
+ results.append(
199
+ check("no log record contains the token (listen task)", not leaked(records))
200
+ )
201
+ stream.close()
202
+
203
+
204
+ class CaptureLogs:
205
+ """Minimal stand-in for pytest's caplog fixture, scoped to LOGGER."""
206
+
207
+ def __enter__(self) -> list[logging.LogRecord]:
208
+ self._records: list[logging.LogRecord] = []
209
+ self._handler = _ListHandler(self._records)
210
+ self._prev_level = LOGGER.level
211
+ LOGGER.addHandler(self._handler)
212
+ LOGGER.setLevel(logging.DEBUG)
213
+ return self._records
214
+
215
+ def __exit__(self, *exc_info: Any) -> None:
216
+ LOGGER.removeHandler(self._handler)
217
+ LOGGER.setLevel(self._prev_level)
218
+
219
+
220
+ class _ListHandler(logging.Handler):
221
+ def __init__(self, records: list[logging.LogRecord]) -> None:
222
+ super().__init__()
223
+ self._records = records
224
+
225
+ def emit(self, record: logging.LogRecord) -> None:
226
+ self._records.append(record)
227
+
228
+
229
+ async def main() -> None:
230
+ results: list[bool] = []
231
+ await test_fixture_would_leak_through_repr(results)
232
+ await test_describe_omits_headers(results)
233
+ await test_server_error_does_not_log_token(results)
234
+ await test_auth_failure_does_not_log_token(results)
235
+ await test_listen_ended_before_connect_does_not_log_token(results)
236
+
237
+ print("-" * 72)
238
+ print("ALL PASS" if all(results) else "FAILURES PRESENT")
239
+ if not all(results):
240
+ raise SystemExit(1)
241
+
242
+
243
+ if __name__ == "__main__":
244
+ asyncio.run(main())