infrared-remotes-client 0.1.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.
@@ -0,0 +1 @@
1
+ recursive-include tests *.py *.json
@@ -0,0 +1,112 @@
1
+ Metadata-Version: 2.4
2
+ Name: infrared-remotes-client
3
+ Version: 0.1.0
4
+ Summary: Async client for the Infrared remotes catalog API
5
+ Requires-Python: >=3.11
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: aiohttp<4,>=3.9
8
+
9
+ # Infrared remotes client
10
+
11
+ `infrared-remotes-client` is an async Python 3.11+ client for schema v2 of
12
+ the Infrared remotes catalog. It takes an existing `aiohttp.ClientSession`.
13
+ The caller manages the session and supplies the catalog bearer token.
14
+
15
+ ## Usage
16
+
17
+ ```sh
18
+ python -m pip install infrared-remotes-client
19
+ ```
20
+
21
+ ```python
22
+ import asyncio
23
+ import os
24
+
25
+ from aiohttp import ClientSession
26
+ from infrared_remotes_client import DEFAULT_URL, CatalogClient
27
+
28
+
29
+ async def main():
30
+ async with ClientSession() as session:
31
+ client = CatalogClient(session, DEFAULT_URL, os.environ["IR_CATALOG_TOKEN"])
32
+ metadata = await client.metadata()
33
+ print(metadata["archive_revision"])
34
+
35
+ page = await client.search("Sony")
36
+ while True:
37
+ for model in page["devices"]:
38
+ print(model["id"], model["brand"], model["model"])
39
+ if page["next_offset"] is None:
40
+ break
41
+ page = await client.search("Sony", offset=page["next_offset"])
42
+
43
+
44
+ asyncio.run(main())
45
+ ```
46
+
47
+ - `metadata()` returns the catalog schema version and archive revision.
48
+ - `search(query, offset=0)` returns up to 25 prefix matches. Use the same query
49
+ and the returned `next_offset` to fetch the next page. A null offset ends
50
+ pagination.
51
+ - `match(captures)` posts a list of capture dictionaries. Use signed integer
52
+ microseconds in `timings`, with positive pulses alternating with negative
53
+ spaces. An optional `command` is the exact archive command name prompted
54
+ for that capture. The response includes the catalog revision, ranked
55
+ candidates and model aliases, and a suggested `next_command` when available.
56
+ The possible statuses are `matched`, `ambiguous`, `no_match`, and
57
+ `insufficient_evidence`.
58
+ - `profile(device_id)` returns the catalog metadata and device profile,
59
+ including archived Pronto commands when available.
60
+
61
+ The client preserves JSON field names and values. It sends a bearer token
62
+ only to the configured HTTPS origin, uses standard session TLS verification,
63
+ disables redirects and applies a 10-second timeout per request.
64
+ `CatalogAuthError` reports HTTP 401 or 403 and is a subclass of
65
+ `CatalogError`. Other HTTP failures, transport failures, and unusable
66
+ responses raise `CatalogError`. Malformed origins and invalid device IDs
67
+ raise `ValueError`.
68
+
69
+ ## Home Assistant integration
70
+
71
+ Pin the released version in the integration's `manifest.json` under
72
+ `requirements`.
73
+
74
+ ```json
75
+ {
76
+ "requirements": ["infrared-remotes-client==0.1.0"]
77
+ }
78
+ ```
79
+
80
+ Instantiate the client using Home Assistant's shared session. Home Assistant
81
+ owns that session.
82
+
83
+ ```python
84
+ from homeassistant.helpers.aiohttp_client import async_get_clientsession
85
+ from infrared_remotes_client import DEFAULT_URL, CatalogClient
86
+
87
+ client = CatalogClient(async_get_clientsession(hass), DEFAULT_URL, token)
88
+ ```
89
+
90
+ For Home Assistant Core, a dependency needs a PyPI source distribution,
91
+ a public repository with a tag for each PyPI release, automated publishing,
92
+ an issue tracker for API libraries, and an OSI-approved license declared in
93
+ the package metadata. Dependencies must also have OSI-approved licenses.
94
+
95
+ [Home Assistant Python library requirements](https://contributors.home-assistant.io/core/integrations/api-library/#requirements) ·
96
+ [Home Assistant manifest requirements](https://contributors.home-assistant.io/core/integrations/manifest/#requirements)
97
+
98
+ ## Build and test locally
99
+
100
+ Run from the project directory. The test suite reuses the upstream API's
101
+ synthetic timing captures and models responses after its fixture contract.
102
+
103
+ ```sh
104
+ python -m pip install .
105
+ python -m unittest discover -s tests -v
106
+ python -m pip install build
107
+ python -m build --outdir ../dist
108
+ ```
109
+
110
+ To smoke-test the built wheel in a fresh virtual environment, install
111
+ `../dist/infrared_remotes_client-0.1.0-py3-none-any.whl` and rerun the same
112
+ test suite using that environment's Python.
@@ -0,0 +1,104 @@
1
+ # Infrared remotes client
2
+
3
+ `infrared-remotes-client` is an async Python 3.11+ client for schema v2 of
4
+ the Infrared remotes catalog. It takes an existing `aiohttp.ClientSession`.
5
+ The caller manages the session and supplies the catalog bearer token.
6
+
7
+ ## Usage
8
+
9
+ ```sh
10
+ python -m pip install infrared-remotes-client
11
+ ```
12
+
13
+ ```python
14
+ import asyncio
15
+ import os
16
+
17
+ from aiohttp import ClientSession
18
+ from infrared_remotes_client import DEFAULT_URL, CatalogClient
19
+
20
+
21
+ async def main():
22
+ async with ClientSession() as session:
23
+ client = CatalogClient(session, DEFAULT_URL, os.environ["IR_CATALOG_TOKEN"])
24
+ metadata = await client.metadata()
25
+ print(metadata["archive_revision"])
26
+
27
+ page = await client.search("Sony")
28
+ while True:
29
+ for model in page["devices"]:
30
+ print(model["id"], model["brand"], model["model"])
31
+ if page["next_offset"] is None:
32
+ break
33
+ page = await client.search("Sony", offset=page["next_offset"])
34
+
35
+
36
+ asyncio.run(main())
37
+ ```
38
+
39
+ - `metadata()` returns the catalog schema version and archive revision.
40
+ - `search(query, offset=0)` returns up to 25 prefix matches. Use the same query
41
+ and the returned `next_offset` to fetch the next page. A null offset ends
42
+ pagination.
43
+ - `match(captures)` posts a list of capture dictionaries. Use signed integer
44
+ microseconds in `timings`, with positive pulses alternating with negative
45
+ spaces. An optional `command` is the exact archive command name prompted
46
+ for that capture. The response includes the catalog revision, ranked
47
+ candidates and model aliases, and a suggested `next_command` when available.
48
+ The possible statuses are `matched`, `ambiguous`, `no_match`, and
49
+ `insufficient_evidence`.
50
+ - `profile(device_id)` returns the catalog metadata and device profile,
51
+ including archived Pronto commands when available.
52
+
53
+ The client preserves JSON field names and values. It sends a bearer token
54
+ only to the configured HTTPS origin, uses standard session TLS verification,
55
+ disables redirects and applies a 10-second timeout per request.
56
+ `CatalogAuthError` reports HTTP 401 or 403 and is a subclass of
57
+ `CatalogError`. Other HTTP failures, transport failures, and unusable
58
+ responses raise `CatalogError`. Malformed origins and invalid device IDs
59
+ raise `ValueError`.
60
+
61
+ ## Home Assistant integration
62
+
63
+ Pin the released version in the integration's `manifest.json` under
64
+ `requirements`.
65
+
66
+ ```json
67
+ {
68
+ "requirements": ["infrared-remotes-client==0.1.0"]
69
+ }
70
+ ```
71
+
72
+ Instantiate the client using Home Assistant's shared session. Home Assistant
73
+ owns that session.
74
+
75
+ ```python
76
+ from homeassistant.helpers.aiohttp_client import async_get_clientsession
77
+ from infrared_remotes_client import DEFAULT_URL, CatalogClient
78
+
79
+ client = CatalogClient(async_get_clientsession(hass), DEFAULT_URL, token)
80
+ ```
81
+
82
+ For Home Assistant Core, a dependency needs a PyPI source distribution,
83
+ a public repository with a tag for each PyPI release, automated publishing,
84
+ an issue tracker for API libraries, and an OSI-approved license declared in
85
+ the package metadata. Dependencies must also have OSI-approved licenses.
86
+
87
+ [Home Assistant Python library requirements](https://contributors.home-assistant.io/core/integrations/api-library/#requirements) ·
88
+ [Home Assistant manifest requirements](https://contributors.home-assistant.io/core/integrations/manifest/#requirements)
89
+
90
+ ## Build and test locally
91
+
92
+ Run from the project directory. The test suite reuses the upstream API's
93
+ synthetic timing captures and models responses after its fixture contract.
94
+
95
+ ```sh
96
+ python -m pip install .
97
+ python -m unittest discover -s tests -v
98
+ python -m pip install build
99
+ python -m build --outdir ../dist
100
+ ```
101
+
102
+ To smoke-test the built wheel in a fresh virtual environment, install
103
+ `../dist/infrared_remotes_client-0.1.0-py3-none-any.whl` and rerun the same
104
+ test suite using that environment's Python.
@@ -0,0 +1,17 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "infrared-remotes-client"
7
+ version = "0.1.0"
8
+ description = "Async client for the Infrared remotes catalog API"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ dependencies = ["aiohttp>=3.9,<4"]
12
+
13
+ [tool.setuptools.packages.find]
14
+ where = ["src"]
15
+
16
+ [tool.setuptools.package-data]
17
+ infrared_remotes_client = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,141 @@
1
+ """Async client for the Infrared remotes catalog."""
2
+
3
+ from typing import Any
4
+ from urllib.parse import urlsplit
5
+
6
+ from aiohttp import ClientError, ClientSession, ClientTimeout
7
+
8
+ __all__ = [
9
+ "DEFAULT_URL",
10
+ "SCHEMA_VERSION",
11
+ "CatalogAuthError",
12
+ "CatalogClient",
13
+ "CatalogError",
14
+ "catalog_url",
15
+ ]
16
+
17
+ DEFAULT_URL = "https://ir.jcisio.com"
18
+ SCHEMA_VERSION = 2
19
+ _REQUEST_TIMEOUT = ClientTimeout(total=10)
20
+ _MATCH_STATUSES = ("matched", "ambiguous", "no_match", "insufficient_evidence")
21
+
22
+
23
+ class CatalogError(Exception):
24
+ """The catalog request failed or the response was unusable."""
25
+
26
+
27
+ class CatalogAuthError(CatalogError):
28
+ """The catalog rejected authentication."""
29
+
30
+
31
+ def catalog_url(url: str) -> str:
32
+ """Normalize an HTTPS origin for use with the catalog."""
33
+ origin = url.strip().rstrip("/")
34
+ if any(char.isspace() or ord(char) < 32 or ord(char) == 127 for char in origin):
35
+ raise ValueError("Invalid catalog URL")
36
+ try:
37
+ parts = urlsplit(origin)
38
+ port = parts.port
39
+ except ValueError:
40
+ raise ValueError("Invalid catalog URL") from None
41
+ if (
42
+ parts.scheme != "https"
43
+ or not parts.hostname
44
+ or parts.username is not None
45
+ or parts.path
46
+ or port == 0
47
+ or any(char in origin for char in "?#\\")
48
+ ):
49
+ raise ValueError("Invalid catalog URL")
50
+ return origin
51
+
52
+
53
+ def _check_catalog(data: Any) -> None:
54
+ if (
55
+ not isinstance(data, dict)
56
+ or type(data.get("schema_version")) is not int
57
+ or data["schema_version"] != SCHEMA_VERSION
58
+ or not isinstance(data.get("archive_revision"), str)
59
+ or not data["archive_revision"]
60
+ ):
61
+ raise CatalogError("Missing or unsupported catalog metadata")
62
+
63
+
64
+ class CatalogClient:
65
+ """Use a caller-owned aiohttp session to query the catalog."""
66
+
67
+ def __init__(self, session: ClientSession, url: str, token: str) -> None:
68
+ self._session = session
69
+ self._url = catalog_url(url)
70
+ self._headers = {"Authorization": f"Bearer {token}"}
71
+
72
+ async def _request(
73
+ self, method: str, path: str, **kwargs: Any
74
+ ) -> dict[str, Any]:
75
+ try:
76
+ async with self._session.request(
77
+ method,
78
+ f"{self._url}/v1/{path}",
79
+ headers=self._headers,
80
+ timeout=_REQUEST_TIMEOUT,
81
+ allow_redirects=False,
82
+ raise_for_status=False,
83
+ **kwargs,
84
+ ) as response:
85
+ if response.status in (401, 403):
86
+ raise CatalogAuthError(
87
+ f"Catalog rejected authentication (HTTP {response.status})"
88
+ )
89
+ if response.status != 200:
90
+ raise CatalogError(f"Catalog returned HTTP {response.status}")
91
+ data = await response.json()
92
+ except (ClientError, TimeoutError, ValueError) as err:
93
+ raise CatalogError("Unable to read the catalog response") from err
94
+ if not isinstance(data, dict):
95
+ raise CatalogError("Expected a JSON object from the catalog")
96
+ return data
97
+
98
+ async def metadata(self) -> dict[str, Any]:
99
+ """Get the catalog schema version and archive revision."""
100
+ data = await self._request("GET", "catalog")
101
+ _check_catalog(data)
102
+ return data
103
+
104
+ async def search(self, query: str, offset: int = 0) -> dict[str, Any]:
105
+ """Get one page of model results and its next offset, if any."""
106
+ data = await self._request("GET", "devices", params={"q": query, "offset": offset})
107
+ if not isinstance(data.get("devices"), list):
108
+ raise CatalogError("Invalid catalog search results")
109
+ next_offset = data.get("next_offset")
110
+ if "next_offset" not in data or (
111
+ next_offset is not None
112
+ and (type(next_offset) is not int or not offset < next_offset <= 9999)
113
+ ):
114
+ raise CatalogError("Invalid catalog search page offset")
115
+ return data
116
+
117
+ async def match(self, captures: list[dict[str, Any]]) -> dict[str, Any]:
118
+ """Match signed microsecond timings, optionally with command names."""
119
+ data = await self._request("POST", "matches", json={"captures": captures})
120
+ _check_catalog(data.get("catalog"))
121
+ if data.get("status") not in _MATCH_STATUSES or not isinstance(
122
+ data.get("candidates"), list
123
+ ):
124
+ raise CatalogError("Invalid catalog match results")
125
+ return data
126
+
127
+ async def profile(self, device_id: int) -> dict[str, Any]:
128
+ """Get the catalog metadata and device profile for a numeric ID."""
129
+ if type(device_id) is not int or not 1 <= device_id <= 9_999_999_999:
130
+ raise ValueError("Expected a positive device ID of up to ten digits")
131
+ data = await self._request("GET", f"devices/{device_id}/profile")
132
+ _check_catalog(data.get("catalog"))
133
+ device = data.get("device")
134
+ if (
135
+ not isinstance(device, dict)
136
+ or type(device.get("id")) is not int
137
+ or device["id"] != device_id
138
+ or not isinstance(device.get("commands"), list)
139
+ ):
140
+ raise CatalogError("Invalid catalog device profile")
141
+ return data
@@ -0,0 +1,112 @@
1
+ Metadata-Version: 2.4
2
+ Name: infrared-remotes-client
3
+ Version: 0.1.0
4
+ Summary: Async client for the Infrared remotes catalog API
5
+ Requires-Python: >=3.11
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: aiohttp<4,>=3.9
8
+
9
+ # Infrared remotes client
10
+
11
+ `infrared-remotes-client` is an async Python 3.11+ client for schema v2 of
12
+ the Infrared remotes catalog. It takes an existing `aiohttp.ClientSession`.
13
+ The caller manages the session and supplies the catalog bearer token.
14
+
15
+ ## Usage
16
+
17
+ ```sh
18
+ python -m pip install infrared-remotes-client
19
+ ```
20
+
21
+ ```python
22
+ import asyncio
23
+ import os
24
+
25
+ from aiohttp import ClientSession
26
+ from infrared_remotes_client import DEFAULT_URL, CatalogClient
27
+
28
+
29
+ async def main():
30
+ async with ClientSession() as session:
31
+ client = CatalogClient(session, DEFAULT_URL, os.environ["IR_CATALOG_TOKEN"])
32
+ metadata = await client.metadata()
33
+ print(metadata["archive_revision"])
34
+
35
+ page = await client.search("Sony")
36
+ while True:
37
+ for model in page["devices"]:
38
+ print(model["id"], model["brand"], model["model"])
39
+ if page["next_offset"] is None:
40
+ break
41
+ page = await client.search("Sony", offset=page["next_offset"])
42
+
43
+
44
+ asyncio.run(main())
45
+ ```
46
+
47
+ - `metadata()` returns the catalog schema version and archive revision.
48
+ - `search(query, offset=0)` returns up to 25 prefix matches. Use the same query
49
+ and the returned `next_offset` to fetch the next page. A null offset ends
50
+ pagination.
51
+ - `match(captures)` posts a list of capture dictionaries. Use signed integer
52
+ microseconds in `timings`, with positive pulses alternating with negative
53
+ spaces. An optional `command` is the exact archive command name prompted
54
+ for that capture. The response includes the catalog revision, ranked
55
+ candidates and model aliases, and a suggested `next_command` when available.
56
+ The possible statuses are `matched`, `ambiguous`, `no_match`, and
57
+ `insufficient_evidence`.
58
+ - `profile(device_id)` returns the catalog metadata and device profile,
59
+ including archived Pronto commands when available.
60
+
61
+ The client preserves JSON field names and values. It sends a bearer token
62
+ only to the configured HTTPS origin, uses standard session TLS verification,
63
+ disables redirects and applies a 10-second timeout per request.
64
+ `CatalogAuthError` reports HTTP 401 or 403 and is a subclass of
65
+ `CatalogError`. Other HTTP failures, transport failures, and unusable
66
+ responses raise `CatalogError`. Malformed origins and invalid device IDs
67
+ raise `ValueError`.
68
+
69
+ ## Home Assistant integration
70
+
71
+ Pin the released version in the integration's `manifest.json` under
72
+ `requirements`.
73
+
74
+ ```json
75
+ {
76
+ "requirements": ["infrared-remotes-client==0.1.0"]
77
+ }
78
+ ```
79
+
80
+ Instantiate the client using Home Assistant's shared session. Home Assistant
81
+ owns that session.
82
+
83
+ ```python
84
+ from homeassistant.helpers.aiohttp_client import async_get_clientsession
85
+ from infrared_remotes_client import DEFAULT_URL, CatalogClient
86
+
87
+ client = CatalogClient(async_get_clientsession(hass), DEFAULT_URL, token)
88
+ ```
89
+
90
+ For Home Assistant Core, a dependency needs a PyPI source distribution,
91
+ a public repository with a tag for each PyPI release, automated publishing,
92
+ an issue tracker for API libraries, and an OSI-approved license declared in
93
+ the package metadata. Dependencies must also have OSI-approved licenses.
94
+
95
+ [Home Assistant Python library requirements](https://contributors.home-assistant.io/core/integrations/api-library/#requirements) ·
96
+ [Home Assistant manifest requirements](https://contributors.home-assistant.io/core/integrations/manifest/#requirements)
97
+
98
+ ## Build and test locally
99
+
100
+ Run from the project directory. The test suite reuses the upstream API's
101
+ synthetic timing captures and models responses after its fixture contract.
102
+
103
+ ```sh
104
+ python -m pip install .
105
+ python -m unittest discover -s tests -v
106
+ python -m pip install build
107
+ python -m build --outdir ../dist
108
+ ```
109
+
110
+ To smoke-test the built wheel in a fresh virtual environment, install
111
+ `../dist/infrared_remotes_client-0.1.0-py3-none-any.whl` and rerun the same
112
+ test suite using that environment's Python.
@@ -0,0 +1,13 @@
1
+ MANIFEST.in
2
+ README.md
3
+ pyproject.toml
4
+ src/infrared_remotes_client/__init__.py
5
+ src/infrared_remotes_client/py.typed
6
+ src/infrared_remotes_client.egg-info/PKG-INFO
7
+ src/infrared_remotes_client.egg-info/SOURCES.txt
8
+ src/infrared_remotes_client.egg-info/dependency_links.txt
9
+ src/infrared_remotes_client.egg-info/requires.txt
10
+ src/infrared_remotes_client.egg-info/top_level.txt
11
+ tests/test_client.py
12
+ tests/fixtures/captures.json
13
+ tests/fixtures/responses.json
@@ -0,0 +1,6 @@
1
+ {
2
+ "initial": {"timings": [4196, -2090, 526, -1052, 526, -526, 526, -1052, 526]},
3
+ "followup": {"command": "Mute", "timings": [4208, -2104, 526, -526, 526, -526, 526, -526, 526]},
4
+ "unknown": {"timings": [1600, -900, 500, -500, 500, -1500, 500, -500, 500, -1500, 500]},
5
+ "repeat_only": {"timings": [9000, -2250, 560]}
6
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "catalog": {"schema_version": 2, "archive_revision": "fixture-revision"},
3
+ "speaker": {"id": 1, "brand": "Fixture", "model": "Speaker", "coverage": "playable"},
4
+ "alias": {"id": 2, "brand": "Fixture", "model": "Speaker alias", "coverage": "playable"},
5
+ "receiver": {"id": 3, "brand": "Fixture", "model": "Receiver", "coverage": "playable"},
6
+ "missing": {"id": 4, "brand": "Fixture", "model": "Missing", "coverage": "missing"},
7
+ "commands": [
8
+ {"name": "VolumeDown", "pronto": "0000 006D 0005 0000 00A0 0050 0014 0028 0014 0014 0014 0028 0014 0100"},
9
+ {"name": "Mute", "pronto": "0000 006D 0005 0000 00A0 0050 0014 0014 0014 0014 0014 0014 0014 0100"}
10
+ ]
11
+ }
@@ -0,0 +1,188 @@
1
+ """Exercise the API fixture contract without a network or live credentials."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+ import unittest
6
+ from unittest.mock import AsyncMock, MagicMock
7
+
8
+ from aiohttp import ClientConnectionError, ClientSession
9
+
10
+ from infrared_remotes_client import (
11
+ DEFAULT_URL,
12
+ CatalogAuthError,
13
+ CatalogClient,
14
+ CatalogError,
15
+ catalog_url,
16
+ )
17
+
18
+ FIXTURES = Path(__file__).parent / "fixtures"
19
+ CAPTURES = json.loads((FIXTURES / "captures.json").read_text())
20
+ RESPONSES = json.loads((FIXTURES / "responses.json").read_text())
21
+ TOKEN = "fixture-only-token"
22
+
23
+
24
+ class CatalogClientTests(unittest.IsolatedAsyncioTestCase):
25
+ def setUp(self) -> None:
26
+ self.session = MagicMock(spec=ClientSession)
27
+ self.response = self.session.request.return_value.__aenter__.return_value
28
+ self.response.status = 200
29
+ self.response.json = AsyncMock()
30
+ self.client = CatalogClient(self.session, f" {DEFAULT_URL}/ ", TOKEN)
31
+
32
+ def assert_request(self, method, path, **expected):
33
+ request = self.session.request.call_args
34
+ self.assertEqual(request.args, (method, f"{DEFAULT_URL}/v1/{path}"))
35
+ self.assertEqual(request.kwargs["headers"]["Authorization"], f"Bearer {TOKEN}")
36
+ self.assertEqual(request.kwargs["timeout"].total, 10)
37
+ self.assertFalse(request.kwargs["allow_redirects"])
38
+ self.assertFalse(request.kwargs["raise_for_status"])
39
+ for name, value in expected.items():
40
+ self.assertEqual(request.kwargs[name], value)
41
+
42
+ async def test_metadata_uses_the_caller_session(self):
43
+ self.response.json.return_value = RESPONSES["catalog"]
44
+ self.assertEqual(await self.client.metadata(), RESPONSES["catalog"])
45
+ self.assert_request("GET", "catalog")
46
+ self.session.request.return_value.__aexit__.assert_awaited_once()
47
+ self.session.close.assert_not_called()
48
+
49
+ async def test_search_pagination_and_empty_results(self):
50
+ # The upstream fixture has four models. Add synthetic rows to fill page one.
51
+ devices = [
52
+ {**RESPONSES["speaker"], "id": index, "model": f"Speaker {index:02d}"}
53
+ for index in range(10, 35)
54
+ ]
55
+ first = {"devices": devices, "next_offset": 25}
56
+ last = {"devices": [RESPONSES["alias"]], "next_offset": None}
57
+ empty = {"devices": [], "next_offset": None}
58
+ self.response.json.side_effect = [first, last, empty]
59
+ self.assertEqual(await self.client.search("Fixture Sp"), first)
60
+ self.assert_request("GET", "devices", params={"q": "Fixture Sp", "offset": 0})
61
+ self.assertEqual(await self.client.search("Fixture Sp", first["next_offset"]), last)
62
+ self.assert_request("GET", "devices", params={"q": "Fixture Sp", "offset": 25})
63
+ self.assertEqual(await self.client.search("no such model"), empty)
64
+
65
+ async def test_matching_outcomes(self):
66
+ speaker = {
67
+ "distance": 0.01,
68
+ "models": [
69
+ {key: model[key] for key in ("id", "brand", "model")}
70
+ for model in (RESPONSES["speaker"], RESPONSES["alias"])
71
+ ],
72
+ "more_models": False,
73
+ }
74
+ receiver = {
75
+ "distance": 0.01,
76
+ "models": [{
77
+ key: RESPONSES["receiver"][key] for key in ("id", "brand", "model")
78
+ }],
79
+ "more_models": False,
80
+ }
81
+ cases = (
82
+ ("ambiguous", ["initial"], [speaker, receiver], "Mute"),
83
+ ("matched", ["initial", "followup"], [speaker], None),
84
+ ("no_match", ["unknown"], [], None),
85
+ ("insufficient_evidence", ["repeat_only"], [], None),
86
+ )
87
+ for status, signals, candidates, next_command in cases:
88
+ with self.subTest(status=status):
89
+ captures = [CAPTURES[signal] for signal in signals]
90
+ result = {
91
+ "catalog": RESPONSES["catalog"],
92
+ "status": status,
93
+ "candidates": candidates,
94
+ "next_command": next_command,
95
+ }
96
+ self.response.json.return_value = result
97
+ self.assertEqual(await self.client.match(captures), result)
98
+ self.assert_request("POST", "matches", json={"captures": captures})
99
+
100
+ async def test_profile_preserves_pronto_and_missing_coverage(self):
101
+ for model, commands in (
102
+ (RESPONSES["speaker"], RESPONSES["commands"]),
103
+ (RESPONSES["missing"], []),
104
+ ):
105
+ with self.subTest(device=model["id"]):
106
+ profile = {
107
+ "catalog": RESPONSES["catalog"],
108
+ "device": {**model, "metadata": {}, "commands": commands},
109
+ }
110
+ self.response.json.return_value = profile
111
+ self.assertEqual(await self.client.profile(model["id"]), profile)
112
+ self.assert_request("GET", f"devices/{model['id']}/profile")
113
+
114
+ async def test_authentication_redirect_and_http_failures(self):
115
+ for status, error in (
116
+ (401, CatalogAuthError),
117
+ (403, CatalogAuthError),
118
+ (302, CatalogError),
119
+ (400, CatalogError),
120
+ (404, CatalogError),
121
+ (503, CatalogError),
122
+ ):
123
+ with self.subTest(status=status):
124
+ self.response.status = status
125
+ with self.assertRaisesRegex(error, f"HTTP {status}") as caught:
126
+ await self.client.profile(1)
127
+ self.assertIs(type(caught.exception), error)
128
+ self.assertNotIn(TOKEN, str(caught.exception))
129
+ self.response.json.assert_not_awaited()
130
+
131
+ async def test_transport_timeout_and_bad_json(self):
132
+ for error in (
133
+ ClientConnectionError(),
134
+ TimeoutError(),
135
+ json.JSONDecodeError("invalid JSON", "", 0),
136
+ ):
137
+ with self.subTest(error=type(error)):
138
+ self.response.json.side_effect = error
139
+ with self.assertRaises(CatalogError):
140
+ await self.client.metadata()
141
+
142
+ async def test_rejects_unusable_catalog_data(self):
143
+ cases = (
144
+ (self.client.metadata, (), []),
145
+ (self.client.metadata, (), {"schema_version": 1, "archive_revision": "old"}),
146
+ (self.client.metadata, (), {"schema_version": 2}),
147
+ (self.client.search, ("Speaker",), {"devices": [], "next_offset": 0}),
148
+ (self.client.search, ("Speaker",), {"devices": {}}),
149
+ (self.client.match, ([],), {"catalog": RESPONSES["catalog"], "status": []}),
150
+ (
151
+ self.client.profile,
152
+ (1,),
153
+ {"catalog": RESPONSES["catalog"], "device": {"id": 2, "commands": []}},
154
+ ),
155
+ )
156
+ for method, args, data in cases:
157
+ with self.subTest(method=method.__name__, data=data):
158
+ self.response.json.return_value = data
159
+ with self.assertRaises(CatalogError):
160
+ await method(*args)
161
+
162
+ async def test_invalid_profile_ids_never_reach_the_session(self):
163
+ for device_id in (0, -1, True, 10_000_000_000, "1/profile"):
164
+ with self.subTest(device_id=device_id), self.assertRaises(ValueError):
165
+ await self.client.profile(device_id)
166
+ self.session.request.assert_not_called()
167
+
168
+
169
+ class CatalogUrlTests(unittest.TestCase):
170
+ def test_https_origins(self):
171
+ self.assertEqual(catalog_url(f" {DEFAULT_URL}/ "), DEFAULT_URL)
172
+ self.assertEqual(catalog_url("https://[::1]:8443/"), "https://[::1]:8443")
173
+
174
+ def test_rejects_unsafe_or_malformed_urls_before_request(self):
175
+ for url in (
176
+ "http://example.test",
177
+ "https://",
178
+ "https://u:p@example.test",
179
+ "https://example.test/api",
180
+ "https://example.test?",
181
+ "https://example.test#",
182
+ "https://example.test:99999",
183
+ "https://example.test:abc",
184
+ "https://example.test\\other",
185
+ "https://example.test\n.evil.test",
186
+ ):
187
+ with self.subTest(url=url), self.assertRaises(ValueError):
188
+ CatalogClient(MagicMock(spec=ClientSession), url, TOKEN)