|
| 1 | +"""Checks the SSE `cursor` resume: the stream keeps the last `cursor` an event |
| 2 | +carried and sends it back on a reconnect asking for the same vehicles and |
| 3 | +topics, so the connect snapshot starts after it. A first connect, or one |
| 4 | +whose vehicles or topics changed, omits it and takes a full snapshot. |
| 5 | +""" |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import asyncio |
| 9 | +import contextlib |
| 10 | +import json |
| 11 | +from typing import Any |
| 12 | + |
| 13 | +import aiohttp |
| 14 | + |
| 15 | +from teslemetry_stream.stream import TeslemetryStream |
| 16 | + |
| 17 | +VIN = "LRW3F7EK4NC000001" |
| 18 | + |
| 19 | + |
| 20 | +def line(event: dict[str, Any]) -> bytes: |
| 21 | + return f"data: {json.dumps(event)}\n".encode() |
| 22 | + |
| 23 | + |
| 24 | +def event(cursor: int | None = None) -> dict[str, Any]: |
| 25 | + ev: dict[str, Any] = { |
| 26 | + "vin": VIN, |
| 27 | + "createdAt": "2026-11-07T10:00:00.000Z", |
| 28 | + "data": {"Odometer": 1}, |
| 29 | + } |
| 30 | + if cursor is not None: |
| 31 | + ev["cursor"] = cursor |
| 32 | + return ev |
| 33 | + |
| 34 | + |
| 35 | +class FakeContent: |
| 36 | + """Response body that yields its lines once, then ends cleanly.""" |
| 37 | + |
| 38 | + def __init__(self, lines: list[bytes]) -> None: |
| 39 | + self._lines = list(lines) |
| 40 | + |
| 41 | + def __aiter__(self) -> FakeContent: |
| 42 | + return self |
| 43 | + |
| 44 | + async def __anext__(self) -> bytes: |
| 45 | + if not self._lines: |
| 46 | + raise StopAsyncIteration |
| 47 | + return self._lines.pop(0) |
| 48 | + |
| 49 | + |
| 50 | +class FakeResponse: |
| 51 | + def __init__(self, events: list[dict[str, Any]]) -> None: |
| 52 | + self.url = "https://fake.teslemetry.com/sse" |
| 53 | + self.status = 200 |
| 54 | + self.content = FakeContent([line(e) for e in events]) |
| 55 | + |
| 56 | + def close(self) -> None: |
| 57 | + pass |
| 58 | + |
| 59 | + |
| 60 | +class FakeSession: |
| 61 | + def __init__(self, responses: list[FakeResponse | Exception]) -> None: |
| 62 | + self._responses = list(responses) |
| 63 | + self.calls: list[dict[str, Any]] = [] |
| 64 | + |
| 65 | + async def get(self, url: str, **kwargs: Any) -> FakeResponse: |
| 66 | + self.calls.append({"url": url, **kwargs}) |
| 67 | + response = self._responses.pop(0) |
| 68 | + if isinstance(response, Exception): |
| 69 | + raise response |
| 70 | + return response |
| 71 | + |
| 72 | + |
| 73 | +def make_stream(session: FakeSession, **kwargs: Any) -> TeslemetryStream: |
| 74 | + return TeslemetryStream( |
| 75 | + session=session, # type: ignore[arg-type] |
| 76 | + access_token="test-token", |
| 77 | + server="api.teslemetry.com", |
| 78 | + manual=True, |
| 79 | + **kwargs, |
| 80 | + ) |
| 81 | + |
| 82 | + |
| 83 | +def sent_cursor(session: FakeSession, index: int) -> str | None: |
| 84 | + return session.calls[index]["params"].get("cursor") |
| 85 | + |
| 86 | + |
| 87 | +def check(label: str, ok: bool, detail: str = "") -> bool: |
| 88 | + print(f"{label:<72} {'PASS' if ok else 'FAIL'}{' ' + detail if detail else ''}") |
| 89 | + return ok |
| 90 | + |
| 91 | + |
| 92 | +async def test_resume(results: list[bool]) -> None: |
| 93 | + session = FakeSession( |
| 94 | + [ |
| 95 | + FakeResponse([event(5), event()]), |
| 96 | + FakeResponse([event(9)]), |
| 97 | + FakeResponse([event()]), |
| 98 | + ] |
| 99 | + ) |
| 100 | + stream = make_stream(session, topics=["data"]) |
| 101 | + stream.active = True |
| 102 | + |
| 103 | + await stream.__anext__() |
| 104 | + results.append( |
| 105 | + check("first connect omits cursor", sent_cursor(session, 0) is None) |
| 106 | + ) |
| 107 | + results.append(check("cursor tracked from an event", stream._cursor == 5)) |
| 108 | + |
| 109 | + await stream.__anext__() |
| 110 | + results.append( |
| 111 | + check("an event without cursor keeps the last value", stream._cursor == 5) |
| 112 | + ) |
| 113 | + |
| 114 | + await stream.__anext__() # body ends, reconnects |
| 115 | + results.append( |
| 116 | + check( |
| 117 | + "reconnect sends the last cursor", |
| 118 | + sent_cursor(session, 1) == "5", |
| 119 | + f"got {sent_cursor(session, 1)!r}", |
| 120 | + ) |
| 121 | + ) |
| 122 | + results.append( |
| 123 | + check( |
| 124 | + "cursor sent next to cache=true", |
| 125 | + session.calls[1]["params"].get("cache") == "true", |
| 126 | + ) |
| 127 | + ) |
| 128 | + |
| 129 | + stream.topics = ["data", "alerts"] |
| 130 | + await stream.__anext__() # body ends, reconnects with new topics |
| 131 | + results.append( |
| 132 | + check( |
| 133 | + "reconnect after a topic change omits cursor", |
| 134 | + sent_cursor(session, 2) is None, |
| 135 | + f"got {sent_cursor(session, 2)!r}", |
| 136 | + ) |
| 137 | + ) |
| 138 | + results.append( |
| 139 | + check("topic change discards the old cursor", stream._cursor is None) |
| 140 | + ) |
| 141 | + |
| 142 | + |
| 143 | +async def test_vehicle_change(results: list[bool]) -> None: |
| 144 | + session = FakeSession( |
| 145 | + [FakeResponse([event(5)]), FakeResponse([event()])] |
| 146 | + ) |
| 147 | + stream = make_stream(session, vin=VIN) |
| 148 | + stream.active = True |
| 149 | + |
| 150 | + await stream.__anext__() |
| 151 | + stream.vin = "LRW3F7EK4NC000002" |
| 152 | + await stream.__anext__() # body ends, reconnects for another vehicle |
| 153 | + results.append( |
| 154 | + check( |
| 155 | + "reconnect after a vehicle change omits cursor", |
| 156 | + sent_cursor(session, 1) is None, |
| 157 | + f"got {sent_cursor(session, 1)!r}", |
| 158 | + ) |
| 159 | + ) |
| 160 | + |
| 161 | + |
| 162 | +async def test_failed_connect_after_topic_change(results: list[bool]) -> None: |
| 163 | + session = FakeSession( |
| 164 | + [ |
| 165 | + FakeResponse([event(5), event(7)]), |
| 166 | + aiohttp.ClientError("refused"), |
| 167 | + FakeResponse([event()]), |
| 168 | + ] |
| 169 | + ) |
| 170 | + stream = make_stream(session, topics=["data"]) |
| 171 | + stream.active = True |
| 172 | + |
| 173 | + await stream.__anext__() |
| 174 | + stream.topics = ["data", "alerts"] |
| 175 | + with contextlib.suppress(aiohttp.ClientError): |
| 176 | + await stream.connect() # GET with the new topics fails |
| 177 | + await stream.__anext__() # the old response is still supplying cursors |
| 178 | + await stream.__anext__() # old body ends, reconnects with the new topics |
| 179 | + results.append( |
| 180 | + check( |
| 181 | + "old response's cursor is not sent for the new topics", |
| 182 | + sent_cursor(session, 2) is None, |
| 183 | + f"got {sent_cursor(session, 2)!r}", |
| 184 | + ) |
| 185 | + ) |
| 186 | + |
| 187 | + |
| 188 | +async def main() -> int: |
| 189 | + results: list[bool] = [] |
| 190 | + await test_resume(results) |
| 191 | + await test_vehicle_change(results) |
| 192 | + await test_failed_connect_after_topic_change(results) |
| 193 | + passed = sum(results) |
| 194 | + print(f"\n{passed}/{len(results)} checks passed") |
| 195 | + return 0 if passed == len(results) else 1 |
| 196 | + |
| 197 | + |
| 198 | +if __name__ == "__main__": |
| 199 | + raise SystemExit(asyncio.run(main())) |
0 commit comments