Skip to content

Home Information - Your home, your data, organized.

Python

HomeBox dual-API client (v0.25 items + v0.26 entities) (#373) (#374)

Tony C694e3f15ea8d
diff --git a/src/hi/services/homebox/hb_client.py b/src/hi/services/homebox/hb_client.py
index a64be839..3141cadd 100644
--- a/src/hi/services/homebox/hb_client.py
+++ b/src/hi/services/homebox/hb_client.py
@@ -1,178 +1,78 @@
-import logging
-from typing import Dict, List, Union, Any, Optional
-from requests import Session, Response
-
+"""HomeBox API client facade.
+
+Delegates to a version-specific backend (``_HbLegacyBackend`` for
+``/v1/items/*`` on HomeBox v0.25 and earlier; ``_HbEntitiesBackend``
+for ``/v1/entities/*`` on v0.26+). Backend selection is a runtime
+probe — performed lazily on the first method call so construction
+remains free of network I/O. Downstream code keeps calling the
+same four read methods and receives ``HbItem``-shaped data with the
+legacy field names regardless of which backend served the request.
+"""
+
+from typing import Any, Dict, List, Optional
+
+from .hb_client_backends import (
+ API_PASSWORD_OPTION,
+ API_URL_OPTION,
+ API_USER_OPTION,
+ _HbBackend,
+)
from .hb_models import HbItem
-logger = logging.getLogger(__name__)
-
class HbClient:
- API_URL = 'apiurl'
- API_USER = 'user'
- API_PASSWORD = 'password'
-
- DEFAULT_TIMEOUT = 25.0
- API_VERSION = 'v1'
-
- def __init__(self, api_options: Dict[str, str], timeout_secs: Optional[float] = None):
- self.api_url = api_options.get(self.API_URL)
- assert self.api_url is not None
- if self.api_url.endswith('/'):
- self.api_url = self.api_url[:-1]
-
- self._user = api_options.get(self.API_USER)
- assert self._user is not None
- self._password = api_options.get(self.API_PASSWORD)
- assert self._password is not None
-
- # Per-instance timeout. Defaults to DEFAULT_TIMEOUT when not
- # specified; the connection-test path passes a tighter bound for
- # interactive save-time validation.
- self._timeout_secs = timeout_secs if timeout_secs is not None else self.DEFAULT_TIMEOUT
-
- self._session = Session()
-
- # Login is deferred to first request rather than performed in
- # __init__. This keeps client construction free of network I/O
- # so that transient upstream problems do not leave the manager
- # with a permanently-null client. _make_request lazily logs in
- # on first use and re-logs in on a 401, so both the periodic
- # monitor and operator-initiated sync naturally self-heal once
- # the upstream recovers.
- self._authenticated = False
-
- def _login(self):
- url = f"{self.api_url}/{self.API_VERSION}/users/login"
- data = {
- 'username': self._user,
- 'password': self._password,
- 'stayLoggedIn': True
- }
- try:
- response = self._session.post(url, json=data, timeout=self._timeout_secs)
- except Exception as e:
- raise ConnectionError(
- f'Cannot connect to HomeBox at {self.api_url}. '
- f'Verify the API URL is correct and the server is running.'
- ) from e
-
- response.raise_for_status()
-
- content_type = response.headers.get('content-type', '')
- if 'json' not in content_type:
- raise ValueError(
- f'HomeBox API URL may be incorrect. Expected JSON response but received '
- f'{content_type or "unknown content type"}. '
- f'Ensure the URL includes the API path (e.g., http://host:port/api).'
+ """Thin facade over a version-specific backend. The class
+ attributes below are the canonical keys into the
+ ``api_options`` dict that callers (factory, tests) populate
+ when constructing the client."""
+
+ API_URL = API_URL_OPTION
+ API_USER = API_USER_OPTION
+ API_PASSWORD = API_PASSWORD_OPTION
+
+ def __init__(
+ self,
+ api_options : Dict[str, str],
+ timeout_secs : Optional[float] = None,
+ ):
+ # Construction stays free of network I/O: the probe that
+ # selects the right backend happens lazily on the first
+ # method call. This matches the deferred-login pattern
+ # that lets a transient upstream failure self-heal on the
+ # next operator-initiated sync without requiring a manager
+ # reload.
+ self._api_options = api_options
+ self._timeout_secs = timeout_secs
+ self._backend : Optional[ _HbBackend ] = None
+ # Normalize the configured API URL once at construction so
+ # the (no-network) ``api_url`` accessor below matches what
+ # the backends use internally — the deep-link builder reads
+ # this without needing to trigger the lazy backend resolve.
+ raw_url = api_options.get( API_URL_OPTION ) or ''
+ self.api_url = raw_url.rstrip( '/' )
+
+ def _get_backend(self) -> _HbBackend:
+ if self._backend is None:
+ # Local import to avoid circular import: the factory
+ # imports the facade for its public-API construction
+ # path.
+ from .hb_client_factory import HbClientFactory
+ self._backend = HbClientFactory.resolve_backend(
+ api_options=self._api_options,
+ timeout_secs=self._timeout_secs,
)
+ return self._backend
- token = response.json().get('token')
- if token:
- self._session.headers.update({'Authorization': token})
- else:
- logger.warning("HomeBox login succeeded but response did not contain a token.")
-
- self._authenticated = True
-
- def _make_request(self, method: str, url: str, **kwargs) -> Union[dict, Response]:
- """Helper to make requests with simple re-authentication."""
-
- kwargs.setdefault('timeout', self._timeout_secs)
-
- # Lazy first login. Failures (connection refused, NON_JSON
- # upstream, etc.) propagate to the caller, who will retry on the
- # next monitor cycle / sync attempt — naturally self-healing
- # once the upstream comes back.
- if not self._authenticated and self._user:
- self._login()
-
- response = self._session.request(method, url, **kwargs)
-
- if response.status_code == 401 and self._user:
- self._authenticated = False
- self._login()
- response = self._session.request(method, url, **kwargs)
-
- response.raise_for_status()
-
- content_type = response.headers.get('content-type', '')
- if content_type.startswith('application/json'):
- return response.json()
- return response
-
- def get_items_summary(self) -> List[Dict[str, Any]]:
- """
- Fetches just the items summary list (one API call). Does not fetch
- per-item details. Suitable for lightweight reachability /
- health-check probes where only the count or IDs are needed.
-
- The items endpoint is always JSON in HomeBox; if we got back a
- raw Response (because _make_request fell through to the
- binary-attachment path on a non-JSON content type), the
- configured API URL is pointing at the wrong place. Surface that
- as a clear ValueError instead of letting downstream callers
- iterate the response as bytes.
- """
- url_list = f"{self.api_url}/{self.API_VERSION}/items"
- data = self._make_request('GET', url_list)
- if not isinstance(data, dict):
- raise ValueError(
- f'HomeBox API URL may be incorrect. Expected JSON response '
- f'from {url_list} but did not receive one. Ensure the URL '
- f'points at the HomeBox API root (e.g., http://host:port/api).'
- )
- return data.get('items', [])
+ def get_items_summary(self) -> List[ Dict[str, Any] ]:
+ return self._get_backend().get_items_summary()
def get_item(self, item_id: str) -> HbItem:
- """Fetches a single item's full detail. Used by the Connect-mode
- on-demand resolver (each entity-detail modal open triggers one
- call). Returns the populated HbItem.
-
- Errors propagate to the caller (auth/network/HTTP errors). The
- Connect resolver wraps this call and degrades to a deep-link-only
- placeholder on failure rather than crashing the modal render."""
- url = f"{self.api_url}/{self.API_VERSION}/items/{item_id}"
- item_detail = self._make_request('GET', url)
- if not isinstance(item_detail, dict):
- raise ValueError(
- f'HomeBox returned non-JSON response for item {item_id}.'
- )
- return HbItem(api_dict=item_detail, client=self)
-
- def get_items(self) -> List[HbItem]:
- """
- Fetches the list of items and, for each one, fetches the full details.
- Returns a list of fully populated HbItem objects.
-
- A failed detail fetch propagates rather than being swallowed
- per-item: a partial-success outcome here is more dangerous
- than a clean failure (it silently drops items, which the
- sync layer then misinterprets as upstream removals or a
- clean 'nothing to import'). The sync flow's outer try/except
- converts the propagated error into an operator-visible
- ``error_list`` entry with the underlying message.
- """
- items_summary = self.get_items_summary()
-
- full_items = []
- for summary in items_summary:
- item_id = summary.get('id')
- if item_id:
- full_items.append(self.get_item(item_id))
-
- return full_items
+ return self._get_backend().get_item( item_id )
- def download_attachment(self, item_id: str, attachment_id: str) -> Optional[Dict[str, Any]]:
- """Downloads an attachment """
- url = f"{self.api_url}/{self.API_VERSION}/items/{item_id}/attachments/{attachment_id}"
- response = self._make_request('GET', url)
+ def get_items(self) -> List[ HbItem ]:
+ return self._get_backend().get_items()
- if not isinstance(response, Response):
- logger.warning(f"Expected a Response object for attachment download, got {type(response)}")
- return None
-
- return {
- 'content': response.content,
- 'mime_type': response.headers.get('content-type'),
- }
+ def download_attachment(
+ self, item_id: str, attachment_id: str,
+ ) -> Optional[ Dict[str, Any] ]:
+ return self._get_backend().download_attachment( item_id, attachment_id )
diff --git a/src/hi/services/homebox/hb_client_backends.py b/src/hi/services/homebox/hb_client_backends.py
new file mode 100644
index 00000000..88b61b66
--- /dev/null
+++ b/src/hi/services/homebox/hb_client_backends.py
@@ -0,0 +1,363 @@
+"""HomeBox API client backends.
+
+Both major HomeBox API versions expose the same logical read
+surface (list items, get one item, download an attachment) under
+different URL paths and slightly different response shapes:
+
+ - v0.25 and earlier: ``/v1/items/*``
+ - v0.26+: ``/v1/entities/*`` (the "entity merge")
+
+Each version is implemented as a concrete subclass of
+``_HbBackendBase``; the ``HbClient`` facade selects between them
+(today: legacy only; #373 Phase 3 adds the entities backend and a
+version probe). Backend output is normalized to the legacy
+``HbItem`` shape so downstream code is version-agnostic.
+"""
+
+import logging
+from typing import Any, Dict, List, Optional, Protocol, Union
+
+from requests import Response, Session
+
+from .hb_models import HbItem
+
+
+logger = logging.getLogger(__name__)
+
+
+# Keys into the ``api_options`` dict passed to a backend's
+# constructor. The factory and the public ``HbClient`` facade use
+# the same names; the backend is the consumer that actually reads
+# them, so the canonical definition lives here.
+API_URL_OPTION = 'apiurl'
+API_USER_OPTION = 'user'
+API_PASSWORD_OPTION = 'password'
+
+
+DEFAULT_TIMEOUT_SECS = 25.0
+API_VERSION = 'v1'
+
+
+class _HbBackend(Protocol):
+ """Read-only HomeBox API surface. Both versions normalize to
+ legacy-shaped ``HbItem`` dicts on the way out so downstream
+ code is version-agnostic."""
+
+ def get_items_summary(self) -> List[Dict[str, Any]]:
+ ...
+
+ def get_item(self, item_id: str) -> HbItem:
+ ...
+
+ def get_items(self) -> List[HbItem]:
+ ...
+
+ def download_attachment(self,
+ item_id: str,
+ attachment_id: str) -> Optional[Dict[str, Any]]:
+ ...
+
+
+class _HbBackendBase:
+ """Transport layer shared by every version-specific backend:
+ session ownership, lazy login, the request helper. URL paths
+ and response normalization are the subclass's concern.
+ """
+
+ @classmethod
+ def _share_transport(cls, source: '_HbBackendBase') -> '_HbBackendBase':
+ """Construct an instance reusing another backend's
+ session, credentials, and auth state. Used by the factory
+ version probe so the chosen backend doesn't re-login after
+ the probe has already authenticated."""
+ instance = cls.__new__( cls )
+ instance.api_url = source.api_url
+ instance._user = source._user
+ instance._password = source._password
+ instance._timeout_secs = source._timeout_secs
+ instance._session = source._session
+ instance._authenticated = source._authenticated
+ return instance
+
+ def __init__(
+ self,
+ api_options : Dict[str, str],
+ timeout_secs : Optional[float] = None,
+ ):
+ self.api_url = api_options.get( API_URL_OPTION )
+ assert self.api_url is not None
+ if self.api_url.endswith( '/' ):
+ self.api_url = self.api_url[:-1]
+
+ self._user = api_options.get( API_USER_OPTION )
+ assert self._user is not None
+ self._password = api_options.get( API_PASSWORD_OPTION )
+ assert self._password is not None
+
+ # Per-instance timeout. Defaults when not specified; the
+ # connection-test path passes a tighter bound for
+ # interactive save-time validation.
+ self._timeout_secs = (
+ timeout_secs if timeout_secs is not None else DEFAULT_TIMEOUT_SECS
+ )
+
+ self._session = Session()
+
+ # Login is deferred to first request rather than performed
+ # in __init__. This keeps construction free of network I/O
+ # so transient upstream problems do not leave the manager
+ # with a permanently-null client. ``_make_request`` lazily
+ # logs in on first use and re-logs on a 401, so both the
+ # periodic monitor and operator-initiated sync naturally
+ # self-heal once the upstream recovers.
+ self._authenticated = False
+
+ def _login(self):
+ url = f"{self.api_url}/{API_VERSION}/users/login"
+ data = {
+ 'username': self._user,
+ 'password': self._password,
+ 'stayLoggedIn': True,
+ }
+ try:
+ response = self._session.post(
+ url, json=data, timeout=self._timeout_secs,
+ )
+ except Exception as e:
+ raise ConnectionError(
+ f'Cannot connect to HomeBox at {self.api_url}. '
+ f'Verify the API URL is correct and the server is running.'
+ ) from e
+
+ response.raise_for_status()
+
+ content_type = response.headers.get( 'content-type', '' )
+ if 'json' not in content_type:
+ raise ValueError(
+ f'HomeBox API URL may be incorrect. Expected JSON response but received '
+ f'{content_type or "unknown content type"}. '
+ f'Ensure the URL includes the API path (e.g., http://host:port/api).'
+ )
+
+ token = response.json().get( 'token' )
+ if token:
+ self._session.headers.update( { 'Authorization': token } )
+ else:
+ logger.warning(
+ 'HomeBox login succeeded but response did not contain a token.'
+ )
+
+ self._authenticated = True
+
+ def _make_request(
+ self, method: str, url: str, **kwargs,
+ ) -> Union[ dict, Response ]:
+ """Make a request with lazy login + retry-on-401 semantics."""
+
+ kwargs.setdefault( 'timeout', self._timeout_secs )
+
+ # Lazy first login. Failures (connection refused, NON_JSON
+ # upstream, etc.) propagate to the caller, who will retry
+ # on the next monitor cycle / sync attempt — naturally
+ # self-healing once the upstream comes back.
+ if not self._authenticated and self._user:
+ self._login()
+
+ response = self._session.request( method, url, **kwargs )
+
+ if response.status_code == 401 and self._user:
+ self._authenticated = False
+ self._login()
+ response = self._session.request( method, url, **kwargs )
+
+ response.raise_for_status()
+
+ content_type = response.headers.get( 'content-type', '' )
+ if content_type.startswith( 'application/json' ):
+ return response.json()
+ return response
+
+ # ---- shared read methods -------------------------------------
+ #
+ # ``get_items_summary`` and ``get_item`` differ enough between
+ # versions to warrant version-specific implementations (paths,
+ # pagination, response normalization). ``get_items`` and
+ # ``download_attachment`` are version-agnostic apart from URL
+ # construction, so they live here with a small per-version URL
+ # hook below.
+
+ def get_items(self) -> List[ HbItem ]:
+ """Fetch the list of items and, for each one, fetch the
+ full details. Returns a list of fully populated ``HbItem``
+ objects.
+
+ A failed detail fetch propagates rather than being
+ swallowed per-item: a partial-success outcome here is more
+ dangerous than a clean failure (it silently drops items,
+ which the sync layer then misinterprets as upstream
+ removals or a clean 'nothing to import'). The sync flow's
+ outer try/except converts the propagated error into an
+ operator-visible ``error_list`` entry."""
+ items_summary = self.get_items_summary()
+ full_items = []
+ for summary in items_summary:
+ item_id = summary.get( 'id' )
+ if item_id:
+ full_items.append( self.get_item( item_id ) )
+ return full_items
+
+ def download_attachment(
+ self, item_id: str, attachment_id: str,
+ ) -> Optional[ Dict[str, Any] ]:
+ """Downloads an attachment. The URL path differs between
+ versions; subclasses supply it via ``_attachment_url``."""
+ url = self._attachment_url(
+ item_id=item_id, attachment_id=attachment_id,
+ )
+ response = self._make_request( 'GET', url )
+
+ if not isinstance( response, Response ):
+ logger.warning(
+ f"Expected a Response object for attachment download, "
+ f"got {type(response)}"
+ )
+ return None
+
+ return {
+ 'content': response.content,
+ 'mime_type': response.headers.get( 'content-type' ),
+ }
+
+ def _attachment_url(self, item_id: str, attachment_id: str) -> str:
+ raise NotImplementedError(
+ 'Subclasses must override ``_attachment_url`` to build the '
+ 'version-specific attachment-download URL.'
+ )
+
+
+class _HbLegacyBackend( _HbBackendBase ):
+ """HomeBox v0.25 and earlier — ``/v1/items/*`` endpoints."""
+
+ def get_items_summary(self) -> List[ Dict[str, Any] ]:
+ """Fetch the items summary list (one API call). Suitable
+ for lightweight reachability / health-check probes where
+ only the count or IDs are needed.
+
+ The items endpoint is always JSON in HomeBox; if we got
+ back a raw Response (because ``_make_request`` fell through
+ to the binary-attachment path on a non-JSON content type),
+ the configured API URL is pointing at the wrong place.
+ Surface that as a clear ValueError instead of letting
+ downstream callers iterate the response as bytes."""
+ url_list = f"{self.api_url}/{API_VERSION}/items"
+ data = self._make_request( 'GET', url_list )
+ if not isinstance( data, dict ):
+ raise ValueError(
+ f'HomeBox API URL may be incorrect. Expected JSON response '
+ f'from {url_list} but did not receive one. Ensure the URL '
+ f'points at the HomeBox API root (e.g., http://host:port/api).'
+ )
+ return data.get( 'items', [] )
+
+ def get_item(self, item_id: str) -> HbItem:
+ """Fetch a single item's full detail. Used by the
+ Connect-mode on-demand resolver (each entity-detail modal
+ open triggers one call).
+
+ Errors propagate to the caller (auth/network/HTTP errors).
+ The Connect resolver wraps this call and degrades to a
+ deep-link-only placeholder on failure rather than crashing
+ the modal render."""
+ url = f"{self.api_url}/{API_VERSION}/items/{item_id}"
+ item_detail = self._make_request( 'GET', url )
+ if not isinstance( item_detail, dict ):
+ raise ValueError(
+ f'HomeBox returned non-JSON response for item {item_id}.'
+ )
+ return HbItem( api_dict=item_detail, client=self )
+
+ def _attachment_url(self, item_id: str, attachment_id: str) -> str:
+ return (
+ f"{self.api_url}/{API_VERSION}/items/{item_id}"
+ f"/attachments/{attachment_id}"
+ )
+
+
+# Page size we request from /v1/entities. Real HomeBox's default
+# pagination behavior when no params are passed isn't formally
+# specified; we always pass an explicit page size and loop on
+# ``total`` to be robust against either default.
+_ENTITIES_PAGE_SIZE = 200
+
+
+class _HbEntitiesBackend( _HbBackendBase ):
+ """HomeBox v0.26+ — ``/v1/entities/*`` endpoints.
+
+ Normalizes responses to the legacy ``HbItem`` shape on the
+ way out so downstream code stays version-agnostic: the v0.26
+ ``parent`` field is renamed to ``location``, the new
+ ``entityType`` discriminator is dropped, and the paginated
+ list response is collapsed to a flat items list."""
+
+ def get_items_summary(self) -> List[ Dict[str, Any] ]:
+ """Fetch the entities list. Pages explicitly and loops
+ on ``total`` until the accumulated items match — robust
+ against either pagination default."""
+ url = f"{self.api_url}/{API_VERSION}/entities"
+ all_items: List[ Dict[str, Any] ] = []
+ page = 1
+ while True:
+ params = { 'page': page, 'pageSize': _ENTITIES_PAGE_SIZE }
+ data = self._make_request( 'GET', url, params=params )
+ if not isinstance( data, dict ):
+ raise ValueError(
+ f'HomeBox API URL may be incorrect. Expected JSON response '
+ f'from {url} but did not receive one. Ensure the URL '
+ f'points at the HomeBox API root (e.g., http://host:port/api).'
+ )
+ page_items = data.get( 'items', [] ) or []
+ for entity in page_items:
+ all_items.append( _normalize_entity( entity ) )
+ total = data.get( 'total' )
+ # ``-1`` is HomeBox's sentinel for "no pagination, all
+ # returned in one shot" (real installs and the simulator
+ # both use this). Treat it as a one-page reply.
+ if not isinstance( total, int ) or total < 0:
+ break
+ if len( all_items ) >= total:
+ break
+ if not page_items:
+ # Defensive: the server promised more items but
+ # gave us an empty page. Avoid an infinite loop.
+ break
+ page += 1
+ return all_items
+
+ def get_item(self, item_id: str) -> HbItem:
+ url = f"{self.api_url}/{API_VERSION}/entities/{item_id}"
+ entity = self._make_request( 'GET', url )
+ if not isinstance( entity, dict ):
+ raise ValueError(
+ f'HomeBox returned non-JSON response for entity {item_id}.'
+ )
+ return HbItem( api_dict=_normalize_entity( entity ), client=self )
+
+ def _attachment_url(self, item_id: str, attachment_id: str) -> str:
+ return (
+ f"{self.api_url}/{API_VERSION}/entities/{item_id}"
+ f"/attachments/{attachment_id}"
+ )
+
+
+def _normalize_entity( entity: Dict[str, Any] ) -> Dict[str, Any]:
+ """Translate a v0.26 entity dict to the legacy item shape so
+ downstream code consumes a single internal vocabulary:
+ ``parent`` becomes ``location``; the new ``entityType``
+ discriminator is dropped (HI doesn't need it). The input dict
+ is not mutated."""
+ normalized = dict( entity )
+ if 'parent' in normalized:
+ normalized['location'] = normalized.pop( 'parent' )
+ normalized.pop( 'entityType', None )
+ return normalized
+
diff --git a/src/hi/services/homebox/hb_client_factory.py b/src/hi/services/homebox/hb_client_factory.py
index c6267268..52b3b02c 100644
--- a/src/hi/services/homebox/hb_client_factory.py
+++ b/src/hi/services/homebox/hb_client_factory.py
@@ -3,6 +3,8 @@
import logging
from typing import Dict, Optional
+from requests import HTTPError
+
from hi.apps.system.enums import HealthStatusType
from hi.integrations.exceptions import IntegrationAttributeError
from hi.integrations.models import IntegrationAttribute
@@ -10,6 +12,12 @@ from hi.integrations.transient_models import IntegrationKey, IntegrationValidati
from hi.services.homebox.enums import HbAttributeType
from .hb_client import HbClient
+from .hb_client_backends import (
+ API_VERSION,
+ _HbBackend,
+ _HbEntitiesBackend,
+ _HbLegacyBackend,
+)
from hi.services.homebox.hb_metadata import HbMetaData
logger = logging.getLogger(__name__)
@@ -67,6 +75,43 @@ class HbClientFactory:
return HbClient(api_options=api_options, timeout_secs=timeout_secs)
+ @staticmethod
+ def resolve_backend(
+ api_options: Dict[str, str],
+ timeout_secs: Optional[float] = None,
+ ) -> _HbBackend:
+ """Probe the configured HomeBox install and return the
+ right backend. ``GET /v1/entities?pageSize=1`` is the
+ discriminator: 2xx means the entity-merge endpoints are
+ live (v0.26+), 404 means we're on the legacy items API
+ (v0.25 and earlier). Other errors propagate so the caller
+ can record an error state and retry on the next reload.
+
+ The probe runs against a temporary legacy backend; its
+ session (now authenticated) is handed to the chosen
+ backend so the picker doesn't double-login.
+ """
+ probe = _HbLegacyBackend(
+ api_options=api_options,
+ timeout_secs=timeout_secs,
+ )
+ probe_url = f'{probe.api_url}/{API_VERSION}/entities'
+ try:
+ probe._make_request( 'GET', probe_url, params={ 'pageSize': 1 } )
+ except HTTPError as e:
+ response = getattr( e, 'response', None )
+ if response is not None and response.status_code == 404:
+ logger.debug(
+ 'HomeBox /v1/entities probe returned 404 — '
+ 'using legacy /v1/items backend.'
+ )
+ return probe
+ raise
+ logger.debug(
+ 'HomeBox /v1/entities probe succeeded — using entities backend.'
+ )
+ return _HbEntitiesBackend._share_transport( probe )
+
def test_client(self, client: HbClient) -> IntegrationValidationResult:
"""
Test API connectivity for a given client.
diff --git a/src/hi/services/homebox/tests/test_hb_client.py b/src/hi/services/homebox/tests/test_hb_client.py
deleted file mode 100644
index 819b3e2f..00000000
--- a/src/hi/services/homebox/tests/test_hb_client.py
+++ /dev/null
@@ -1,230 +0,0 @@
-import logging
-import json
-from unittest.mock import Mock, patch
-
-from django.test import SimpleTestCase
-from requests import Response
-
-from hi.services.homebox.hb_client import HbClient
-
-
-logging.disable(logging.CRITICAL)
-
-
-class TestHbClient(SimpleTestCase):
-
- def _api_options(self):
- return {
- HbClient.API_URL: 'https://homebox.local',
- HbClient.API_USER: 'user',
- HbClient.API_PASSWORD: 'pass',
- }
-
- def _response(self, status_code=200, json_data=None, content_type='application/json', content=b''):
- response = Response()
- response.status_code = status_code
- response.headers['content-type'] = content_type
-
- if json_data is not None:
- response._content = json.dumps(json_data).encode('utf-8')
- else:
- response._content = content
-
- return response
-
- def test_init_strips_trailing_slash_and_defers_login(self):
- """Client construction must not perform network I/O. _login is
- deferred to first request so a transient upstream problem at
- construction time does not leave the manager with a permanently
- null client."""
- with patch.object(HbClient, '_login') as mock_login:
- client = HbClient(api_options={
- HbClient.API_URL: 'https://homebox.local/',
- HbClient.API_USER: 'user',
- HbClient.API_PASSWORD: 'pass',
- })
-
- self.assertEqual(client.api_url, 'https://homebox.local')
- mock_login.assert_not_called()
- self.assertFalse(client._authenticated)
-
- def test_make_request_lazy_logs_in_on_first_use(self):
- """First _make_request call performs the deferred login."""
- with patch.object(HbClient, '_login') as mock_login:
- client = HbClient(api_options={
- HbClient.API_URL: 'https://homebox.local',
- HbClient.API_USER: 'user',
- HbClient.API_PASSWORD: 'pass',
- })
-
- success = self._response(status_code=200, json_data={'items': []})
- client._session.request = Mock(return_value=success)
-
- # Simulate _login marking the client as authenticated.
- def fake_login():
- client._authenticated = True
- mock_login.side_effect = fake_login
-
- result = client._make_request('GET', 'https://homebox.local/v1/items')
-
- mock_login.assert_called_once()
- self.assertEqual(result, {'items': []})
-
- def test_make_request_retries_after_unauthorized(self):
- with patch.object(HbClient, '_login') as mock_login:
- client = HbClient(api_options={
- HbClient.API_URL: 'https://homebox.local',
- HbClient.API_USER: 'user',
- HbClient.API_PASSWORD: 'pass',
- })
- # Pretend a prior request already authenticated us so we are
- # exercising only the 401 -> re-login -> retry path here.
- client._authenticated = True
-
- unauthorized = self._response(status_code=401, json_data={'detail': 'Unauthorized'})
- success = self._response(status_code=200, json_data={'items': []})
-
- client._session.request = Mock(side_effect=[unauthorized, success])
-
- result = client._make_request('GET', 'https://homebox.local/v1/items')
-
- self.assertEqual(result, {'items': []})
- self.assertEqual(client._session.request.call_count, 2)
- mock_login.assert_called_once()
-
- def test_make_request_returns_response_for_non_json_content(self):
- client = HbClient(api_options=self._api_options())
- # Already-authenticated path so we exercise only the binary
- # attachment-download branch without triggering a lazy login.
- client._authenticated = True
-
- binary_response = self._response(
- status_code=200,
- json_data=None,
- content_type='application/octet-stream',
- content=b'file-bytes',
- )
- client._session.request = Mock(return_value=binary_response)
-
- result = client._make_request('GET', 'https://homebox.local/v1/items/1/attachments/1')
-
- self.assertIs(result, binary_response)
-
- def test_get_items_summary_raises_when_response_is_not_json(self):
- """A non-JSON response on the items endpoint means the configured
- API URL is wrong; surface that as a clear ValueError instead of
- passing the raw Response through to get_items where it would
- explode on byte iteration."""
- client = HbClient(api_options=self._api_options())
- client._authenticated = True
-
- non_json_response = self._response(
- status_code=200,
- json_data=None,
- content_type='text/html',
- content=b'<html><body>not the API</body></html>',
- )
- client._session.request = Mock(return_value=non_json_response)
-
- with self.assertRaises(ValueError) as context:
- client.get_items_summary()
- self.assertIn('URL may be incorrect', str(context.exception))
-
- def test_get_items_fetches_detail_for_each_item(self):
- """Happy path: each summary entry fans out to a detail
- fetch and the detail responses are wrapped as HbItems.
- Items with no id are skipped (still safe — the summary
- is the only signal)."""
- with patch.object(HbClient, '_login'):
- client = HbClient(api_options=self._api_options())
-
- client._make_request = Mock(side_effect=[
- {'items': [{'id': 'item-1'}, {'id': 'item-2'}, {}, {'id': 'item-3'}]},
- {'id': 'item-1', 'name': 'One'},
- {'id': 'item-2', 'name': 'Two'},
- {'id': 'item-3', 'name': 'Three'},
- ])
-
- items = client.get_items()
-
- self.assertEqual(len(items), 3)
- self.assertEqual([i.id for i in items], ['item-1', 'item-2', 'item-3'])
-
- def test_get_items_propagates_detail_fetch_failures(self):
- """A failed detail fetch propagates rather than being
- silently dropped: a partial-success outcome here is
- misinterpreted by the sync layer as upstream removals or a
- clean 'nothing to import,' which masks real upstream
- problems. The sync flow's outer try/except converts the
- propagated error into an ``error_list`` entry."""
- with patch.object(HbClient, '_login'):
- client = HbClient(api_options=self._api_options())
-
- client._make_request = Mock(side_effect=[
- {'items': [{'id': 'item-1'}, {'id': 'item-2'}]},
- {'id': 'item-1', 'name': 'One'},
- Exception('detail request failed'),
- ])
-
- with self.assertRaises(Exception) as context:
- client.get_items()
- self.assertIn('detail request failed', str(context.exception))
-
- def test_get_item_returns_hb_item_from_detail_endpoint(self):
- with patch.object(HbClient, '_login'):
- client = HbClient(api_options=self._api_options())
- client._make_request = Mock(return_value={'id': 'item-5', 'name': 'Five'})
-
- item = client.get_item('item-5')
-
- self.assertEqual(item.id, 'item-5')
- self.assertEqual(item.name, 'Five')
- client._make_request.assert_called_once_with(
- 'GET',
- 'https://homebox.local/v1/items/item-5',
- )
-
- def test_get_item_raises_when_response_is_not_dict(self):
- with patch.object(HbClient, '_login'):
- client = HbClient(api_options=self._api_options())
- client._make_request = Mock(return_value=self._response(
- status_code=200,
- json_data=None,
- content_type='text/html',
- content=b'<html>not the api</html>',
- ))
-
- with self.assertRaises(ValueError) as context:
- client.get_item('item-5')
- self.assertIn('non-JSON', str(context.exception))
-
- def test_download_attachment_returns_none_when_request_is_not_response(self):
- with patch.object(HbClient, '_login'):
- client = HbClient(api_options=self._api_options())
- client._make_request = Mock(return_value={'content': 'wrong-type'})
-
- payload = client.download_attachment(item_id='item-1', attachment_id='att-1')
-
- self.assertIsNone(payload)
- client._make_request.assert_called_once_with(
- 'GET',
- 'https://homebox.local/v1/items/item-1/attachments/att-1',
- )
-
- def test_download_attachment_returns_content_and_mime_type(self):
- with patch.object(HbClient, '_login'):
- client = HbClient(api_options=self._api_options())
- response = self._response(
- status_code=200,
- json_data=None,
- content_type='image/png',
- content=b'PNGDATA',
- )
- client._make_request = Mock(return_value=response)
-
- payload = client.download_attachment(item_id='item-1', attachment_id='att-1')
-
- self.assertEqual(payload, {
- 'content': b'PNGDATA',
- 'mime_type': 'image/png',
- })
diff --git a/src/hi/services/homebox/tests/test_hb_client_backends.py b/src/hi/services/homebox/tests/test_hb_client_backends.py
new file mode 100644
index 00000000..93b24017
--- /dev/null
+++ b/src/hi/services/homebox/tests/test_hb_client_backends.py
@@ -0,0 +1,534 @@
+"""Behavior tests for the HomeBox API client backends.
+
+The public ``HbClient`` is a thin facade over a version-specific
+backend (today: ``_HbLegacyBackend`` for the ``/v1/items`` API).
+These tests exercise the backend directly — session ownership,
+lazy login, retry-on-401, response-type handling, and the four
+read methods.
+"""
+
+import logging
+import json
+from unittest.mock import Mock, patch
+
+from django.test import SimpleTestCase
+from requests import Response
+
+from hi.services.homebox.hb_client import HbClient # constants
+from hi.services.homebox.hb_client_backends import (
+ _HbEntitiesBackend,
+ _HbLegacyBackend,
+ _normalize_entity,
+)
+
+
+logging.disable(logging.CRITICAL)
+
+
+class TestHbLegacyBackend(SimpleTestCase):
+
+ def _api_options(self):
+ return {
+ HbClient.API_URL: 'https://homebox.local',
+ HbClient.API_USER: 'user',
+ HbClient.API_PASSWORD: 'pass',
+ }
+
+ def _response(self, status_code=200, json_data=None,
+ content_type='application/json', content=b''):
+ response = Response()
+ response.status_code = status_code
+ response.headers['content-type'] = content_type
+
+ if json_data is not None:
+ response._content = json.dumps(json_data).encode('utf-8')
+ else:
+ response._content = content
+
+ return response
+
+ def test_init_strips_trailing_slash_and_defers_login(self):
+ """Backend construction must not perform network I/O.
+ ``_login`` is deferred to first request so a transient
+ upstream problem at construction time does not leave the
+ manager with a permanently null client."""
+ with patch.object(_HbLegacyBackend, '_login') as mock_login:
+ backend = _HbLegacyBackend(api_options={
+ HbClient.API_URL: 'https://homebox.local/',
+ HbClient.API_USER: 'user',
+ HbClient.API_PASSWORD: 'pass',
+ })
+
+ self.assertEqual(backend.api_url, 'https://homebox.local')
+ mock_login.assert_not_called()
+ self.assertFalse(backend._authenticated)
+
+ def test_login_wraps_connection_error_with_operator_hint(self):
+ """A network failure at login surfaces as a
+ ``ConnectionError`` whose message points the operator at
+ the configured URL — this is the diagnostic that helps
+ the operator distinguish 'HomeBox is down' from 'wrong
+ URL configured'."""
+ backend = _HbLegacyBackend(api_options=self._api_options())
+ backend._session.post = Mock(side_effect=OSError('refused'))
+
+ with self.assertRaises(ConnectionError) as context:
+ backend._login()
+
+ self.assertIn('Cannot connect to HomeBox', str(context.exception))
+ self.assertIn(backend.api_url, str(context.exception))
+
+ def test_login_rejects_non_json_response(self):
+ """The login endpoint must reply with JSON; a non-JSON
+ response means the configured API URL is pointing at a
+ non-API surface (e.g., the HTML UI) and should surface
+ a clear ``ValueError`` with the API-path hint."""
+ backend = _HbLegacyBackend(api_options=self._api_options())
+ backend._session.post = Mock(return_value=self._response(
+ status_code=200,
+ json_data=None,
+ content_type='text/html',
+ content=b'<html>not the api</html>',
+ ))
+
+ with self.assertRaises(ValueError) as context:
+ backend._login()
+ self.assertIn('API path', str(context.exception))
+
+ def test_make_request_lazy_logs_in_on_first_use(self):
+ """First ``_make_request`` call performs the deferred login."""
+ with patch.object(_HbLegacyBackend, '_login') as mock_login:
+ backend = _HbLegacyBackend(api_options={
+ HbClient.API_URL: 'https://homebox.local',
+ HbClient.API_USER: 'user',
+ HbClient.API_PASSWORD: 'pass',
+ })
+
+ success = self._response(status_code=200, json_data={'items': []})
+ backend._session.request = Mock(return_value=success)
+
+ # Simulate _login marking the backend as authenticated.
+ def fake_login():
+ backend._authenticated = True
+ mock_login.side_effect = fake_login
+
+ result = backend._make_request('GET', 'https://homebox.local/v1/items')
+
+ mock_login.assert_called_once()
+ self.assertEqual(result, {'items': []})
+
+ def test_make_request_retries_after_unauthorized(self):
+ with patch.object(_HbLegacyBackend, '_login') as mock_login:
+ backend = _HbLegacyBackend(api_options={
+ HbClient.API_URL: 'https://homebox.local',
+ HbClient.API_USER: 'user',
+ HbClient.API_PASSWORD: 'pass',
+ })
+ # Pretend a prior request already authenticated so we are
+ # exercising only the 401 -> re-login -> retry path here.
+ backend._authenticated = True
+
+ unauthorized = self._response(status_code=401, json_data={'detail': 'Unauthorized'})
+ success = self._response(status_code=200, json_data={'items': []})
+
+ backend._session.request = Mock(side_effect=[unauthorized, success])
+
+ result = backend._make_request('GET', 'https://homebox.local/v1/items')
+
+ self.assertEqual(result, {'items': []})
+ self.assertEqual(backend._session.request.call_count, 2)
+ mock_login.assert_called_once()
+
+ def test_make_request_returns_response_for_non_json_content(self):
+ backend = _HbLegacyBackend(api_options=self._api_options())
+ # Already-authenticated path so we exercise only the binary
+ # attachment-download branch without triggering a lazy login.
+ backend._authenticated = True
+
+ binary_response = self._response(
+ status_code=200,
+ json_data=None,
+ content_type='application/octet-stream',
+ content=b'file-bytes',
+ )
+ backend._session.request = Mock(return_value=binary_response)
+
+ result = backend._make_request('GET', 'https://homebox.local/v1/items/1/attachments/1')
+
+ self.assertIs(result, binary_response)
+
+ def test_get_items_summary_raises_when_response_is_not_json(self):
+ """A non-JSON response on the items endpoint means the
+ configured API URL is wrong; surface that as a clear
+ ValueError instead of passing the raw Response through to
+ ``get_items`` where it would explode on byte iteration."""
+ backend = _HbLegacyBackend(api_options=self._api_options())
+ backend._authenticated = True
+
+ non_json_response = self._response(
+ status_code=200,
+ json_data=None,
+ content_type='text/html',
+ content=b'<html><body>not the API</body></html>',
+ )
+ backend._session.request = Mock(return_value=non_json_response)
+
+ with self.assertRaises(ValueError) as context:
+ backend.get_items_summary()
+ self.assertIn('URL may be incorrect', str(context.exception))
+
+ def test_get_items_fetches_detail_for_each_item(self):
+ """Happy path: each summary entry fans out to a detail
+ fetch and the detail responses are wrapped as HbItems.
+ Items with no id are skipped (still safe — the summary
+ is the only signal)."""
+ with patch.object(_HbLegacyBackend, '_login'):
+ backend = _HbLegacyBackend(api_options=self._api_options())
+
+ backend._make_request = Mock(side_effect=[
+ {'items': [{'id': 'item-1'}, {'id': 'item-2'}, {}, {'id': 'item-3'}]},
+ {'id': 'item-1', 'name': 'One'},
+ {'id': 'item-2', 'name': 'Two'},
+ {'id': 'item-3', 'name': 'Three'},
+ ])
+
+ items = backend.get_items()
+
+ self.assertEqual(len(items), 3)
+ self.assertEqual([i.id for i in items], ['item-1', 'item-2', 'item-3'])
+
+ def test_get_items_propagates_detail_fetch_failures(self):
+ """A failed detail fetch propagates rather than being
+ silently dropped: a partial-success outcome here is
+ misinterpreted by the sync layer as upstream removals or a
+ clean 'nothing to import,' which masks real upstream
+ problems. The sync flow's outer try/except converts the
+ propagated error into an ``error_list`` entry."""
+ with patch.object(_HbLegacyBackend, '_login'):
+ backend = _HbLegacyBackend(api_options=self._api_options())
+
+ backend._make_request = Mock(side_effect=[
+ {'items': [{'id': 'item-1'}, {'id': 'item-2'}]},
+ {'id': 'item-1', 'name': 'One'},
+ Exception('detail request failed'),
+ ])
+
+ with self.assertRaises(Exception) as context:
+ backend.get_items()
+ self.assertIn('detail request failed', str(context.exception))
+
+ def test_get_item_returns_hb_item_from_detail_endpoint(self):
+ with patch.object(_HbLegacyBackend, '_login'):
+ backend = _HbLegacyBackend(api_options=self._api_options())
+ backend._make_request = Mock(return_value={'id': 'item-5', 'name': 'Five'})
+
+ item = backend.get_item('item-5')
+
+ self.assertEqual(item.id, 'item-5')
+ self.assertEqual(item.name, 'Five')
+ backend._make_request.assert_called_once_with(
+ 'GET',
+ 'https://homebox.local/v1/items/item-5',
+ )
+
+ def test_get_item_raises_when_response_is_not_dict(self):
+ with patch.object(_HbLegacyBackend, '_login'):
+ backend = _HbLegacyBackend(api_options=self._api_options())
+ backend._make_request = Mock(return_value=self._response(
+ status_code=200,
+ json_data=None,
+ content_type='text/html',
+ content=b'<html>not the api</html>',
+ ))
+
+ with self.assertRaises(ValueError) as context:
+ backend.get_item('item-5')
+ self.assertIn('non-JSON', str(context.exception))
+
+ def test_download_attachment_returns_none_when_request_is_not_response(self):
+ with patch.object(_HbLegacyBackend, '_login'):
+ backend = _HbLegacyBackend(api_options=self._api_options())
+ backend._make_request = Mock(return_value={'content': 'wrong-type'})
+
+ payload = backend.download_attachment(item_id='item-1', attachment_id='att-1')
+
+ self.assertIsNone(payload)
+ backend._make_request.assert_called_once_with(
+ 'GET',
+ 'https://homebox.local/v1/items/item-1/attachments/att-1',
+ )
+
+ def test_download_attachment_returns_content_and_mime_type(self):
+ with patch.object(_HbLegacyBackend, '_login'):
+ backend = _HbLegacyBackend(api_options=self._api_options())
+ response = self._response(
+ status_code=200,
+ json_data=None,
+ content_type='image/png',
+ content=b'PNGDATA',
+ )
+ backend._make_request = Mock(return_value=response)
+
+ payload = backend.download_attachment(item_id='item-1', attachment_id='att-1')
+
+ self.assertEqual(payload, {
+ 'content': b'PNGDATA',
+ 'mime_type': 'image/png',
+ })
+
+
+class TestHbClientFacade(SimpleTestCase):
+ """The public facade delegates every method to its backend.
+ These tests pin the delegation contract independent of which
+ backend is selected."""
+
+ def _api_options(self):
+ return {
+ HbClient.API_URL: 'https://homebox.local',
+ HbClient.API_USER: 'user',
+ HbClient.API_PASSWORD: 'pass',
+ }
+
+ def test_facade_construction_defers_backend_resolution(self):
+ # Construction must not trigger network I/O. The version
+ # probe (which selects between legacy and entities
+ # backends) is performed lazily on the first method call.
+ client = HbClient(api_options=self._api_options())
+ self.assertIsNone(client._backend)
+
+ def test_facade_delegates_read_methods_to_backend(self):
+ client = HbClient(api_options=self._api_options())
+ # Pre-seed the backend so the lazy probe doesn't run.
+ client._backend = Mock()
+ client._backend.get_items_summary.return_value = [{'id': '1'}]
+ client._backend.get_item.return_value = Mock()
+ client._backend.get_items.return_value = []
+ client._backend.download_attachment.return_value = None
+
+ client.get_items_summary()
+ client.get_item('xyz')
+ client.get_items()
+ client.download_attachment('xyz', 'a1')
+
+ client._backend.get_items_summary.assert_called_once_with()
+ client._backend.get_item.assert_called_once_with('xyz')
+ client._backend.get_items.assert_called_once_with()
+ client._backend.download_attachment.assert_called_once_with('xyz', 'a1')
+
+
+class TestNormalizeEntity(SimpleTestCase):
+ """The entities backend renames ``parent`` to ``location`` and
+ drops the ``entityType`` discriminator so downstream code
+ consumes a single internal vocabulary regardless of HB version."""
+
+ def test_parent_renamed_to_location(self):
+ normalized = _normalize_entity({
+ 'id': 'e-1',
+ 'name': 'Drill',
+ 'parent': {'id': 'loc-garage', 'name': 'Garage'},
+ })
+ self.assertEqual(normalized['location'], {'id': 'loc-garage', 'name': 'Garage'})
+ self.assertNotIn('parent', normalized)
+
+ def test_entity_type_dropped(self):
+ normalized = _normalize_entity({
+ 'id': 'e-1',
+ 'entityType': {'id': 'et-1', 'name': 'Item', 'isLocation': False},
+ })
+ self.assertNotIn('entityType', normalized)
+
+ def test_other_fields_preserved(self):
+ normalized = _normalize_entity({
+ 'id': 'e-1',
+ 'name': 'Drill',
+ 'description': 'Cordless drill',
+ 'quantity': 1,
+ 'tags': [{'id': 't-1', 'name': 'tools'}],
+ 'archived': False,
+ })
+ self.assertEqual(normalized['name'], 'Drill')
+ self.assertEqual(normalized['description'], 'Cordless drill')
+ self.assertEqual(normalized['quantity'], 1)
+ self.assertEqual(normalized['tags'], [{'id': 't-1', 'name': 'tools'}])
+ self.assertEqual(normalized['archived'], False)
+
+ def test_source_dict_not_mutated(self):
+ # The backend hands the normalized copy to HbItem; the
+ # original response dict should remain untouched in case a
+ # future caller wants to inspect raw v0.26 fields.
+ source = {'id': 'e-1', 'parent': {'name': 'Garage'}, 'entityType': {}}
+ _normalize_entity(source)
+ self.assertIn('parent', source)
+ self.assertIn('entityType', source)
+
+
+class TestHbEntitiesBackend(SimpleTestCase):
+ """v0.26 backend: pagination loop, response normalization,
+ and the path-rename across the four read methods."""
+
+ def _api_options(self):
+ return {
+ HbClient.API_URL: 'https://homebox.local',
+ HbClient.API_USER: 'user',
+ HbClient.API_PASSWORD: 'pass',
+ }
+
+ def _entity_dict(self, entity_id, name='X', location_name='Garage'):
+ return {
+ 'id': entity_id,
+ 'name': name,
+ 'parent': {'id': f'loc-{location_name.lower()}', 'name': location_name},
+ 'entityType': {'id': 'et-item', 'name': 'Item', 'isLocation': False},
+ }
+
+ def test_get_items_summary_handles_sentinel_total(self):
+ """Real HB and the simulator return ``total=-1`` /
+ ``pageSize=-1`` when serving everything in one page; the
+ loop should terminate after the first page in that case."""
+ with patch.object(_HbEntitiesBackend, '_login'):
+ backend = _HbEntitiesBackend(api_options=self._api_options())
+ backend._make_request = Mock(return_value={
+ 'page': -1,
+ 'pageSize': -1,
+ 'total': -1,
+ 'items': [self._entity_dict('e-1'), self._entity_dict('e-2')],
+ })
+
+ items = backend.get_items_summary()
+
+ self.assertEqual(len(items), 2)
+ # Normalized in-place: parent → location, entityType dropped.
+ for item in items:
+ self.assertIn('location', item)
+ self.assertNotIn('parent', item)
+ self.assertNotIn('entityType', item)
+ self.assertEqual(backend._make_request.call_count, 1)
+
+ def test_get_items_summary_loops_until_total_reached(self):
+ """When the server gives a real ``total`` and pages, the
+ loop fetches additional pages until the count is met."""
+ with patch.object(_HbEntitiesBackend, '_login'):
+ backend = _HbEntitiesBackend(api_options=self._api_options())
+ page1 = {
+ 'page': 1, 'pageSize': 2, 'total': 3,
+ 'items': [self._entity_dict('e-1'), self._entity_dict('e-2')],
+ }
+ page2 = {
+ 'page': 2, 'pageSize': 2, 'total': 3,
+ 'items': [self._entity_dict('e-3')],
+ }
+ backend._make_request = Mock(side_effect=[page1, page2])
+
+ items = backend.get_items_summary()
+
+ self.assertEqual([i['id'] for i in items], ['e-1', 'e-2', 'e-3'])
+ self.assertEqual(backend._make_request.call_count, 2)
+
+ def test_get_items_summary_breaks_on_empty_page(self):
+ """Defensive: if the server promises more items than it
+ delivers (empty page), the loop must terminate rather than
+ spin forever."""
+ with patch.object(_HbEntitiesBackend, '_login'):
+ backend = _HbEntitiesBackend(api_options=self._api_options())
+ page1 = {
+ 'page': 1, 'pageSize': 2, 'total': 10,
+ 'items': [self._entity_dict('e-1')],
+ }
+ page2 = {
+ 'page': 2, 'pageSize': 2, 'total': 10,
+ 'items': [],
+ }
+ backend._make_request = Mock(side_effect=[page1, page2])
+
+ items = backend.get_items_summary()
+
+ self.assertEqual(len(items), 1)
+ self.assertEqual(backend._make_request.call_count, 2)
+
+ def test_get_item_hits_entities_path_and_normalizes(self):
+ with patch.object(_HbEntitiesBackend, '_login'):
+ backend = _HbEntitiesBackend(api_options=self._api_options())
+ backend._make_request = Mock(return_value=self._entity_dict('e-7', name='Drill'))
+
+ item = backend.get_item('e-7')
+
+ self.assertEqual(item.id, 'e-7')
+ self.assertEqual(item.name, 'Drill')
+ # Field rename: HbItem.location reads ``location`` from the
+ # api_dict — present because the backend renamed parent.
+ self.assertEqual(item.location['name'], 'Garage')
+ backend._make_request.assert_called_once_with(
+ 'GET',
+ 'https://homebox.local/v1/entities/e-7',
+ )
+
+ def test_get_item_raises_on_non_dict_response(self):
+ with patch.object(_HbEntitiesBackend, '_login'):
+ backend = _HbEntitiesBackend(api_options=self._api_options())
+ backend._make_request = Mock(return_value=Response())
+ with self.assertRaises(ValueError) as context:
+ backend.get_item('e-7')
+ self.assertIn('non-JSON', str(context.exception))
+
+ def test_download_attachment_uses_entities_path(self):
+ with patch.object(_HbEntitiesBackend, '_login'):
+ backend = _HbEntitiesBackend(api_options=self._api_options())
+ response = Response()
+ response.status_code = 200
+ response.headers['content-type'] = 'image/png'
+ response._content = b'PNGDATA'
+ backend._make_request = Mock(return_value=response)
+
+ payload = backend.download_attachment(item_id='e-1', attachment_id='att-1')
+
+ self.assertEqual(payload['mime_type'], 'image/png')
+ self.assertEqual(payload['content'], b'PNGDATA')
+ backend._make_request.assert_called_once_with(
+ 'GET',
+ 'https://homebox.local/v1/entities/e-1/attachments/att-1',
+ )
+
+ def test_get_items_summary_raises_when_response_is_not_json(self):
+ """Mirror of the legacy backend's defensive check — a
+ non-JSON list response on /v1/entities signals a
+ misconfigured API URL; surface a clear ValueError instead
+ of letting the loop iterate over a raw Response."""
+ with patch.object(_HbEntitiesBackend, '_login'):
+ backend = _HbEntitiesBackend(api_options=self._api_options())
+ backend._make_request = Mock(return_value=Response())
+
+ with self.assertRaises(ValueError) as context:
+ backend.get_items_summary()
+ self.assertIn('URL may be incorrect', str(context.exception))
+
+ def test_get_items_fans_out_to_entities_detail_path(self):
+ """``get_items`` is now shared on the base class, but its
+ per-version contract is that the per-item detail fetches
+ go to the version-specific URL. Pin that the entities
+ backend routes detail fetches to /v1/entities/<id>."""
+ with patch.object(_HbEntitiesBackend, '_login'):
+ backend = _HbEntitiesBackend(api_options=self._api_options())
+ backend._make_request = Mock(side_effect=[
+ {
+ 'page': -1, 'pageSize': -1, 'total': -1,
+ 'items': [{'id': 'e-1'}, {'id': 'e-2'}],
+ },
+ {'id': 'e-1', 'name': 'One'},
+ {'id': 'e-2', 'name': 'Two'},
+ ])
+
+ items = backend.get_items()
+
+ self.assertEqual([i.id for i in items], ['e-1', 'e-2'])
+ # Per-item fetches hit the entities path, not items.
+ detail_calls = [c for c in backend._make_request.call_args_list
+ if c.args[0] == 'GET' and 'entities/' in c.args[1]]
+ self.assertEqual(len(detail_calls), 2)
+ self.assertIn(
+ 'https://homebox.local/v1/entities/e-1',
+ [c.args[1] for c in detail_calls],
+ )
+ self.assertIn(
+ 'https://homebox.local/v1/entities/e-2',
+ [c.args[1] for c in detail_calls],
+ )
diff --git a/src/hi/services/homebox/tests/test_hb_client_factory.py b/src/hi/services/homebox/tests/test_hb_client_factory.py
index 212aba3f..6ea3c93c 100644
--- a/src/hi/services/homebox/tests/test_hb_client_factory.py
+++ b/src/hi/services/homebox/tests/test_hb_client_factory.py
@@ -161,3 +161,66 @@ class TestHbClientFactory(TestCase):
kwargs = mock_client_class.call_args.kwargs
self.assertEqual(kwargs.get('timeout_secs'), 2)
+
+
+class TestHbClientFactoryResolveBackend(TestCase):
+ """Version-probe selection: ``GET /v1/entities`` is the
+ discriminator. 2xx selects the entities backend, 404 falls
+ back to the legacy backend, other errors propagate so the
+ manager can record an error state and retry later."""
+
+ def _api_options(self):
+ from hi.services.homebox.hb_client import HbClient
+ return {
+ HbClient.API_URL: 'https://homebox.local',
+ HbClient.API_USER: 'user',
+ HbClient.API_PASSWORD: 'pass',
+ }
+
+ def test_entities_200_selects_entities_backend(self):
+ from hi.services.homebox.hb_client_backends import (
+ _HbEntitiesBackend, _HbLegacyBackend,
+ )
+ with patch.object(_HbLegacyBackend, '_login'):
+ with patch.object(
+ _HbLegacyBackend, '_make_request', return_value={'items': []}
+ ):
+ backend = HbClientFactory.resolve_backend(
+ api_options=self._api_options(),
+ )
+ self.assertIsInstance(backend, _HbEntitiesBackend)
+
+ def test_entities_404_falls_back_to_legacy(self):
+ from requests import HTTPError, Response
+ from hi.services.homebox.hb_client_backends import _HbLegacyBackend
+ response = Mock(spec=Response)
+ response.status_code = 404
+ http_error = HTTPError('Not Found')
+ http_error.response = response
+
+ with patch.object(_HbLegacyBackend, '_login'):
+ with patch.object(
+ _HbLegacyBackend, '_make_request', side_effect=http_error
+ ):
+ backend = HbClientFactory.resolve_backend(
+ api_options=self._api_options(),
+ )
+ self.assertIsInstance(backend, _HbLegacyBackend)
+
+ def test_non_404_http_error_propagates(self):
+ from requests import HTTPError, Response
+ from hi.services.homebox.hb_client_backends import _HbLegacyBackend
+ response = Mock(spec=Response)
+ response.status_code = 500
+ http_error = HTTPError('Server Error')
+ http_error.response = response
+
+ with patch.object(_HbLegacyBackend, '_login'):
+ with patch.object(
+ _HbLegacyBackend, '_make_request', side_effect=http_error
+ ):
+ with self.assertRaises(HTTPError):
+ HbClientFactory.resolve_backend(
+ api_options=self._api_options(),
+ )
+
diff --git a/src/hi/simulator/services/homebox/api/urls.py b/src/hi/simulator/services/homebox/api/urls.py
index df1dbde4..8bb0af45 100644
--- a/src/hi/simulator/services/homebox/api/urls.py
+++ b/src/hi/simulator/services/homebox/api/urls.py
@@ -9,6 +9,7 @@ urlpatterns = [
views.LoginView.as_view(),
name = 'homebox_api_login' ),
+ # v0.25 legacy ``items`` family.
path( 'v1/items',
views.AllItemsView.as_view(),
name = 'homebox_api_items' ),
@@ -20,4 +21,19 @@ urlpatterns = [
re_path( r'^v1/items/(?P<item_id>[\w\-]+)/attachments/(?P<attachment_id>[\w\-]+)$',
views.AttachmentDownloadView.as_view(),
name = 'homebox_api_attachment_download' ),
+
+ # v0.26 ``entities`` family. Each view 404s when the simulator
+ # is in v0.25 mode so the integration's version probe sees the
+ # legacy fallback correctly.
+ path( 'v1/entities',
+ views.AllEntitiesView.as_view(),
+ name = 'homebox_api_entities' ),
+
+ re_path( r'^v1/entities/(?P<entity_id>[\w\-]+)$',
+ views.EntityDetailView.as_view(),
+ name = 'homebox_api_entity_detail' ),
+
+ re_path( r'^v1/entities/(?P<entity_id>[\w\-]+)/attachments/(?P<attachment_id>[\w\-]+)$',
+ views.EntityAttachmentDownloadView.as_view(),
+ name = 'homebox_api_entity_attachment_download' ),
]
diff --git a/src/hi/simulator/services/homebox/api/views.py b/src/hi/simulator/services/homebox/api/views.py
index ec96ef33..0caf752f 100644
--- a/src/hi/simulator/services/homebox/api/views.py
+++ b/src/hi/simulator/services/homebox/api/views.py
@@ -2,19 +2,27 @@
Emulated HomeBox REST API endpoints.
Mirrors the subset of the real HomeBox API consumed by the main app's
-HomeBox integration:
- - POST /v1/users/login
- - GET /v1/items
- - GET /v1/items/<id>
- - GET /v1/items/<id>/attachments/<key>
-
-The login endpoint accepts any credentials and returns a fixed token. The
-token is not validated on subsequent requests. Both the request body
-shapes and the response shapes match the real HomeBox API closely enough
-for the integration's HbItem parser to consume them unchanged. The
-attachment download endpoint serves bytes generated on the fly from
-the per-item ``attachment_keys`` configuration plus the catalog in
-``attachment_catalog`` — no files on disk.
+HomeBox integration. Two endpoint families are served, switched by
+the simulator's ``api_version`` setting:
+
+ - v0.25 mode (default): ``/v1/items/*``
+ - POST /v1/users/login
+ - GET /v1/items
+ - GET /v1/items/<id>
+ - GET /v1/items/<id>/attachments/<key>
+ - v0.26 mode: ``/v1/entities/*`` (the "entity merge")
+ - GET /v1/entities
+ - GET /v1/entities/<id>
+ - GET /v1/entities/<id>/attachments/<key>
+
+When the simulator is in the "wrong" mode for a given URL family
+the view returns 404 — that's what lets the integration's version
+probe (which 404-detects) resolve correctly against the simulator.
+
+The login endpoint accepts any credentials and is served in either
+mode (auth wasn't affected by the entity merge). Attachment download
+URL shape changes paths but the response shape is identical between
+versions.
"""
from django.http import HttpResponse, JsonResponse
@@ -26,8 +34,12 @@ from hi.simulator.services.homebox.attachment_catalog import (
parse_attachment_keys,
render_attachment_content,
)
-from hi.simulator.services.homebox.sim_models import build_item_api_dict
-from hi.simulator.services.homebox.simulator import HomeBoxSimulator
+from hi.simulator.services.homebox.sim_models import (
+ build_entity_api_dict,
+ build_item_api_dict,
+ build_paginated_envelope,
+)
+from hi.simulator.services.homebox.simulator import HbApiVersion, HomeBoxSimulator
# Static token returned by the simulator's login endpoint. Not validated
@@ -54,14 +66,28 @@ def _api_id_for(fields, sim_entity_id) -> str:
return fields.item_id or str(sim_entity_id)
-class AllItemsView( View ):
+def _not_found( message: str ) -> JsonResponse:
+ return JsonResponse( { 'message': message }, status = 404 )
+
+
+# ----- v0.25 ``/v1/items/*`` views ------------------------------------
+
+
+class _LegacyOnlyMixin:
+ """Returns 404 when the simulator is in v0.26 mode so the
+ version probe in the integration's client factory correctly
+ detects the absence of the legacy endpoints."""
+
+ def _legacy_mode_active( self, simulator: HomeBoxSimulator ) -> bool:
+ return simulator.api_version is HbApiVersion.V0_25
+
+
+class AllItemsView( View, _LegacyOnlyMixin ):
def get(self, request, *args, **kwargs):
- # No broad except: if entity hydration or dict-building
- # fails for any reason, surface a real 500 with the
- # traceback so problems are visible. Returning an empty
- # items list silently was previously masking real bugs.
simulator = HomeBoxSimulator()
+ if not self._legacy_mode_active( simulator ):
+ return _not_found( 'Legacy items endpoint not served in v0.26 mode' )
items = [
build_item_api_dict(
sim_entity_id = sim_entity_id,
@@ -77,11 +103,13 @@ class AllItemsView( View ):
return JsonResponse( { 'items': items } )
-class ItemDetailView( View ):
+class ItemDetailView( View, _LegacyOnlyMixin ):
def get(self, request, *args, **kwargs):
item_id = kwargs.get('item_id')
simulator = HomeBoxSimulator()
+ if not self._legacy_mode_active( simulator ):
+ return _not_found( f'Item {item_id} not found' )
for ( sim_entity_id, fields, archived_state,
created_at, updated_at ) in simulator.get_sim_entity_pairs():
if _api_id_for(fields, sim_entity_id) == item_id:
@@ -92,10 +120,47 @@ class ItemDetailView( View ):
created_at = created_at,
updated_at = updated_at,
))
- return JsonResponse( { 'message': f'Item {item_id} not found' }, status = 404 )
+ return _not_found( f'Item {item_id} not found' )
+
+
+def _serve_attachment( request, item_id, attachment_id, simulator ):
+ """Common attachment-serving logic for both API versions; the
+ URL path differs but the response is identical."""
+ thumbnail_suffix = '-thumb'
+ is_thumbnail = attachment_id.endswith( thumbnail_suffix )
+ lookup_key = (
+ attachment_id[:-len(thumbnail_suffix)]
+ if is_thumbnail else attachment_id
+ )
+
+ for ( sim_entity_id, fields, _archived_state,
+ _created_at, _updated_at ) in simulator.get_sim_entity_pairs():
+ if _api_id_for(fields, sim_entity_id) != item_id:
+ continue
+ templates_by_key = {
+ template.key: template
+ for template in parse_attachment_keys( fields.attachment_keys )
+ }
+ template = templates_by_key.get( lookup_key )
+ if template is None:
+ return _not_found( f'Attachment {attachment_id} not found' )
+ if is_thumbnail and template.kind != 'image':
+ return _not_found( f'Attachment {attachment_id} not found' )
+ rendered = render_attachment_content(
+ template = template,
+ item_name = fields.name,
+ thumbnail = is_thumbnail,
+ )
+ if not rendered:
+ return _not_found( f'Attachment {attachment_id} not found' )
+ return HttpResponse(
+ rendered['content'],
+ content_type = rendered['mime_type'],
+ )
+ return _not_found( f'Item {item_id} not found' )
-class AttachmentDownloadView( View ):
+class AttachmentDownloadView( View, _LegacyOnlyMixin ):
"""Serves the binary content for an attachment listed on an item.
The real HomeBox API exposes ``GET /v1/items/<id>/attachments/<id>``
@@ -109,52 +174,81 @@ class AttachmentDownloadView( View ):
"""
def get(self, request, *args, **kwargs):
- item_id = kwargs.get('item_id')
- attachment_id = kwargs.get('attachment_id')
-
- # Thumbnail variants share the underlying catalog template
- # with the main attachment but render at a smaller size.
- # The wire convention is ``<template.key>-thumb`` (see
- # ``build_attachment_metadata``).
- thumbnail_suffix = '-thumb'
- is_thumbnail = attachment_id.endswith( thumbnail_suffix )
- lookup_key = (
- attachment_id[:-len(thumbnail_suffix)]
- if is_thumbnail else attachment_id
+ simulator = HomeBoxSimulator()
+ if not self._legacy_mode_active( simulator ):
+ return _not_found( 'Legacy attachment endpoint not served in v0.26 mode' )
+ return _serve_attachment(
+ request,
+ item_id = kwargs.get('item_id'),
+ attachment_id = kwargs.get('attachment_id'),
+ simulator = simulator,
)
+
+# ----- v0.26 ``/v1/entities/*`` views ---------------------------------
+
+
+class _EntitiesOnlyMixin:
+ """Returns 404 when the simulator is in v0.25 mode so the
+ integration's version probe falls back to the legacy
+ endpoints correctly."""
+
+ def _entities_mode_active( self, simulator: HomeBoxSimulator ) -> bool:
+ return simulator.api_version is HbApiVersion.V0_26
+
+
+class AllEntitiesView( View, _EntitiesOnlyMixin ):
+
+ def get(self, request, *args, **kwargs):
simulator = HomeBoxSimulator()
- for ( sim_entity_id, fields, _archived_state,
- _created_at, _updated_at ) in simulator.get_sim_entity_pairs():
- if _api_id_for(fields, sim_entity_id) != item_id:
- continue
- templates_by_key = {
- template.key: template
- for template in parse_attachment_keys( fields.attachment_keys )
- }
- template = templates_by_key.get( lookup_key )
- if template is None:
- return JsonResponse(
- { 'message': f'Attachment {attachment_id} not found' },
- status = 404,
- )
- if is_thumbnail and template.kind != 'image':
- return JsonResponse(
- { 'message': f'Attachment {attachment_id} not found' },
- status = 404,
- )
- rendered = render_attachment_content(
- template = template,
- item_name = fields.name,
- thumbnail = is_thumbnail,
- )
- if not rendered:
- return JsonResponse(
- { 'message': f'Attachment {attachment_id} not found' },
- status = 404,
- )
- return HttpResponse(
- rendered['content'],
- content_type = rendered['mime_type'],
+ if not self._entities_mode_active( simulator ):
+ return _not_found( 'Entities endpoint not served in v0.25 mode' )
+ entities = [
+ build_entity_api_dict(
+ sim_entity_id = sim_entity_id,
+ fields = fields,
+ archived_state = archived_state,
+ created_at = created_at,
+ updated_at = updated_at,
)
- return JsonResponse( { 'message': f'Item {item_id} not found' }, status = 404 )
+ for ( sim_entity_id, fields, archived_state,
+ created_at, updated_at )
+ in simulator.get_sim_entity_pairs()
+ ]
+ return JsonResponse( build_paginated_envelope( entities ) )
+
+
+class EntityDetailView( View, _EntitiesOnlyMixin ):
+
+ def get(self, request, *args, **kwargs):
+ entity_id = kwargs.get('entity_id')
+ simulator = HomeBoxSimulator()
+ if not self._entities_mode_active( simulator ):
+ return _not_found( f'Entity {entity_id} not found' )
+ for ( sim_entity_id, fields, archived_state,
+ created_at, updated_at ) in simulator.get_sim_entity_pairs():
+ if _api_id_for(fields, sim_entity_id) == entity_id:
+ return JsonResponse( build_entity_api_dict(
+ sim_entity_id = sim_entity_id,
+ fields = fields,
+ archived_state = archived_state,
+ created_at = created_at,
+ updated_at = updated_at,
+ ))
+ return _not_found( f'Entity {entity_id} not found' )
+
+
+class EntityAttachmentDownloadView( View, _EntitiesOnlyMixin ):
+ """v0.26 attachment download. Same response shape as the
+ legacy view; only the URL path changed."""
+
+ def get(self, request, *args, **kwargs):
+ simulator = HomeBoxSimulator()
+ if not self._entities_mode_active( simulator ):
+ return _not_found( 'Entities attachment endpoint not served in v0.25 mode' )
+ return _serve_attachment(
+ request,
+ item_id = kwargs.get('entity_id'),
+ attachment_id = kwargs.get('attachment_id'),
+ simulator = simulator,
+ )
diff --git a/src/hi/simulator/services/homebox/sim_models.py b/src/hi/simulator/services/homebox/sim_models.py
index ca562996..c81e32fa 100644
--- a/src/hi/simulator/services/homebox/sim_models.py
+++ b/src/hi/simulator/services/homebox/sim_models.py
@@ -247,3 +247,67 @@ def build_item_api_dict( sim_entity_id : int,
'createdAt' : created_at.isoformat(),
'updatedAt' : updated_at.isoformat(),
}
+
+
+# Sentinel entity type emitted on every v0.26 response. The
+# simulator doesn't model the user-definable entity-type system
+# from the real HomeBox v0.26+ — every simulated row is an
+# inventory item, which maps to the default "Item" type. The id
+# stays constant so consumers that key off it see stable values
+# across reads.
+_DEFAULT_ENTITY_TYPE = {
+ 'id' : 'entity-type-item',
+ 'name' : 'Item',
+ 'isLocation' : False,
+}
+
+
+def build_entity_api_dict( sim_entity_id : int,
+ fields : HomeBoxInventoryItemFields,
+ archived_state : HomeBoxItemArchivedState,
+ created_at,
+ updated_at ) -> Dict[ str, Any ]:
+ """
+ Build the HomeBox v0.26 entity JSON shape returned by the
+ simulator's ``/v1/entities/*`` endpoints. Same content as
+ ``build_item_api_dict`` with two response-shape differences:
+
+ - The ``location`` field is renamed to ``parent`` (locations
+ are entities themselves in v0.26 and can nest under other
+ location-type entities; for the simulator the parent is
+ always a leaf location, mirroring v0.25 semantics).
+ - A new ``entityType`` discriminator is included on every
+ entity. The simulator emits a single static "Item" type
+ since it does not model the user-definable type system.
+
+ Consumed by ``_HbEntitiesBackend`` (#373 phase 3); the field
+ normalization on that backend renames ``parent`` back to
+ ``location`` so downstream code stays version-agnostic.
+ """
+ base = build_item_api_dict(
+ sim_entity_id = sim_entity_id,
+ fields = fields,
+ archived_state = archived_state,
+ created_at = created_at,
+ updated_at = updated_at,
+ )
+ parent = base.pop( 'location' )
+ base['parent'] = parent
+ base['entityType'] = dict( _DEFAULT_ENTITY_TYPE )
+ return base
+
+
+def build_paginated_envelope( items: list ) -> Dict[ str, Any ]:
+ """Wrap a list of entity dicts in the v0.26 paginated response
+ shape. The simulator returns everything in one page (sentinel
+ ``page=-1``/``pageSize=-1`` matches v0.25's "no pagination"
+ convention) — the entities backend always passes an explicit
+ ``pageSize`` and loops on ``total`` regardless, so this is
+ safe."""
+ return {
+ 'page' : -1,
+ 'pageSize' : -1,
+ 'total' : len( items ),
+ 'items' : items,
+ 'totalPrice' : 0,
+ }
diff --git a/src/hi/simulator/services/homebox/simulator.py b/src/hi/simulator/services/homebox/simulator.py
index 8352e088..fdc1b95a 100644
--- a/src/hi/simulator/services/homebox/simulator.py
+++ b/src/hi/simulator/services/homebox/simulator.py
@@ -1,3 +1,4 @@
+from enum import Enum
from typing import List
from hi.simulator.services.base_models import SimEntityDefinition
@@ -10,8 +11,34 @@ from .sim_models import (
)
+class HbApiVersion( Enum ):
+ """The HomeBox API surface the simulator serves. v0.25 is the
+ legacy ``/v1/items/*`` shape (the only API for HomeBox versions
+ up to v0.25). v0.26+ is the ``/v1/entities/*`` shape introduced
+ by the entity-merge release. Toggle via the simulator's
+ HomeBox-specific settings panel."""
+
+ V0_25 = 'v0.25'
+ V0_26 = 'v0.26'
+
+ @classmethod
+ def default(cls):
+ return cls.V0_25
+
+ @property
+ def label(self):
+ # Operator-facing label; the value already reads naturally.
+ return self.value
+
+
class HomeBoxSimulator( ServiceSimulator ):
+ def __init_singleton__( self ):
+ # Persist the operator-selected API version across SimProfile
+ # switches (same pattern as ``_fault_mode``).
+ self._api_version = HbApiVersion.default()
+ super().__init_singleton__()
+
@property
def id(self):
return 'hb'
@@ -28,6 +55,25 @@ class HomeBoxSimulator( ServiceSimulator ):
def sim_entity_definition_list(self) -> List[ SimEntityDefinition ]:
return HOMEBOX_SIM_ENTITY_DEFINITION_LIST
+ @property
+ def api_version(self) -> HbApiVersion:
+ return self._api_version
+
+ def set_api_version( self, api_version: HbApiVersion ):
+ self._api_version = api_version
+ return
+
+ @property
+ def extras_template_name(self):
+ return 'homebox/panes/api_version_form.html'
+
+ @property
+ def extras_context(self):
+ return {
+ 'api_version': self._api_version,
+ 'api_version_choices': list( HbApiVersion ),
+ }
+
def get_sim_entity_pairs(self):
"""
Iterate (sim_entity_id, fields, archived_state, created_at,
diff --git a/src/hi/simulator/services/homebox/templates/homebox/panes/api_version_form.html b/src/hi/simulator/services/homebox/templates/homebox/panes/api_version_form.html
new file mode 100644
index 00000000..76f8a8a1
--- /dev/null
+++ b/src/hi/simulator/services/homebox/templates/homebox/panes/api_version_form.html
@@ -0,0 +1,37 @@
+{% comment %}
+ Operator toggle for the HomeBox simulator's served API version.
+ Swapped in place on submit (antinode data-async + data-mode=replace)
+ so the page doesn't reload on each flip.
+
+ Context:
+ api_version : HbApiVersion — currently active value
+ api_version_choices : list[HbApiVersion]
+{% endcomment %}
+<form id="hi-homebox-api-version-form"
+ method="post"
+ action="{% url 'homebox_api_version_set' %}"
+ class="form-inline mb-3"
+ data-async data-mode="replace">
+ {% csrf_token %}
+ <label for="hi-homebox-api-version" class="mr-2 mb-0">
+ <strong>API version:</strong>
+ </label>
+ <select id="hi-homebox-api-version"
+ name="api_version"
+ class="form-control form-control-sm"
+ onchange="this.form.requestSubmit ? this.form.requestSubmit() : this.form.submit()">
+ {% for choice in api_version_choices %}
+ <option value="{{ choice.name }}"
+ {% if choice == api_version %}selected{% endif %}>
+ {{ choice.label }}
+ </option>
+ {% endfor %}
+ </select>
+ <span class="text-muted small ml-2">
+ {% if api_version.name == "V0_25" %}
+ Serving <code>/v1/items/*</code> (HomeBox v0.25 and earlier).
+ {% else %}
+ Serving <code>/v1/entities/*</code> (HomeBox v0.26+).
+ {% endif %}
+ </span>
+</form>
diff --git a/src/hi/simulator/services/homebox/urls.py b/src/hi/simulator/services/homebox/urls.py
index f641d4ee..098c0cce 100644
--- a/src/hi/simulator/services/homebox/urls.py
+++ b/src/hi/simulator/services/homebox/urls.py
@@ -13,5 +13,9 @@ urlpatterns = [
views.ItemView.as_view(),
name = 'homebox_item' ),
+ path( 'api-version/set/',
+ views.SetApiVersionView.as_view(),
+ name = 'homebox_api_version_set' ),
+
path( 'api/', include('hi.simulator.services.homebox.api.urls' )),
]
diff --git a/src/hi/simulator/services/homebox/views.py b/src/hi/simulator/services/homebox/views.py
index 174a9ac0..f13e37fa 100644
--- a/src/hi/simulator/services/homebox/views.py
+++ b/src/hi/simulator/services/homebox/views.py
@@ -1,15 +1,23 @@
+from django.core.exceptions import BadRequest
from django.http import Http404
from django.shortcuts import render
from django.views.generic import View
from hi.simulator.services.homebox.sim_models import build_item_api_dict
-from hi.simulator.services.homebox.simulator import HomeBoxSimulator
+from hi.simulator.services.homebox.simulator import HbApiVersion, HomeBoxSimulator
def _api_id_for(fields, sim_entity_id) -> str:
return fields.item_id or str(sim_entity_id)
+def _api_version_context(simulator: HomeBoxSimulator) -> dict:
+ return {
+ 'api_version': simulator.api_version,
+ 'api_version_choices': list( HbApiVersion ),
+ }
+
+
class HomeView( View ):
def get(self, request, *args, **kwargs):
@@ -22,10 +30,36 @@ class HomeView( View ):
'name' : fields.name,
})
items.sort( key = lambda row: row['name'] )
+ context = { 'items': items }
+ context.update( _api_version_context( simulator ) )
return render(
request,
'homebox/home.html',
- { 'items': items },
+ context,
+ )
+
+
+class SetApiVersionView( View ):
+ """Operator toggle for the HomeBox simulator's served API
+ version. Used to exercise the integration's dual-API client
+ (#373) against both v0.25 (``/v1/items/*``) and v0.26+
+ (``/v1/entities/*``) shapes without needing two HomeBox
+ installs."""
+
+ TEMPLATE_NAME = 'homebox/panes/api_version_form.html'
+
+ def post(self, request, *args, **kwargs):
+ simulator = HomeBoxSimulator()
+ api_version_name = request.POST.get('api_version')
+ try:
+ api_version = HbApiVersion[ api_version_name ]
+ except (KeyError, TypeError):
+ raise BadRequest( f'Invalid api_version: {api_version_name}' )
+ simulator.set_api_version( api_version )
+ return render(
+ request,
+ self.TEMPLATE_NAME,
+ _api_version_context( simulator ),
)
diff --git a/src/hi/simulator/services/service_simulator.py b/src/hi/simulator/services/service_simulator.py
index e2e7ffaa..02b418bd 100644
--- a/src/hi/simulator/services/service_simulator.py
+++ b/src/hi/simulator/services/service_simulator.py
@@ -102,7 +102,26 @@ class ServiceSimulator( Singleton ):
def set_fault_mode( self, fault_mode : ServiceFaultMode ):
self._fault_mode = fault_mode
return
-
+
+ @property
+ def extras_template_name(self) -> str:
+ """Optional template path included in the simulator's
+ service-page toolbar for simulator-specific controls
+ (e.g., HomeBox's API-version toggle). Return None to skip
+ the include; the default is no extras."""
+ return None
+
+ @property
+ def extras_context(self) -> Dict:
+ """Extra context the ``extras_template_name`` template
+ needs beyond the standard service-page variables. Default
+ empty; override when the extras pane has dynamic choices
+ or other simulator-specific data to expose. Implementations
+ should avoid keys that collide with the standard service-
+ page context (``simulator``, ``profile_list``, etc.) since
+ the caller merges this dict via ``dict.update``."""
+ return {}
+
@property
def label(self) -> str:
""" A human-friendly label for this simulatior. """
diff --git a/src/hi/simulator/services/templates/services/pages/service.html b/src/hi/simulator/services/templates/services/pages/service.html
index 8547b784..5b33d8b6 100644
--- a/src/hi/simulator/services/templates/services/pages/service.html
+++ b/src/hi/simulator/services/templates/services/pages/service.html
@@ -41,6 +41,10 @@
{% include "services/panes/fault_mode_form.html" with simulator=simulator fault_mode_choices=fault_mode_choices %}
</div>
+{% if simulator.extras_template_name %}
+{% include simulator.extras_template_name %}
+{% endif %}
+
{% for sim_entity in simulator.sim_entities %}
{% include "services/panes/sim_entity.html" with simulator=simulator sim_entity=sim_entity %}
{% empty %}
diff --git a/src/hi/simulator/services/views.py b/src/hi/simulator/services/views.py
index 58cbb293..0b8c1ac8 100644
--- a/src/hi/simulator/services/views.py
+++ b/src/hi/simulator/services/views.py
@@ -83,6 +83,7 @@ class ServiceView( View ):
'temperature_unit_choices': list( SimTemperatureUnit ),
'temperature_unit_override': runtime_settings.temperature_unit_override,
}
+ context.update( simulator.extras_context )
return render( request, 'services/pages/service.html', context )