-
Notifications
You must be signed in to change notification settings - Fork 200
refactor: extract shared Supervisor httpx client helper (#1130) #1203
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Patch76
merged 2 commits into
homeassistant-ai:master
from
Patch76:refactor/issue-1130-supervisor-httpx-helper
May 11, 2026
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| """Shared factory for direct-Supervisor httpx clients. | ||
|
|
||
| Three call sites in the codebase talk directly to the Home Assistant | ||
| Supervisor REST API at ``http://supervisor`` rather than through | ||
| ``HomeAssistantClient.httpx_client`` (which is bound to HA Core, not the | ||
| Supervisor — different base URL, different token, different role gate): | ||
|
|
||
| - :meth:`ha_mcp.client.rest_client.HomeAssistantClient._supervisor_logs_get` | ||
| — fetches addon and system-service logs (#1116, #1126) | ||
| - :func:`ha_mcp.tools.tools_bug_report._fetch_addon_logs` — bundles ha-mcp's | ||
| own addon logs into a bug-report payload | ||
| - :func:`ha_mcp.settings_ui._restart_addon` — POSTs ``/addons/self/restart`` | ||
| from the settings UI | ||
|
|
||
| All three share the same boilerplate (base URL, ``Authorization: Bearer | ||
| ${SUPERVISOR_TOKEN}`` header), so this module supplies a single factory and | ||
| keeps the three sites consistent. | ||
|
|
||
| The token is read from env at construction time; the caller is responsible | ||
| for token-absent handling because each site has its own policy (a rich | ||
| :class:`HomeAssistantAuthError`, a silent ``""`` return, or a 400 | ||
| ``JSONResponse``) that does not share a common shape. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import os | ||
|
|
||
| import httpx | ||
|
|
||
| from .._version import get_supervisor_base_url | ||
|
|
||
| __all__ = ["make_supervisor_httpx_client"] | ||
|
|
||
|
|
||
| def make_supervisor_httpx_client( | ||
| *, | ||
| timeout: float | httpx.Timeout, | ||
| verify: bool, | ||
| ) -> httpx.AsyncClient: | ||
| """Construct an ``httpx.AsyncClient`` pre-configured for the Supervisor REST API. | ||
|
|
||
| Args: | ||
| timeout: Per-request timeout. Accepts either a plain ``float`` | ||
| (seconds, applied to all phases) or a full :class:`httpx.Timeout` | ||
| for finer-grained control. | ||
| verify: TLS verify policy. A no-op for the default | ||
| ``http://supervisor`` base URL (plain HTTP — no TLS to verify), | ||
| but kept as a parameter because :func:`get_supervisor_base_url` | ||
| honours ``SUPERVISOR_BASE_URL`` env-var overrides that may be | ||
| HTTPS in non-add-on test rigs. | ||
|
|
||
| Returns: | ||
| A new :class:`httpx.AsyncClient` bound to the Supervisor base URL | ||
| with ``Authorization: Bearer ${SUPERVISOR_TOKEN}`` preset. Callers | ||
| pass relative paths (``/addons/self/logs``) to ``client.get/post``; | ||
| ``base_url`` joins them onto the Supervisor host. | ||
|
|
||
| ``SUPERVISOR_TOKEN`` is read from env at construction time. An absent | ||
| or empty value produces a literal ``"Bearer "`` header — callers are | ||
| expected to short-circuit before reaching here (see module docstring | ||
| for the per-site policies). | ||
| """ | ||
| token = os.environ.get("SUPERVISOR_TOKEN", "") | ||
| return httpx.AsyncClient( | ||
| base_url=get_supervisor_base_url(), | ||
| timeout=timeout, | ||
| verify=verify, | ||
| headers={"Authorization": f"Bearer {token}"}, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| """Unit tests for the shared Supervisor httpx client factory. | ||
|
|
||
| Covers :func:`ha_mcp.client.supervisor_client.make_supervisor_httpx_client`, | ||
| which builds the ``httpx.AsyncClient`` instances used by the three direct- | ||
| Supervisor call sites (``rest_client._supervisor_logs_get``, | ||
| ``tools_bug_report._fetch_addon_logs``, ``settings_ui._restart_addon``). | ||
|
|
||
| The factory itself is a one-liner around ``httpx.AsyncClient`` — these tests | ||
| guard the contract the three call sites rely on: | ||
|
|
||
| - ``base_url`` resolved through :func:`ha_mcp._version.get_supervisor_base_url` | ||
| (so the ``SUPERVISOR_BASE_URL`` E2E override flows through) | ||
| - ``Authorization: Bearer ${SUPERVISOR_TOKEN}`` preset on the client | ||
| - ``timeout`` / ``verify`` forwarded verbatim, both as plain ``float`` and as | ||
| :class:`httpx.Timeout` | ||
| - Absent or empty ``SUPERVISOR_TOKEN`` produces a ``"Bearer "`` header (the | ||
| call-site policy is to short-circuit before reaching here; this test pins | ||
| the documented graceful-degradation behaviour) | ||
| """ | ||
|
|
||
| from unittest.mock import patch | ||
|
|
||
| import httpx | ||
| import pytest | ||
|
|
||
| from ha_mcp.client.supervisor_client import make_supervisor_httpx_client | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def supervisor_token(monkeypatch: pytest.MonkeyPatch) -> str: | ||
| """Set a non-empty ``SUPERVISOR_TOKEN`` for the duration of one test.""" | ||
| token = "test-supervisor-token-abc123" | ||
| monkeypatch.setenv("SUPERVISOR_TOKEN", token) | ||
| return token | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def no_supervisor_token(monkeypatch: pytest.MonkeyPatch) -> None: | ||
| """Ensure ``SUPERVISOR_TOKEN`` is unset for the duration of one test.""" | ||
| monkeypatch.delenv("SUPERVISOR_TOKEN", raising=False) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def no_base_url_override(monkeypatch: pytest.MonkeyPatch) -> None: | ||
| """Ensure no ``SUPERVISOR_BASE_URL`` override leaks in from the host env.""" | ||
| monkeypatch.delenv("SUPERVISOR_BASE_URL", raising=False) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_returns_async_client( | ||
| supervisor_token: str, no_base_url_override: None | ||
| ) -> None: | ||
| """Factory returns a ready-to-use ``httpx.AsyncClient``.""" | ||
| async with make_supervisor_httpx_client(timeout=5.0, verify=True) as client: | ||
| assert isinstance(client, httpx.AsyncClient) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_base_url_defaults_to_supervisor( | ||
| supervisor_token: str, no_base_url_override: None | ||
| ) -> None: | ||
| """Default base URL is the in-addon ``http://supervisor`` hostname.""" | ||
| async with make_supervisor_httpx_client(timeout=5.0, verify=True) as client: | ||
| assert str(client.base_url) == "http://supervisor" | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_base_url_honors_env_override( | ||
| supervisor_token: str, monkeypatch: pytest.MonkeyPatch | ||
| ) -> None: | ||
| """``SUPERVISOR_BASE_URL`` env override flows through to the client. | ||
|
|
||
| This is the path E2E tests use to point the call sites at a local mock | ||
| without /etc/hosts hacks — guarding it here keeps that wiring intact. | ||
| """ | ||
| monkeypatch.setenv("SUPERVISOR_BASE_URL", "http://127.0.0.1:9876") | ||
| async with make_supervisor_httpx_client(timeout=5.0, verify=True) as client: | ||
| assert str(client.base_url) == "http://127.0.0.1:9876" | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_authorization_header_uses_token_from_env( | ||
| supervisor_token: str, no_base_url_override: None | ||
| ) -> None: | ||
| """``Authorization`` header is ``Bearer <SUPERVISOR_TOKEN>``.""" | ||
| async with make_supervisor_httpx_client(timeout=5.0, verify=True) as client: | ||
| assert client.headers["Authorization"] == f"Bearer {supervisor_token}" | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_authorization_header_with_absent_token( | ||
| no_supervisor_token: None, no_base_url_override: None | ||
| ) -> None: | ||
| """Missing ``SUPERVISOR_TOKEN`` falls back to a literal ``Bearer `` header. | ||
|
|
||
| Each call site short-circuits before reaching the factory when the token | ||
| is absent (see module docstring); this test pins the graceful-degradation | ||
| contract for any future direct caller that forgets to guard. | ||
| """ | ||
| async with make_supervisor_httpx_client(timeout=5.0, verify=True) as client: | ||
| assert client.headers["Authorization"] == "Bearer " | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_timeout_forwarded_as_float( | ||
| supervisor_token: str, no_base_url_override: None | ||
| ) -> None: | ||
| """A plain ``float`` timeout is forwarded to the underlying client. | ||
|
|
||
| httpx normalises ``float`` to a :class:`httpx.Timeout` with the same | ||
| value applied to all four phases — assert connect + read carry the | ||
| value through. | ||
| """ | ||
| async with make_supervisor_httpx_client(timeout=7.5, verify=True) as client: | ||
| assert client.timeout.connect == 7.5 | ||
| assert client.timeout.read == 7.5 | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_timeout_forwarded_as_httpx_timeout( | ||
| supervisor_token: str, no_base_url_override: None | ||
| ) -> None: | ||
| """An :class:`httpx.Timeout` instance is forwarded verbatim. | ||
|
|
||
| ``rest_client._supervisor_logs_get`` passes ``httpx.Timeout(self.timeout)`` | ||
| rather than a bare float; this test guards that the helper accepts the | ||
| rich type unchanged. | ||
| """ | ||
| timeout = httpx.Timeout(connect=2.0, read=30.0, write=30.0, pool=30.0) | ||
| async with make_supervisor_httpx_client(timeout=timeout, verify=True) as client: | ||
| assert client.timeout.connect == 2.0 | ||
| assert client.timeout.read == 30.0 | ||
|
|
||
|
|
||
| def test_verify_forwarded_to_async_client_kwarg(supervisor_token: str) -> None: | ||
| """``verify`` is forwarded verbatim to the underlying ``httpx.AsyncClient``. | ||
|
|
||
| httpx does not expose the constructor's ``verify`` value via any public | ||
| attribute on the client, so a real-instance assertion can't tell apart | ||
| ``verify=True`` from ``verify=False``. Patch the constructor and check | ||
| the kwarg directly — this is the only way to guard against a regression | ||
| that drops the parameter on the floor while still returning a valid | ||
| client. The ``verify`` flag is a no-op for plain ``http://supervisor`` | ||
| today, but call sites pass it for symmetry with the HTTPS-override path | ||
| (#1128) and that contract has to hold. | ||
| """ | ||
| with patch("ha_mcp.client.supervisor_client.httpx.AsyncClient") as mock_ctor: | ||
| make_supervisor_httpx_client(timeout=5.0, verify=False) | ||
| assert mock_ctor.call_args.kwargs["verify"] is False | ||
|
|
||
| mock_ctor.reset_mock() | ||
| make_supervisor_httpx_client(timeout=5.0, verify=True) | ||
| assert mock_ctor.call_args.kwargs["verify"] is True |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.