diff --git a/.github/workflows/validate.yaml b/.github/workflows/validate.yaml index 20dc7526..07b5dce2 100644 --- a/.github/workflows/validate.yaml +++ b/.github/workflows/validate.yaml @@ -104,7 +104,11 @@ jobs: -r requirements.txt \ -r requirements_test.txt - - name: Tests suite + - name: Tests suite (HA integration — harness) run: | - pytest --cov=./custom_components/zaptec --cov-branch + pytest tests --ignore=tests/zaptec --cov=./custom_components/zaptec --cov-branch + + - name: Tests suite (API client — plain pytest, no harness) + run: | + pytest tests/zaptec -p no:homeassistant --cov=./custom_components/zaptec --cov-branch --cov-append diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 882bd3e2..087460f1 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -163,6 +163,24 @@ To run tests and check test coverage: report, or enable the "Coverage Gutters" extension to view the coverage directly in VSCode. +The suite runs as **two pytest invocations**, and `./scripts/test` runs both: + +- **HA-integration tests** (`tests/test_*.py`) run under the + `pytest-homeassistant-custom-component` harness, which autoloads on Linux. + Run directly with: + `pytest tests --ignore=tests/zaptec --cov=./custom_components/zaptec --cov-branch` +- **API-client tests** (`tests/zaptec/*`) test the vendored `zaptec/` client, + which is destined to become a standalone PyPI library (issue #257) and has no + Home Assistant dependency. They run as plain pytest with the harness disabled + (the harness blocks non-localhost sockets, which would break their live + `api.zaptec.com/api/constants` call): + `pytest tests/zaptec -p no:homeassistant --cov=./custom_components/zaptec --cov-branch --cov-append` + +Because the harness (and its socket block) is process-wide, a bare `pytest` +is not the entry point — use `./scripts/test` or the two commands above. The +HA-integration tests require Linux; run them in the Dev Container (native +Windows is not supported for that half). `tests/zaptec/*` run anywhere. + HA requires [95% coverage](https://developers.home-assistant.io/docs/core/integration-quality-scale/rules/test-coverage/) for all core integration modules, and while HACS doesn't have the same requirements, reaching this level is still a goal for this integration. diff --git a/custom_components/zaptec/__init__.py b/custom_components/zaptec/__init__.py index acb5e111..a7514994 100644 --- a/custom_components/zaptec/__init__.py +++ b/custom_components/zaptec/__init__.py @@ -10,6 +10,7 @@ from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryError, ConfigEntryNotReady from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.aiohttp_client import async_get_clientsession +from homeassistant.helpers.typing import ConfigType from .const import ( CONF_CHARGERS, @@ -24,7 +25,7 @@ ) from .coordinator import ZaptecUpdateCoordinator, ZaptecUpdateOptions from .manager import ZaptecConfigEntry, ZaptecManager -from .services import async_setup_services, async_unload_services +from .services import async_setup_services from .zaptec import ( RETRYABLE_HTTP_STATUSES, AuthenticationError, @@ -70,6 +71,17 @@ def _config_entry_error( ] +async def async_setup(hass: HomeAssistant, _config: ConfigType) -> bool: + """Set up the zaptec integration's services. + + Called once at Home Assistant startup, independent of how many zaptec + config entries exist, so services are available regardless of which + (or how many) accounts are configured. + """ + await async_setup_services(hass) + return True + + async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up zaptec as config entry.""" @@ -205,9 +217,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: # in various HA functions. entry.runtime_data = manager - # Setup services - await async_setup_services(hass, manager) - # Setup all platforms await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) entry.async_on_unload(entry.add_update_listener(async_reload_entry)) @@ -282,9 +291,7 @@ async def async_unload_entry(hass: HomeAssistant, entry: ZaptecConfigEntry) -> b manager = entry.runtime_data await manager.cancel_streams() - unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) - await async_unload_services(hass) - return unload_ok + return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: diff --git a/custom_components/zaptec/services.py b/custom_components/zaptec/services.py index ac406ca8..e171e1f7 100644 --- a/custom_components/zaptec/services.py +++ b/custom_components/zaptec/services.py @@ -4,7 +4,7 @@ from collections.abc import Awaitable, Callable, Generator import logging -from typing import TYPE_CHECKING, TypeVar +from typing import TYPE_CHECKING from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.exceptions import HomeAssistantError @@ -22,7 +22,6 @@ _LOGGER = logging.getLogger(__name__) TServiceHandler = Callable[[ServiceCall], Awaitable[None]] -T = TypeVar("T") CHARGER_ID_SCHEMA = vol.Schema( vol.All( @@ -116,205 +115,244 @@ ) -async def async_setup_services(hass: HomeAssistant, manager: ZaptecManager) -> None: # noqa: C901 Too complex, will be fixed in https://github.com/custom-components/zaptec/issues/253 - """Set up services for zaptec.""" - - def get_as_set(service_call: ServiceCall, key: str) -> set[str]: - data = service_call.data.get(key, []) - if not isinstance(data, list): - data = [data] - return set(data) - - def iter_objects( - service_call: ServiceCall, mustbe: type[T] - ) -> Generator[tuple[ZaptecUpdateCoordinator, T]]: - ent_reg = er.async_get(hass) - dev_reg = dr.async_get(hass) - - device_ids = get_as_set(service_call, "device_id") - lookup: dict[str, str] = {} - - # Parse all entities and find their device ids which is appended to the - # list of devices. - for entity_id in get_as_set(service_call, "entity_id"): - entity_entry = ent_reg.async_get(entity_id) - if entity_entry is None: - raise HomeAssistantError(f"Unable to find entity '{entity_id}'") - if not entity_entry.device_id: - raise HomeAssistantError(f"Entity '{entity_id}' doesn't have a device") - device_ids.add(entity_entry.device_id) - lookup[entity_entry.device_id] = f"entity '{entity_id}'" - - # Parse all device ids and find the uid for each device - uids: set[str] = set() - for device_id in device_ids: - device_entry = dev_reg.async_get(device_id) - err_device = lookup.get(device_id, f"device '{device_id}'") - if device_entry is None: - raise HomeAssistantError(f"Unable to find device {err_device}") - err_device = lookup.get(device_id, f"device {device_entry.name}") - if not device_entry.identifiers: - raise HomeAssistantError(f"Unable to find identifiers for {err_device}") - for domain, uid in device_entry.identifiers: - if domain != DOMAIN: - raise HomeAssistantError(f"Non-zaptec device specified {err_device}") - uids.add(uid) - lookup[uid] = err_device - - # Append any legacy charger_id or installation_id that might be specified - field = None - if mustbe is Charger: - field = "charger_id" - elif mustbe is Installation: - field = "installation_id" - if field: - uids.update(get_as_set(service_call, field)) - - # Any uid specified at all? - if not uids: - suffix = f". Missing field '{field}'" if field else "" - raise HomeAssistantError(f"No zaptec devices specified{suffix}") - - # Loop through every uid and find the object - for uid in uids: - # Set the human readable identifier for the error message - err_device = f"{lookup[uid]} ({uid})" if uid in lookup else f"id {uid}" - +def _get_as_set(service_call: ServiceCall, key: str) -> set[str]: + """Return the given service-call field as a set of strings.""" + data = service_call.data.get(key, []) + if not isinstance(data, list): + data = [data] + return set(data) + + +def _iter_managers(hass: HomeAssistant) -> Generator[ZaptecManager]: + """Yield the manager for every currently loaded zaptec config entry.""" + for entry in hass.config_entries.async_entries(DOMAIN): + if hasattr(entry, "runtime_data"): + yield entry.runtime_data + + +def iter_objects[T]( + service_call: ServiceCall, mustbe: type[T] +) -> Generator[tuple[ZaptecUpdateCoordinator, T]]: + """Resolve the devices/entities targeted by a service call to zaptec objects. + + Devices are looked up across every loaded zaptec config entry, not just + one, so a service call still resolves correctly when multiple Zaptec + accounts are configured. + """ + hass = service_call.hass + ent_reg = er.async_get(hass) + dev_reg = dr.async_get(hass) + + device_ids = _get_as_set(service_call, "device_id") + lookup: dict[str, str] = {} + + # Parse all entities and find their device ids which is appended to the + # list of devices. + for entity_id in _get_as_set(service_call, "entity_id"): + entity_entry = ent_reg.async_get(entity_id) + if entity_entry is None: + raise HomeAssistantError(f"Unable to find entity '{entity_id}'") + if not entity_entry.device_id: + raise HomeAssistantError(f"Entity '{entity_id}' doesn't have a device") + device_ids.add(entity_entry.device_id) + lookup[entity_entry.device_id] = f"entity '{entity_id}'" + + # Parse all device ids and find the uid for each device + uids: set[str] = set() + for device_id in device_ids: + device_entry = dev_reg.async_get(device_id) + err_device = lookup.get(device_id, f"device '{device_id}'") + if device_entry is None: + raise HomeAssistantError(f"Unable to find device {err_device}") + err_device = lookup.get(device_id, f"device {device_entry.name}") + if not device_entry.identifiers: + raise HomeAssistantError(f"Unable to find identifiers for {err_device}") + for domain, uid in device_entry.identifiers: + if domain != DOMAIN: + raise HomeAssistantError(f"Non-zaptec device specified {err_device}") + uids.add(uid) + lookup[uid] = err_device + + # Append any legacy charger_id or installation_id that might be specified + field = None + if mustbe is Charger: + field = "charger_id" + elif mustbe is Installation: + field = "installation_id" + if field: + uids.update(_get_as_set(service_call, field)) + + # Any uid specified at all? + if not uids: + suffix = f". Missing field '{field}'" if field else "" + raise HomeAssistantError(f"No zaptec devices specified{suffix}") + + managers = list(_iter_managers(hass)) + + # Loop through every uid and find the object, searching every manager + for uid in uids: + # Set the human readable identifier for the error message + err_device = f"{lookup[uid]} ({uid})" if uid in lookup else f"id {uid}" + + zaptec_object = None + coordinator = None + for manager in managers: zaptec_object = manager.zaptec.get(uid) - if zaptec_object is None: - raise HomeAssistantError(f"Unable to find zaptec object for {err_device}") - if not isinstance(zaptec_object, mustbe): - raise HomeAssistantError(f"{err_device} is not a {mustbe.__name__}") - if uid not in manager.device_coordinators: - raise HomeAssistantError(f"{err_device} is not available") - - coordinator = manager.device_coordinators[uid] - yield coordinator, zaptec_object - - async def service_handle_stop_charging(service_call: ServiceCall) -> None: - _LOGGER.debug("Called stop charging") - _LOGGER.warning( - "The 'stop_charging' action is deprecated and will be removed in a future release. " - "Use the 'Stop charging' button entity instead" - ) - for coordinator, obj in iter_objects(service_call, Charger): - _LOGGER.debug(" >> to %s", obj.id) - try: - await obj.command("stop_charging_final") - except Exception as exc: - raise HomeAssistantError(f"Command 'stop_charging_final' failed: {exc}") from exc - await coordinator.trigger_poll() - - async def service_handle_resume_charging(service_call: ServiceCall) -> None: - _LOGGER.debug("Called resume charging") - _LOGGER.warning( - "The 'resume_charging' action is deprecated and will be removed in a future release. " - "Use the 'Resume charging' button entity instead" - ) - for coordinator, obj in iter_objects(service_call, mustbe=Charger): - _LOGGER.debug(" >> to %s", obj.id) - try: - await obj.command("resume_charging") - except Exception as exc: - raise HomeAssistantError(f"Command 'resume_charging' failed: {exc}") from exc - await coordinator.trigger_poll() - - async def service_handle_authorize_charging(service_call: ServiceCall) -> None: - _LOGGER.debug("Called authorize charging") - _LOGGER.warning( - "The 'authorize_charging' action is deprecated and will be removed in a future " - "release. Use the 'Authorize charging' button entity instead" - ) - for coordinator, obj in iter_objects(service_call, mustbe=Charger): - _LOGGER.debug(" >> to %s", obj.id) - try: - await obj.authorize_charge() - except Exception as exc: - raise HomeAssistantError(f"Command 'authorize_charge' failed: {exc}") from exc - await coordinator.trigger_poll() - - async def service_handle_deauthorize_charging(service_call: ServiceCall) -> None: - _LOGGER.debug("Called deauthorize charging and stop") - _LOGGER.warning( - "The 'deauthorize_charging' action is deprecated and will be removed in a future " - "release. Use the 'Deauthorize charging' button entity instead" - ) - for coordinator, obj in iter_objects(service_call, mustbe=Charger): - _LOGGER.debug(" >> to %s", obj.id) - try: - await obj.command("deauthorize_and_stop") - except Exception as exc: - raise HomeAssistantError(f"Command 'deauthorize_and_stop' failed: {exc}") from exc - await coordinator.trigger_poll() - - async def service_handle_restart_charger(service_call: ServiceCall) -> None: - _LOGGER.debug("Called restart charger") - _LOGGER.warning( - "The 'restart_charger' action is deprecated and will be removed in a future release. " - "Use the 'Restart charger' button entity instead" - ) - for coordinator, obj in iter_objects(service_call, mustbe=Charger): - _LOGGER.debug(" >> to %s", obj.id) - try: - await obj.command("restart_charger") - except Exception as exc: - raise HomeAssistantError(f"Command 'restart_charger' failed: {exc}") from exc - await coordinator.trigger_poll() - - async def service_handle_upgrade_firmware(service_call: ServiceCall) -> None: - _LOGGER.debug("Called update firmware") - _LOGGER.warning( - "The 'upgrade_firmware' action is deprecated and will be removed in a future " - "release. Use the 'Upgrade firmware' button entity instead" - ) - for coordinator, obj in iter_objects(service_call, mustbe=Charger): - _LOGGER.debug(" >> to %s", obj.id) - try: - await obj.command("upgrade_firmware") - except Exception as exc: - raise HomeAssistantError(f"Command 'upgrade_firmware' failed: {exc}") from exc - await coordinator.trigger_poll() - - async def service_handle_limit_current(service_call: ServiceCall) -> None: - _LOGGER.debug("Called set current limit") - limit_args = {} - # only add the relevant arguments if they are not None - if (available_current := service_call.data.get("available_current")) is not None: - limit_args["availableCurrent"] = available_current - if ( - available_current_phase1 := service_call.data.get("available_current_phase1") - ) is not None: - limit_args["availableCurrentPhase1"] = available_current_phase1 - if ( - available_current_phase2 := service_call.data.get("available_current_phase2") - ) is not None: - limit_args["availableCurrentPhase2"] = available_current_phase2 - if ( - available_current_phase3 := service_call.data.get("available_current_phase3") - ) is not None: - limit_args["availableCurrentPhase3"] = available_current_phase3 - for coordinator, obj in iter_objects(service_call, mustbe=Installation): - _LOGGER.debug(" >> to %s", obj.id) - try: - await obj.set_limit_current(**limit_args) - except Exception as exc: - raise HomeAssistantError(f"Limit current failed: {exc}") from exc - await coordinator.trigger_poll() - - async def service_handle_send_command(service_call: ServiceCall) -> None: - _LOGGER.debug("Called send command") - for coordinator, obj in iter_objects(service_call, mustbe=Charger): - _LOGGER.debug(" >> to %s", obj.id) - command = service_call.data.get("command") - if command is None: - raise HomeAssistantError("No Command received") - try: - await obj.command(command) - except Exception as exc: - raise HomeAssistantError(f"Command '{command}' failed: {exc}") from exc - await coordinator.trigger_poll() - - # LIST OF SERVICES + if zaptec_object is not None: + coordinator = manager.device_coordinators.get(uid) + break + + if zaptec_object is None: + raise HomeAssistantError(f"Unable to find zaptec object for {err_device}") + if not isinstance(zaptec_object, mustbe): + raise HomeAssistantError(f"{err_device} is not a {mustbe.__name__}") + if coordinator is None: + raise HomeAssistantError(f"{err_device} is not available") + + yield coordinator, zaptec_object + + +async def service_handle_stop_charging(service_call: ServiceCall) -> None: + """Handle the stop_charging service call.""" + _LOGGER.debug("Called stop charging") + _LOGGER.warning( + "The 'stop_charging' action is deprecated and will be removed in a future release. " + "Use the 'Stop charging' button entity instead" + ) + for coordinator, obj in iter_objects(service_call, Charger): + _LOGGER.debug(" >> to %s", obj.id) + try: + await obj.command("stop_charging_final") + except Exception as exc: + raise HomeAssistantError(f"Command 'stop_charging_final' failed: {exc}") from exc + await coordinator.trigger_poll() + + +async def service_handle_resume_charging(service_call: ServiceCall) -> None: + """Handle the resume_charging service call.""" + _LOGGER.debug("Called resume charging") + _LOGGER.warning( + "The 'resume_charging' action is deprecated and will be removed in a future release. " + "Use the 'Resume charging' button entity instead" + ) + for coordinator, obj in iter_objects(service_call, mustbe=Charger): + _LOGGER.debug(" >> to %s", obj.id) + try: + await obj.command("resume_charging") + except Exception as exc: + raise HomeAssistantError(f"Command 'resume_charging' failed: {exc}") from exc + await coordinator.trigger_poll() + + +async def service_handle_authorize_charging(service_call: ServiceCall) -> None: + """Handle the authorize_charging service call.""" + _LOGGER.debug("Called authorize charging") + _LOGGER.warning( + "The 'authorize_charging' action is deprecated and will be removed in a future " + "release. Use the 'Authorize charging' button entity instead" + ) + for coordinator, obj in iter_objects(service_call, mustbe=Charger): + _LOGGER.debug(" >> to %s", obj.id) + try: + await obj.authorize_charge() + except Exception as exc: + raise HomeAssistantError(f"Command 'authorize_charge' failed: {exc}") from exc + await coordinator.trigger_poll() + + +async def service_handle_deauthorize_charging(service_call: ServiceCall) -> None: + """Handle the deauthorize_charging service call.""" + _LOGGER.debug("Called deauthorize charging and stop") + _LOGGER.warning( + "The 'deauthorize_charging' action is deprecated and will be removed in a future " + "release. Use the 'Deauthorize charging' button entity instead" + ) + for coordinator, obj in iter_objects(service_call, mustbe=Charger): + _LOGGER.debug(" >> to %s", obj.id) + try: + await obj.command("deauthorize_and_stop") + except Exception as exc: + raise HomeAssistantError(f"Command 'deauthorize_and_stop' failed: {exc}") from exc + await coordinator.trigger_poll() + + +async def service_handle_restart_charger(service_call: ServiceCall) -> None: + """Handle the restart_charger service call.""" + _LOGGER.debug("Called restart charger") + _LOGGER.warning( + "The 'restart_charger' action is deprecated and will be removed in a future release. " + "Use the 'Restart charger' button entity instead" + ) + for coordinator, obj in iter_objects(service_call, mustbe=Charger): + _LOGGER.debug(" >> to %s", obj.id) + try: + await obj.command("restart_charger") + except Exception as exc: + raise HomeAssistantError(f"Command 'restart_charger' failed: {exc}") from exc + await coordinator.trigger_poll() + + +async def service_handle_upgrade_firmware(service_call: ServiceCall) -> None: + """Handle the upgrade_firmware service call.""" + _LOGGER.debug("Called update firmware") + _LOGGER.warning( + "The 'upgrade_firmware' action is deprecated and will be removed in a future " + "release. Use the 'Upgrade firmware' button entity instead" + ) + for coordinator, obj in iter_objects(service_call, mustbe=Charger): + _LOGGER.debug(" >> to %s", obj.id) + try: + await obj.command("upgrade_firmware") + except Exception as exc: + raise HomeAssistantError(f"Command 'upgrade_firmware' failed: {exc}") from exc + await coordinator.trigger_poll() + + +async def service_handle_limit_current(service_call: ServiceCall) -> None: + """Handle the limit_current service call.""" + _LOGGER.debug("Called set current limit") + limit_args = {} + # only add the relevant arguments if they are not None + if (available_current := service_call.data.get("available_current")) is not None: + limit_args["availableCurrent"] = available_current + if ( + available_current_phase1 := service_call.data.get("available_current_phase1") + ) is not None: + limit_args["availableCurrentPhase1"] = available_current_phase1 + if ( + available_current_phase2 := service_call.data.get("available_current_phase2") + ) is not None: + limit_args["availableCurrentPhase2"] = available_current_phase2 + if ( + available_current_phase3 := service_call.data.get("available_current_phase3") + ) is not None: + limit_args["availableCurrentPhase3"] = available_current_phase3 + for coordinator, obj in iter_objects(service_call, mustbe=Installation): + _LOGGER.debug(" >> to %s", obj.id) + try: + await obj.set_limit_current(**limit_args) + except Exception as exc: + raise HomeAssistantError(f"Limit current failed: {exc}") from exc + await coordinator.trigger_poll() + + +async def service_handle_send_command(service_call: ServiceCall) -> None: + """Handle the send_command service call.""" + _LOGGER.debug("Called send command") + for coordinator, obj in iter_objects(service_call, mustbe=Charger): + _LOGGER.debug(" >> to %s", obj.id) + command = service_call.data.get("command") + if command is None: + raise HomeAssistantError("No Command received") + try: + await obj.command(command) + except Exception as exc: + raise HomeAssistantError(f"Command '{command}' failed: {exc}") from exc + await coordinator.trigger_poll() + + +async def async_setup_services(hass: HomeAssistant) -> None: + """Set up services for zaptec.""" services: list[tuple[str, vol.Schema, TServiceHandler]] = [ ("stop_charging", CHARGER_ID_SCHEMA, service_handle_stop_charging), ("resume_charging", CHARGER_ID_SCHEMA, service_handle_resume_charging), @@ -334,10 +372,3 @@ async def service_handle_send_command(service_call: ServiceCall) -> None: for name, schema, handler in services: if not hass.services.has_service(DOMAIN, name): hass.services.async_register(DOMAIN, name, handler, schema=schema) - - -async def async_unload_services(hass: HomeAssistant) -> None: - """Unload zaptec services.""" - _LOGGER.debug("Unload services") - for service in hass.services.async_services().get(DOMAIN, {}): - hass.services.async_remove(DOMAIN, service) diff --git a/custom_components/zaptec/services.yaml b/custom_components/zaptec/services.yaml index 1eee58b4..0d4024ac 100644 --- a/custom_components/zaptec/services.yaml +++ b/custom_components/zaptec/services.yaml @@ -73,7 +73,7 @@ restart_charger: description: Charger identifier example: 00000000-1111-2222-3333-444444444444 -update_firmware: +upgrade_firmware: name: Update firmware description: >- Send update firmware request to the charger. Select charger diff --git a/requirements.txt b/requirements.txt index 1adb323f..be7d8a98 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,5 +6,5 @@ ruff==0.15.22 # Copy from manifest.json to get this into the dev container # without needing to start HA azure-servicebus==7.14.3 -pydantic==2.13.1 +pydantic>=2.11.7,<2.14 aiolimiter==1.2.1 diff --git a/requirements_test.txt b/requirements_test.txt index cf21f7bc..be62f2c4 100644 --- a/requirements_test.txt +++ b/requirements_test.txt @@ -1,4 +1,6 @@ pytest pytest-asyncio pytest-mock -pytest-cov \ No newline at end of file +pytest-cov +pytest-homeassistant-custom-component==0.13.324; python_version >= "3.14" +pytest-homeassistant-custom-component==0.13.316; python_version < "3.14" diff --git a/scripts/test b/scripts/test index b3d15862..58923e90 100755 --- a/scripts/test +++ b/scripts/test @@ -5,8 +5,14 @@ set -e if [ "$1" == "--skip-api" ]; then export SKIP_ZAPTEC_API_TEST="true" fi + +# HA-integration tests run under the pytest-hacc harness (autoloads on Linux). +# API-client tests (tests/zaptec/*) run as plain pytest with the harness +# disabled, so their live constants call is not socket-blocked. Coverage +# from both is combined via --cov-append. # run tests with -s to display printouts and --log-cli-level to get logger output -pytest --cov=./custom_components/zaptec --cov-branch --log-cli-level=INFO -s +pytest tests --ignore=tests/zaptec --cov=./custom_components/zaptec --cov-branch --log-cli-level=INFO -s +pytest tests/zaptec -p no:homeassistant --cov=./custom_components/zaptec --cov-branch --cov-append --log-cli-level=INFO -s # generate coverage report in html and xml coverage html diff --git a/tests/conftest.py b/tests/conftest.py index ba07a5c5..f0af50e4 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,11 +1,20 @@ """Zaptec testing configuration file.""" -import asyncio +from collections.abc import Callable, Iterable import os +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch +from homeassistant.const import CONF_PASSWORD, CONF_USERNAME +from homeassistant.core import HomeAssistant import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry +from custom_components.zaptec.const import DOMAIN +from custom_components.zaptec.manager import ZaptecManager +from custom_components.zaptec.zaptec import MISSING, Charger, Installation from custom_components.zaptec.zaptec.api import Zaptec +from custom_components.zaptec.zaptec.utils import to_under @pytest.fixture(scope="session") @@ -24,12 +33,7 @@ def skip_if_user_disabled_api_tests() -> None: @pytest.fixture(scope="session") def zaptec_username(skip_if_user_disabled_api_tests, skip_if_in_github_actions) -> str: # noqa: ANN001 (the inputs are purely to create dependencies to the env-flags above) - """ - Get the zaptec username stored in env. - - Any test relying on this fixture will be skipped if the test is running - in Gihub Actions, or the user has disabled tests requiring API login. - """ + """Get the zaptec username from env, skipping if API-login tests are disabled.""" username = os.environ.get("ZAPTEC_USERNAME") assert username, ( "Missing username, either set it with \"export ZAPTEC_USERNAME='username'\" " @@ -40,12 +44,7 @@ def zaptec_username(skip_if_user_disabled_api_tests, skip_if_in_github_actions) @pytest.fixture(scope="session") def zaptec_password(skip_if_user_disabled_api_tests, skip_if_in_github_actions) -> str: # noqa: ANN001 - """ - Get the zaptec password stored in env. - - Any test relying on this fixture will be skipped if the test is running - in Gihub Actions, or the user has disabled tests requiring API login. - """ + """Get the zaptec password from env, skipping if API-login tests are disabled.""" password = os.environ.get("ZAPTEC_PASSWORD") assert password, ( "Missing password, either set it with \"export ZAPTEC_PASSWORD='password'\" " @@ -54,14 +53,123 @@ def zaptec_password(skip_if_user_disabled_api_tests, skip_if_in_github_actions) return password -@pytest.fixture(scope="session") -def zaptec_constants() -> dict: - """Get latest constants from Zaptec API.""" +def _backed_get(data: dict[str, Any]) -> Callable[..., Any]: + """Return a `.get(key, default=MISSING)` implementation backed by `data`. + + Mirrors `ZaptecBase.__getitem__`'s key normalization (`to_under`); defaults + to `MISSING` rather than `Mapping.get`'s `None` since every real call site + (`entity.py`'s `_get_zaptec_value`) passes `default=MISSING` explicitly. + """ + + def _get(key: str, default: Any = MISSING) -> Any: + return data.get(to_under(key), default) - async def get_zaptec_constants() -> dict: - async with Zaptec("N/A", "N/A") as zaptec: - # the constants API endpoint does not require login - const: dict = await zaptec.request("constants") - return const + return _get - return asyncio.run(get_zaptec_constants()) + +def make_charger( + data: dict[str, Any], *, installation: MagicMock | None = None, charging: bool = False +) -> MagicMock: + """Build a spec'd Charger double backed by `data`. + + `model` is hardcoded rather than modeling `Charger.model`'s real + `ZCONST.serial_to_model` lookup — a deliberate simplification. + """ + charger = MagicMock(spec=Charger) + charger.id = data["id"] + charger.name = data.get("name", "Mock Charger") + charger.model = "Zaptec Charger" + charger.qual_id = f"Charger[{data['id'][-6:]}]" + charger.get.side_effect = _backed_get(data) + charger.is_charging.return_value = charging + charger.installation = installation + charger.command = AsyncMock() + charger.authorize_charge = AsyncMock() + return charger + + +def make_installation(data: dict[str, Any], *, chargers: Iterable[MagicMock] = ()) -> MagicMock: + """Build a spec'd Installation double backed by `data`.""" + install = MagicMock(spec=Installation) + install.id = data["id"] + install.name = data.get("name", "Mock Installation") + install.model = "Zaptec Installation" + install.qual_id = f"Installation[{data['id'][-6:]}]" + install.get.side_effect = _backed_get(data) + install.chargers = list(chargers) + install.stream_main = AsyncMock(return_value=None) + install.stream_close = AsyncMock(return_value=None) + install.set_limit_current = AsyncMock() + return install + + +@pytest.fixture +def mock_zaptec() -> MagicMock: + """A spec'd Zaptec client seeded with one installation and one charger. + + `__getitem__`/`__iter__`/`__contains__`/`__len__` are wired because `Zaptec` + is itself `Mapping[str, ZaptecBase]` in production, and real code (e.g. + `zaptec[deviceid]` in `__init__.py`/`coordinator.py`) indexes into it directly. + """ + installation = make_installation({"id": "inst-mock-1", "name": "Mock Home"}) + charger = make_charger( + { + "id": "chg-mock-1", + "name": "Mock Charger", + # Keys read by entities under test; extend as needed for coverage. + "operating_mode": "Connected", + "charger_operation_mode": "Connected", + }, + installation=installation, + charging=False, + ) + installation.chargers = [charger] + + objects = {installation.id: installation, charger.id: charger} + + zaptec = MagicMock(spec=Zaptec) + zaptec.__getitem__.side_effect = objects.__getitem__ + zaptec.__iter__.side_effect = lambda: iter(objects) + zaptec.__contains__.side_effect = objects.__contains__ + zaptec.__len__.side_effect = lambda: len(objects) + zaptec.get.side_effect = objects.get + zaptec.objects.return_value = list(objects.values()) + zaptec.installations = [installation] + zaptec.chargers = [charger] + zaptec.login = AsyncMock(return_value=None) + zaptec.build = AsyncMock(return_value=None) + zaptec.poll = AsyncMock(return_value=None) + zaptec.show_all_updates = False + zaptec.redact = MagicMock() + # Load-bearing, not incidental: __init__.py's startup debug-dump path does + # `message += manager.zaptec.redact.dumps()`, which setup_integration actually + # exercises. An unconfigured MagicMock here would raise TypeError on the +=. + zaptec.redact.dumps.return_value = "" + return zaptec + + +@pytest.fixture +def mock_config_entry() -> MockConfigEntry: + """A MockConfigEntry for the zaptec domain.""" + return MockConfigEntry( + domain=DOMAIN, + title="Mock Zaptec", + data={CONF_USERNAME: "user", CONF_PASSWORD: "pass"}, + entry_id="mock_entry_1", + ) + + +async def setup_integration( + hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_zaptec: MagicMock +) -> ZaptecManager: + """Set the integration up through the real async_setup, with a mocked client. + + Patches `custom_components.zaptec.Zaptec` — where `__init__.py` looks the name + up, per unittest.mock's patch-at-the-lookup rule — not the original definition + in `zaptec/api.py`, which `__init__.py`'s own import wouldn't see patched. + """ + mock_config_entry.add_to_hass(hass) + with patch("custom_components.zaptec.Zaptec", return_value=mock_zaptec): + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + return mock_config_entry.runtime_data diff --git a/tests/test_coordinator.py b/tests/test_coordinator.py new file mode 100644 index 00000000..fdb74b39 --- /dev/null +++ b/tests/test_coordinator.py @@ -0,0 +1,184 @@ +"""Behavior tests for ZaptecUpdateCoordinator, driven through the real harness.""" + +from datetime import timedelta +from unittest.mock import AsyncMock, MagicMock + +from homeassistant.core import HomeAssistant +import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from custom_components.zaptec.const import ( + ZAPTEC_POLL_INTERVAL_CHARGING, + ZAPTEC_POLL_INTERVAL_IDLE, +) +from custom_components.zaptec.coordinator import ZaptecUpdateCoordinator, ZaptecUpdateOptions +from custom_components.zaptec.zaptec import ZaptecApiError +from tests.conftest import setup_integration + + +async def test_successful_poll_marks_last_update_success( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_zaptec: MagicMock, + enable_custom_integrations: None, +) -> None: + """A successful poll leaves every coordinator reporting success.""" + manager = await setup_integration(hass, mock_config_entry, mock_zaptec) + for coordinator in manager.all_coordinators: + assert coordinator.last_update_success is True + mock_zaptec.poll.assert_awaited() + + +async def test_poll_failure_sets_update_failed( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_zaptec: MagicMock, + enable_custom_integrations: None, +) -> None: + """A ZaptecApiError during poll flips last_update_success to False.""" + manager = await setup_integration(hass, mock_config_entry, mock_zaptec) + head = manager.head_coordinator + + mock_zaptec.poll.side_effect = ZaptecApiError("boom") + await head.async_refresh() + + assert head.last_update_success is False + + +async def test_device_coordinator_switches_interval_when_charging( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_zaptec: MagicMock, + enable_custom_integrations: None, +) -> None: + """A charger's coordinator uses the shorter interval once it reports charging.""" + manager = await setup_integration(hass, mock_config_entry, mock_zaptec) + charger_coord = manager.device_coordinators["chg-mock-1"] + idle_interval = charger_coord.update_interval + assert idle_interval == timedelta(seconds=ZAPTEC_POLL_INTERVAL_IDLE) + + # Flip the seeded charger to 'charging' and re-run the update-listener path. + mock_zaptec.chargers[0].is_charging.return_value = True + charger_coord.set_update_interval() + + assert charger_coord.update_interval == timedelta(seconds=ZAPTEC_POLL_INTERVAL_CHARGING) + # Also assert the relation directly, catching e.g. const.py setting + # CHARGING >= IDLE, which the equality asserts alone would miss. + assert charger_coord.update_interval < idle_interval + + +async def test_charging_update_interval_requires_charger_object( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, +) -> None: + """Constructing a coordinator with a charging interval on a non-Charger object errors. + + Skips `setup_integration` to hit the constructor-time guard directly: a + bare `manager=MagicMock()` auto-vivifies `self.zaptec` with no error before + the `isinstance(zaptec_object, Charger)` check runs. + """ + mock_config_entry.add_to_hass(hass) + + with pytest.raises(ValueError, match="Charging update interval requires a Charger object"): + ZaptecUpdateCoordinator( + hass, + entry=mock_config_entry, + manager=MagicMock(), + options=ZaptecUpdateOptions( + name="bad", + update_interval=60, + charging_update_interval=30, + tracked_devices=set(), + poll_args={}, + zaptec_object=object(), # not a Charger instance + ), + ) + + +async def test_trigger_poll_is_noop_without_zaptec_object( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_zaptec: MagicMock, + enable_custom_integrations: None, +) -> None: + """trigger_poll() on a coordinator with no bound zaptec object does nothing. + + `head_coordinator` is the one coordinator built with `zaptec_object=None` + (device coordinators always get a real Charger/Installation), satisfying + trigger_poll()'s no-op guard. + """ + manager = await setup_integration(hass, mock_config_entry, mock_zaptec) + + await manager.head_coordinator.trigger_poll() + + assert manager.head_coordinator._trigger_task is None # noqa: SLF001 + + +async def test_trigger_poll_cancels_in_flight_task_and_reschedules( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_zaptec: MagicMock, + enable_custom_integrations: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A second trigger_poll() call cancels the running poll sequence and starts a new one.""" + manager = await setup_integration(hass, mock_config_entry, mock_zaptec) + charger_coord = manager.device_coordinators["chg-mock-1"] + + # Collapse the real delays to zero, keeping real asyncio.sleep(0) checkpoints so + # the eagerly-started background task actually suspends and can be cancelled mid-flight. + monkeypatch.setattr( + "custom_components.zaptec.coordinator.ZAPTEC_POLL_CHARGER_TRIGGER_DELAYS", [0, 0, 0] + ) + + # HA's eager task factory runs the task immediately; it suspends at the + # first sleep(0) checkpoint and is left pending. + await charger_coord.trigger_poll() + first_task = charger_coord._trigger_task # noqa: SLF001 + assert first_task is not None + + # Second call sees the still-pending first task and cancels it before rescheduling. + await charger_coord.trigger_poll() + assert first_task.cancelled() + + second_task = charger_coord._trigger_task # noqa: SLF001 + assert second_task is not None + assert second_task is not first_task + await second_task + await hass.async_block_till_done() + + assert charger_coord._trigger_task is None # noqa: SLF001 + assert charger_coord.last_update_success is True + + +async def test_trigger_poll_triggers_child_charger_coordinators( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_zaptec: MagicMock, + enable_custom_integrations: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Polling an installation also triggers the poll sequence of its tracked chargers. + + Patches `asyncio.sleep` globally, rather than the delays-list constant (as the + cancel/reschedule test does), just to reach the loop's first iteration fast — + installations use their own delay constant this test doesn't care about. + `charger_coord.trigger_poll` is mocked to isolate "parent calls child" from + the child's own trigger_poll logic (covered elsewhere). + """ + manager = await setup_integration(hass, mock_config_entry, mock_zaptec) + install_coord = manager.device_coordinators["inst-mock-1"] + charger_coord = manager.device_coordinators["chg-mock-1"] + + monkeypatch.setattr( + "custom_components.zaptec.coordinator.asyncio.sleep", AsyncMock(return_value=None) + ) + charger_coord.trigger_poll = AsyncMock() + + await install_coord.trigger_poll() + task = install_coord._trigger_task # noqa: SLF001 + assert task is not None + await task + await hass.async_block_till_done() + + charger_coord.trigger_poll.assert_awaited_once() diff --git a/tests/test_entity.py b/tests/test_entity.py new file mode 100644 index 00000000..cf7da4e9 --- /dev/null +++ b/tests/test_entity.py @@ -0,0 +1,264 @@ +"""Behavior tests for ZaptecBaseEntity, driven through the real harness.""" + +import logging +from unittest.mock import AsyncMock, MagicMock + +from homeassistant.core import HomeAssistant +import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from custom_components.zaptec.const import KEYS_TO_SKIP_ENTITY_AVAILABILITY_CHECK +from custom_components.zaptec.coordinator import ZaptecUpdateCoordinator +from custom_components.zaptec.entity import KeyUnavailableError, ZaptecBaseEntity +from custom_components.zaptec.zaptec import MISSING, ZaptecApiError +from tests.conftest import setup_integration + + +def _entity_from_coordinator( + coordinator: ZaptecUpdateCoordinator, *, key_not_in_skip_list: bool = False +) -> ZaptecBaseEntity: + """Return a real entity instance bound to `coordinator`. + + Reaches into the private `_listeners` dict since there's no public way to + list entities subscribed to a coordinator. `hasattr(candidate, "_log_value")` + filters out non-entity listeners (e.g. the coordinator's own + `set_update_interval`, also registered as a listener). + + `key_not_in_skip_list=True` skips entities whose `.key` is in + `KEYS_TO_SKIP_ENTITY_AVAILABILITY_CHECK`, needed when asserting on the + "Getting value failed" log line those keys suppress. + """ + for cb, _context in coordinator._listeners.values(): # noqa: SLF001 + candidate = cb.__self__ + if not hasattr(candidate, "_log_value"): + continue + if key_not_in_skip_list and candidate.key in KEYS_TO_SKIP_ENTITY_AVAILABILITY_CHECK: + continue + return candidate + raise AssertionError("no matching zaptec entity found") + + +async def _get_zaptec_entity(hass: HomeAssistant) -> str: + """Return one live zaptec entity_id whose value is backed by seeded data. + + Not every zaptec entity reads a key `mock_zaptec` seeds, and setup order + isn't guaranteed to surface a backed one first — skip unbacked entities. + """ + for state in hass.states.async_all(): + if state.entity_id.startswith( + ("sensor.", "binary_sensor.", "switch.", "number.") + ) and state.state not in ("unavailable", "unknown"): + return state.entity_id + raise AssertionError("no backed zaptec entity found") + + +async def test_entity_reports_value_from_zaptec( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_zaptec: MagicMock, + enable_custom_integrations: None, +) -> None: + """A backed key surfaces as the entity's state (not 'unavailable'/'unknown').""" + await setup_integration(hass, mock_config_entry, mock_zaptec) + entity_id = await _get_zaptec_entity(hass) + state = hass.states.get(entity_id) + assert state.state not in ("unavailable", "unknown") + + +async def test_entity_stays_available_when_single_key_missing( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_zaptec: MagicMock, + enable_custom_integrations: None, +) -> None: + """A single missing backing key does NOT mark the entity unavailable. + + `CoordinatorEntity.available` is driven by `coordinator.last_update_success`, + not `_attr_available` — `_handle_coordinator_update` catches the + `KeyUnavailableError` from `_update_from_zaptec`, so the poll still succeeds + and the entity keeps its previous value/state. + """ + await setup_integration(hass, mock_config_entry, mock_zaptec) + entity_id = await _get_zaptec_entity(hass) + + state_before = hass.states.get(entity_id) + assert state_before.state not in ("unavailable", "unknown") + + # Make every key lookup miss, then re-run a refresh so entities re-read. + mock_zaptec.chargers[0].get.side_effect = lambda _key, default=MISSING: default + manager = mock_config_entry.runtime_data + for coordinator in manager.all_coordinators: + await coordinator.async_refresh() + await hass.async_block_till_done() + + state_after = hass.states.get(entity_id) + assert state_after.state != "unavailable" + assert state_after.state == state_before.state + + +async def test_entity_unavailable_when_coordinator_poll_fails( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_zaptec: MagicMock, + enable_custom_integrations: None, +) -> None: + """The entity reports 'unavailable' when its coordinator's poll fails. + + `CoordinatorEntity.available` reflects `coordinator.last_update_success`, + not any per-key state. + """ + manager = await setup_integration(hass, mock_config_entry, mock_zaptec) + entity_id = await _get_zaptec_entity(hass) + + mock_zaptec.poll.side_effect = ZaptecApiError("boom") + coordinator = manager.device_coordinators["chg-mock-1"] + await coordinator.async_refresh() + await hass.async_block_till_done() + + assert hass.states.get(entity_id).state == "unavailable" + + +async def test_log_value_logs_on_change_then_skips_when_unchanged( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_zaptec: MagicMock, + caplog: pytest.LogCaptureFixture, + enable_custom_integrations: None, +) -> None: + """_log_value logs when the tracked value changes and stays quiet when it doesn't. + + `_log_value` reads an arbitrary attribute via `getattr` and dedups against + `_prev_value`, purely to feed a debug log line — no `hass.states` to assert on. + """ + manager = await setup_integration(hass, mock_config_entry, mock_zaptec) + coordinator = manager.device_coordinators["chg-mock-1"] + entity = _entity_from_coordinator(coordinator) + entity.some_attr = "value1" + + with caplog.at_level(logging.DEBUG): + entity._log_value("some_attr") # noqa: SLF001 + assert "value1" in caplog.text + + caplog.clear() + with caplog.at_level(logging.DEBUG): + entity._log_value("some_attr") # noqa: SLF001 + assert caplog.text == "" + + +async def test_get_zaptec_value_returns_default_when_key_missing( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_zaptec: MagicMock, + enable_custom_integrations: None, +) -> None: + """_get_zaptec_value() returns the caller's default when the key isn't backed. + + Covers the one production call site that opts out of the `MISSING`-triggers- + `KeyUnavailableError` default (`sensor.py`'s `default={}` for `completed_session`). + """ + manager = await setup_integration(hass, mock_config_entry, mock_zaptec) + coordinator = manager.device_coordinators["chg-mock-1"] + entity = _entity_from_coordinator(coordinator) + + sentinel = object() + assert entity._get_zaptec_value(key="totally_missing_key", default=sentinel) is sentinel # noqa: SLF001 + + +async def test_get_zaptec_value_raises_when_intermediate_value_not_mapping( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_zaptec: MagicMock, + enable_custom_integrations: None, +) -> None: + """A dotted key whose first segment resolves to a non-Mapping value raises. + + No shipped entity uses a dotted key today, so this exercises + `_get_zaptec_value`'s "obj isn't Mapping-like" branch directly, guarding it + for whenever one does. + """ + manager = await setup_integration(hass, mock_config_entry, mock_zaptec) + coordinator = manager.device_coordinators["chg-mock-1"] + entity = _entity_from_coordinator(coordinator) + + # "operating_mode" is seeded as a plain string, which has no `.get()`. + with pytest.raises(KeyUnavailableError): + entity._get_zaptec_value(key="operating_mode.sub") # noqa: SLF001 + + +async def test_log_zaptec_attribute_formats_none_str_iterable_and_scalar_keys( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_zaptec: MagicMock, + enable_custom_integrations: None, +) -> None: + """_log_zaptec_attribute formats None, a single key, an iterable, and a scalar. + + Pokes all four branches directly since the property only feeds a debug log + line. `str` (default `description.key`) and `Iterable` (sensor.py/update.py's + multi-key logging) are live; `None` and the scalar fallback are currently + unreachable in production but worth guarding. + """ + manager = await setup_integration(hass, mock_config_entry, mock_zaptec) + coordinator = manager.device_coordinators["chg-mock-1"] + entity = _entity_from_coordinator(coordinator) + + entity._log_zaptec_key = None # noqa: SLF001 + assert entity._log_zaptec_attribute == "" # noqa: SLF001 + + entity._log_zaptec_key = "foo" # noqa: SLF001 + assert entity._log_zaptec_attribute == ".foo" # noqa: SLF001 + + entity._log_zaptec_key = ["foo", "bar"] # noqa: SLF001 + assert entity._log_zaptec_attribute == ".foo and .bar" # noqa: SLF001 + + entity._log_zaptec_key = 42 # noqa: SLF001 + assert entity._log_zaptec_attribute == ".42" # noqa: SLF001 + + +async def test_log_unavailable_logs_error_and_recovery_transitions( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_zaptec: MagicMock, + caplog: pytest.LogCaptureFixture, + enable_custom_integrations: None, +) -> None: + """_log_unavailable logs the real exception on going unavailable, and logs recovery. + + Sets `_attr_available`/`_prev_available` directly since they're decoupled + from `CoordinatorEntity.available` (which reads `last_update_success`) — no + real coordinator refresh can drive both log transitions. + """ + manager = await setup_integration(hass, mock_config_entry, mock_zaptec) + coordinator = manager.device_coordinators["chg-mock-1"] + entity = _entity_from_coordinator(coordinator, key_not_in_skip_list=True) + + entity._prev_available = True # noqa: SLF001 + entity._attr_available = False # noqa: SLF001 + with caplog.at_level(logging.DEBUG): + entity._log_unavailable(RuntimeError("boom")) # noqa: SLF001 + assert f"Entity {entity.entity_id} is unavailable" in caplog.text + assert "Getting value failed" in caplog.text + + caplog.clear() + entity._prev_available = False # noqa: SLF001 + entity._attr_available = True # noqa: SLF001 + with caplog.at_level(logging.DEBUG): + entity._log_unavailable() # noqa: SLF001 + assert f"Entity {entity.entity_id} is available" in caplog.text + + +async def test_entity_trigger_poll_delegates_to_coordinator( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_zaptec: MagicMock, + enable_custom_integrations: None, +) -> None: + """ZaptecBaseEntity.trigger_poll() awaits the bound coordinator's trigger_poll().""" + manager = await setup_integration(hass, mock_config_entry, mock_zaptec) + coordinator = manager.device_coordinators["chg-mock-1"] + entity = _entity_from_coordinator(coordinator) + + coordinator.trigger_poll = AsyncMock() + await entity.trigger_poll() + + coordinator.trigger_poll.assert_awaited_once() diff --git a/tests/test_init.py b/tests/test_init.py index 4082b177..6a00fb20 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -1,17 +1,22 @@ """Tests for custom_components.zaptec.__init__.""" from http import HTTPStatus +from unittest.mock import MagicMock +from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryError, ConfigEntryNotReady import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry from custom_components.zaptec import _config_entry_error +from custom_components.zaptec.manager import ZaptecManager from custom_components.zaptec.zaptec.exceptions import ( AuthenticationError, RequestConnectionError, RequestError, RequestTimeoutError, ) +from tests.conftest import setup_integration @pytest.mark.parametrize( @@ -22,7 +27,7 @@ # Connection/timeout are recoverable -> HA retries setup. (RequestTimeoutError("slow"), ConfigEntryNotReady), (RequestConnectionError("down"), ConfigEntryNotReady), - # Transient server statuses are recoverable -> HA retries setup (issue #392). + # Transient server statuses are recoverable -> HA retries setup. (RequestError("unavailable", HTTPStatus.SERVICE_UNAVAILABLE), ConfigEntryNotReady), (RequestError("too many", HTTPStatus.TOO_MANY_REQUESTS), ConfigEntryNotReady), # Other HTTP errors stay permanent. @@ -33,3 +38,20 @@ def test_config_entry_error_mapping(err: Exception, expected: type[Exception]) -> None: """Setup login errors map to the right Home Assistant config-entry error.""" assert isinstance(_config_entry_error(err), expected) + + +async def test_setup_entry_creates_manager_and_entities( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_zaptec: MagicMock, + enable_custom_integrations: None, +) -> None: + """A full setup wires up the manager and registers at least one entity.""" + manager = await setup_integration(hass, mock_config_entry, mock_zaptec) + + assert isinstance(manager, ZaptecManager) + assert mock_config_entry.runtime_data is manager + # Matches because mock_zaptec seeds "Mock Charger"/"Mock Home", which HA + # slugifies into "mock..." entity_ids. Update if that seed naming changes. + states = [s for s in hass.states.async_all() if s.entity_id.split(".")[1].startswith("mock")] + assert states, "expected at least one zaptec entity to be created" diff --git a/tests/test_services.py b/tests/test_services.py new file mode 100644 index 00000000..4c78ad83 --- /dev/null +++ b/tests/test_services.py @@ -0,0 +1,519 @@ +"""Tests for services.py.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +from homeassistant.core import HomeAssistant, ServiceCall +from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers import device_registry as dr, entity_registry as er +import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry +import voluptuous as vol +import yaml + +from custom_components.zaptec.const import DOMAIN +from custom_components.zaptec.manager import ZaptecManager +import custom_components.zaptec.services as services_module +from custom_components.zaptec.services import ( + CHARGER_ID_SCHEMA, + LIMIT_CURRENT_SCHEMA, + SEND_COMMAND_SCHEMA, + async_setup_services, + service_handle_authorize_charging, + service_handle_deauthorize_charging, + service_handle_limit_current, + service_handle_restart_charger, + service_handle_resume_charging, + service_handle_send_command, + service_handle_stop_charging, + service_handle_upgrade_firmware, +) +from custom_components.zaptec.zaptec import Charger +from tests.conftest import setup_integration + +SERVICES_YAML_PATH = Path(services_module.__file__).with_name("services.yaml") + +INSTALLATION_ID = "inst-mock-1" +CHARGER_ID = "chg-mock-1" + + +def make_call(hass: HomeAssistant, data: dict[str, Any]) -> ServiceCall: + """Build a ServiceCall carrying the given data, bypassing schema validation.""" + return ServiceCall(hass, DOMAIN, "test_service", data) + + +@pytest.fixture +async def manager( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_zaptec: MagicMock, + enable_custom_integrations: None, +) -> ZaptecManager: + """A real ZaptecManager from a full integration setup (registers services too).""" + return await setup_integration(hass, mock_config_entry, mock_zaptec) + + +@pytest.fixture +def charger(manager: ZaptecManager) -> MagicMock: + """The mock charger seeded by mock_zaptec, resolved through the real manager.""" + return manager.zaptec[CHARGER_ID] + + +@pytest.fixture +def installation(manager: ZaptecManager) -> MagicMock: + """The mock installation seeded by mock_zaptec, resolved through the real manager.""" + return manager.zaptec[INSTALLATION_ID] + + +# --------------------------------------------------------------------------- +# async_setup_services +# --------------------------------------------------------------------------- + + +async def test_setup_registers_all_services(hass: HomeAssistant, manager: ZaptecManager) -> None: + """A full integration setup registers all eight zaptec services.""" + assert hass.services.async_services().get(DOMAIN, {}).keys() == { + "stop_charging", + "resume_charging", + "authorize_charging", + "deauthorize_charging", + "restart_charger", + "upgrade_firmware", + "limit_current", + "send_command", + } + + +async def test_setup_is_idempotent(hass: HomeAssistant, manager: ZaptecManager) -> None: + """Calling async_setup_services again (e.g. a second config entry) re-registers nothing.""" + stop_charging_before = hass.services.async_services()[DOMAIN]["stop_charging"] + + await async_setup_services(hass) + + assert hass.services.async_services()[DOMAIN]["stop_charging"] is stop_charging_before + + +# --------------------------------------------------------------------------- +# iter_objects resolution / error paths (exercised through stop_charging) +# --------------------------------------------------------------------------- + + +async def test_resolves_via_legacy_charger_id(hass: HomeAssistant, charger: MagicMock) -> None: + """A bare charger_id resolves directly to the zaptec object.""" + await service_handle_stop_charging(make_call(hass, {"charger_id": CHARGER_ID})) + + charger.command.assert_awaited_once_with("stop_charging_final") + + +async def test_resolves_via_device_id(hass: HomeAssistant, charger: MagicMock) -> None: + """A device_id resolves through the device registry's zaptec identifier.""" + device = dr.async_get(hass).async_get_device(identifiers={(DOMAIN, CHARGER_ID)}) + assert device is not None + + await service_handle_stop_charging(make_call(hass, {"device_id": device.id})) + + charger.command.assert_awaited_once_with("stop_charging_final") + + +async def test_resolves_via_entity_id(hass: HomeAssistant, charger: MagicMock) -> None: + """An entity_id resolves through the entity registry's device, then the device registry.""" + device = dr.async_get(hass).async_get_device(identifiers={(DOMAIN, CHARGER_ID)}) + assert device is not None + entity_entry = next( + e for e in er.async_get(hass).entities.values() if e.device_id == device.id + ) + + await service_handle_stop_charging(make_call(hass, {"entity_id": entity_entry.entity_id})) + + charger.command.assert_awaited_once_with("stop_charging_final") + + +async def test_entity_id_not_found_raises(hass: HomeAssistant, manager: ZaptecManager) -> None: + """An unknown entity_id raises a HomeAssistantError.""" + with pytest.raises(HomeAssistantError, match="Unable to find entity"): + await service_handle_stop_charging(make_call(hass, {"entity_id": "sensor.missing"})) + + +async def test_entity_without_device_raises(hass: HomeAssistant, manager: ZaptecManager) -> None: + """An entity with no device_id raises a HomeAssistantError.""" + entry = er.async_get(hass).async_get_or_create("sensor", "other", "no_device_unique_id") + + with pytest.raises(HomeAssistantError, match="doesn't have a device"): + await service_handle_stop_charging(make_call(hass, {"entity_id": entry.entity_id})) + + +async def test_device_id_not_found_raises(hass: HomeAssistant, manager: ZaptecManager) -> None: + """An unknown device_id raises a HomeAssistantError.""" + with pytest.raises(HomeAssistantError, match="Unable to find device"): + await service_handle_stop_charging(make_call(hass, {"device_id": "device_missing"})) + + +async def test_device_without_identifiers_raises( + hass: HomeAssistant, manager: ZaptecManager, mock_config_entry: MockConfigEntry +) -> None: + """A device with no zaptec identifiers raises a HomeAssistantError.""" + device = dr.async_get(hass).async_get_or_create( + config_entry_id=mock_config_entry.entry_id, connections={("mac", "00:00:00:00:00:00")} + ) + + with pytest.raises(HomeAssistantError, match="Unable to find identifiers"): + await service_handle_stop_charging(make_call(hass, {"device_id": device.id})) + + +async def test_device_with_non_zaptec_identifier_raises( + hass: HomeAssistant, manager: ZaptecManager, mock_config_entry: MockConfigEntry +) -> None: + """A device tied to a non-zaptec identifier domain raises a HomeAssistantError.""" + device = dr.async_get(hass).async_get_or_create( + config_entry_id=mock_config_entry.entry_id, identifiers={("other_domain", "foo")} + ) + + with pytest.raises(HomeAssistantError, match="Non-zaptec device specified"): + await service_handle_stop_charging(make_call(hass, {"device_id": device.id})) + + +async def test_no_ids_specified_raises_with_missing_field( + hass: HomeAssistant, manager: ZaptecManager +) -> None: + """Calling a handler with none of charger_id/device_id/entity_id names the missing field.""" + with pytest.raises(HomeAssistantError, match="Missing field 'charger_id'"): + await service_handle_stop_charging(make_call(hass, {})) + + +async def test_unknown_zaptec_object_raises(hass: HomeAssistant, manager: ZaptecManager) -> None: + """A uid with no matching zaptec object raises a HomeAssistantError.""" + with pytest.raises(HomeAssistantError, match="Unable to find zaptec object"): + await service_handle_stop_charging(make_call(hass, {"charger_id": "charger_missing"})) + + +async def test_wrong_object_type_raises(hass: HomeAssistant, manager: ZaptecManager) -> None: + """A uid resolving to the wrong zaptec object type raises a HomeAssistantError.""" + with pytest.raises(HomeAssistantError, match="is not a Charger"): + await service_handle_stop_charging(make_call(hass, {"charger_id": INSTALLATION_ID})) + + +async def test_object_without_coordinator_raises( + hass: HomeAssistant, manager: ZaptecManager +) -> None: + """A resolved zaptec object with no matching coordinator raises a HomeAssistantError.""" + del manager.device_coordinators[CHARGER_ID] + + with pytest.raises(HomeAssistantError, match="is not available"): + await service_handle_stop_charging(make_call(hass, {"charger_id": CHARGER_ID})) + + +async def test_resolves_across_multiple_config_entries( + hass: HomeAssistant, manager: ZaptecManager +) -> None: + """A service call resolves a charger under a second config entry's manager.""" + other_charger_id = "chg-mock-2" + other_charger = MagicMock(spec=Charger) + other_charger.id = other_charger_id + other_charger.command = AsyncMock() + other_coordinator = MagicMock() + other_coordinator.trigger_poll = AsyncMock() + + other_manager = MagicMock() + other_manager.zaptec = {other_charger_id: other_charger} + other_manager.device_coordinators = {other_charger_id: other_coordinator} + + other_entry = MockConfigEntry(domain=DOMAIN, title="Second account") + other_entry.add_to_hass(hass) + other_entry.runtime_data = other_manager + + await service_handle_stop_charging(make_call(hass, {"charger_id": other_charger_id})) + + other_charger.command.assert_awaited_once_with("stop_charging_final") + + +async def test_unloaded_config_entry_without_runtime_data_is_skipped( + hass: HomeAssistant, charger: MagicMock +) -> None: + """An entry with no runtime_data (never set up) is skipped, not crashed on.""" + other_entry = MockConfigEntry(domain=DOMAIN, title="Not set up") + other_entry.add_to_hass(hass) + + await service_handle_stop_charging(make_call(hass, {"charger_id": CHARGER_ID})) + + charger.command.assert_awaited_once_with("stop_charging_final") + + +# --------------------------------------------------------------------------- +# Individual service handlers +# --------------------------------------------------------------------------- + + +async def test_stop_charging_wraps_command_failure( + hass: HomeAssistant, charger: MagicMock, manager: ZaptecManager +) -> None: + """A command failure is wrapped in HomeAssistantError and no poll is triggered.""" + charger.command.side_effect = Exception("boom") + + with pytest.raises(HomeAssistantError, match="stop_charging_final"): + await service_handle_stop_charging(make_call(hass, {"charger_id": CHARGER_ID})) + + +async def test_resume_charging_sends_command(hass: HomeAssistant, charger: MagicMock) -> None: + """resume_charging sends the resume_charging command.""" + await service_handle_resume_charging(make_call(hass, {"charger_id": CHARGER_ID})) + + charger.command.assert_awaited_once_with("resume_charging") + + +async def test_resume_charging_wraps_command_failure( + hass: HomeAssistant, charger: MagicMock +) -> None: + """A command failure is wrapped in HomeAssistantError.""" + charger.command.side_effect = Exception("boom") + + with pytest.raises(HomeAssistantError, match="resume_charging"): + await service_handle_resume_charging(make_call(hass, {"charger_id": CHARGER_ID})) + + +async def test_authorize_charging_calls_authorize_charge( + hass: HomeAssistant, charger: MagicMock +) -> None: + """authorize_charging calls authorize_charge.""" + await service_handle_authorize_charging(make_call(hass, {"charger_id": CHARGER_ID})) + + charger.authorize_charge.assert_awaited_once() + + +async def test_authorize_charging_wraps_failure(hass: HomeAssistant, charger: MagicMock) -> None: + """An authorize_charge failure is wrapped in HomeAssistantError.""" + charger.authorize_charge.side_effect = Exception("boom") + + with pytest.raises(HomeAssistantError, match="authorize_charge"): + await service_handle_authorize_charging(make_call(hass, {"charger_id": CHARGER_ID})) + + +async def test_deauthorize_charging_sends_command( + hass: HomeAssistant, charger: MagicMock +) -> None: + """deauthorize_charging sends the deauthorize_and_stop command.""" + await service_handle_deauthorize_charging(make_call(hass, {"charger_id": CHARGER_ID})) + + charger.command.assert_awaited_once_with("deauthorize_and_stop") + + +async def test_deauthorize_charging_wraps_command_failure( + hass: HomeAssistant, charger: MagicMock +) -> None: + """A command failure is wrapped in HomeAssistantError.""" + charger.command.side_effect = Exception("boom") + + with pytest.raises(HomeAssistantError, match="deauthorize_and_stop"): + await service_handle_deauthorize_charging(make_call(hass, {"charger_id": CHARGER_ID})) + + +async def test_restart_charger_sends_command(hass: HomeAssistant, charger: MagicMock) -> None: + """restart_charger sends the restart_charger command.""" + await service_handle_restart_charger(make_call(hass, {"charger_id": CHARGER_ID})) + + charger.command.assert_awaited_once_with("restart_charger") + + +async def test_restart_charger_wraps_command_failure( + hass: HomeAssistant, charger: MagicMock +) -> None: + """A command failure is wrapped in HomeAssistantError.""" + charger.command.side_effect = Exception("boom") + + with pytest.raises(HomeAssistantError, match="restart_charger"): + await service_handle_restart_charger(make_call(hass, {"charger_id": CHARGER_ID})) + + +async def test_upgrade_firmware_sends_command(hass: HomeAssistant, charger: MagicMock) -> None: + """upgrade_firmware sends the upgrade_firmware command.""" + await service_handle_upgrade_firmware(make_call(hass, {"charger_id": CHARGER_ID})) + + charger.command.assert_awaited_once_with("upgrade_firmware") + + +async def test_upgrade_firmware_wraps_command_failure( + hass: HomeAssistant, charger: MagicMock +) -> None: + """A command failure is wrapped in HomeAssistantError.""" + charger.command.side_effect = Exception("boom") + + with pytest.raises(HomeAssistantError, match="upgrade_firmware"): + await service_handle_upgrade_firmware(make_call(hass, {"charger_id": CHARGER_ID})) + + +async def test_limit_current_with_available_current_only( + hass: HomeAssistant, installation: MagicMock +) -> None: + """Only availableCurrent is passed through when available_current is set.""" + await service_handle_limit_current( + make_call(hass, {"installation_id": INSTALLATION_ID, "available_current": 16}) + ) + + installation.set_limit_current.assert_awaited_once_with(availableCurrent=16) + + +async def test_limit_current_with_all_phases( + hass: HomeAssistant, installation: MagicMock +) -> None: + """All three phase kwargs are passed through when the phase fields are set.""" + await service_handle_limit_current( + make_call( + hass, + { + "installation_id": INSTALLATION_ID, + "available_current_phase1": 10, + "available_current_phase2": 11, + "available_current_phase3": 12, + }, + ) + ) + + installation.set_limit_current.assert_awaited_once_with( + availableCurrentPhase1=10, availableCurrentPhase2=11, availableCurrentPhase3=12 + ) + + +async def test_limit_current_wraps_failure(hass: HomeAssistant, installation: MagicMock) -> None: + """A set_limit_current failure is wrapped in HomeAssistantError.""" + installation.set_limit_current.side_effect = Exception("boom") + + with pytest.raises(HomeAssistantError, match="Limit current failed"): + await service_handle_limit_current( + make_call(hass, {"installation_id": INSTALLATION_ID, "available_current": 16}) + ) + + +async def test_send_command_with_string_command(hass: HomeAssistant, charger: MagicMock) -> None: + """send_command forwards a string command.""" + await service_handle_send_command( + make_call(hass, {"charger_id": CHARGER_ID, "command": "StopChargingFinal"}) + ) + + charger.command.assert_awaited_once_with("StopChargingFinal") + + +async def test_send_command_with_integer_command(hass: HomeAssistant, charger: MagicMock) -> None: + """send_command forwards an integer command.""" + await service_handle_send_command(make_call(hass, {"charger_id": CHARGER_ID, "command": 507})) + + charger.command.assert_awaited_once_with(507) + + +async def test_send_command_missing_command_raises( + hass: HomeAssistant, charger: MagicMock +) -> None: + """send_command without a command value raises before calling the charger.""" + with pytest.raises(HomeAssistantError, match="No Command received"): + await service_handle_send_command(make_call(hass, {"charger_id": CHARGER_ID})) + + charger.command.assert_not_awaited() + + +async def test_send_command_wraps_failure(hass: HomeAssistant, charger: MagicMock) -> None: + """A command failure is wrapped in HomeAssistantError.""" + charger.command.side_effect = Exception("boom") + + with pytest.raises(HomeAssistantError, match="'StopChargingFinal' failed"): + await service_handle_send_command( + make_call(hass, {"charger_id": CHARGER_ID, "command": "StopChargingFinal"}) + ) + + +# --------------------------------------------------------------------------- +# Schema validation +# --------------------------------------------------------------------------- + + +def test_charger_id_schema_requires_one_of_the_id_fields() -> None: + """CHARGER_ID_SCHEMA rejects data with none of charger_id/device_id/entity_id.""" + with pytest.raises(vol.Invalid, match="At leas one of"): + CHARGER_ID_SCHEMA({}) + + +def test_charger_id_schema_accepts_entity_id() -> None: + """CHARGER_ID_SCHEMA accepts a bare entity_id and normalizes it to a list.""" + result = CHARGER_ID_SCHEMA({"entity_id": "sensor.foo"}) + assert result["entity_id"] == ["sensor.foo"] + + +def test_limit_current_schema_requires_current_value() -> None: + """LIMIT_CURRENT_SCHEMA rejects data with neither available_current nor all three phases.""" + with pytest.raises(vol.Invalid, match="Either 'available_current'"): + LIMIT_CURRENT_SCHEMA({"installation_id": "x"}) + + +def test_limit_current_schema_accepts_available_current() -> None: + """LIMIT_CURRENT_SCHEMA accepts a bare available_current.""" + result = LIMIT_CURRENT_SCHEMA({"installation_id": "x", "available_current": 16}) + assert result["available_current"] == 16 # noqa: PLR2004 + + +def test_limit_current_schema_accepts_all_three_phases() -> None: + """LIMIT_CURRENT_SCHEMA accepts all three phase fields together.""" + result = LIMIT_CURRENT_SCHEMA( + { + "installation_id": "x", + "available_current_phase1": 1, + "available_current_phase2": 2, + "available_current_phase3": 3, + } + ) + assert result["available_current_phase3"] == 3 # noqa: PLR2004 + + +def test_limit_current_schema_rejects_partial_phases() -> None: + """LIMIT_CURRENT_SCHEMA rejects only two of the three phase fields.""" + with pytest.raises(vol.Invalid, match="Either 'available_current'"): + LIMIT_CURRENT_SCHEMA( + { + "installation_id": "x", + "available_current_phase1": 1, + "available_current_phase2": 2, + } + ) + + +def test_limit_current_schema_rejects_current_and_phases_together() -> None: + """LIMIT_CURRENT_SCHEMA rejects mixing available_current with the phase fields.""" + with pytest.raises(vol.Invalid, match="Either 'available_current'"): + LIMIT_CURRENT_SCHEMA( + { + "installation_id": "x", + "available_current": 16, + "available_current_phase1": 1, + "available_current_phase2": 2, + "available_current_phase3": 3, + } + ) + + +def test_send_command_schema_accepts_string_and_int_commands() -> None: + """SEND_COMMAND_SCHEMA accepts both string and integer commands.""" + assert ( + SEND_COMMAND_SCHEMA({"charger_id": "x", "command": "StopChargingFinal"})["command"] + == "StopChargingFinal" + ) + assert SEND_COMMAND_SCHEMA({"charger_id": "x", "command": 5})["command"] == 5 # noqa: PLR2004 + + +def test_send_command_schema_requires_command() -> None: + """SEND_COMMAND_SCHEMA rejects data missing the command field.""" + with pytest.raises(vol.Invalid, match="required key not provided"): + SEND_COMMAND_SCHEMA({"charger_id": "x"}) + + +# --------------------------------------------------------------------------- +# services.yaml consistency +# --------------------------------------------------------------------------- + + +async def test_services_yaml_keys_match_registered_service_names( + hass: HomeAssistant, manager: ZaptecManager +) -> None: + """services.yaml documents exactly the services async_setup_services registers.""" + registered = set(hass.services.async_services()[DOMAIN]) + documented = set(yaml.safe_load(SERVICES_YAML_PATH.read_text())) + + assert documented == registered diff --git a/tests/zaptec/conftest.py b/tests/zaptec/conftest.py new file mode 100644 index 00000000..2b86570b --- /dev/null +++ b/tests/zaptec/conftest.py @@ -0,0 +1,37 @@ +"""Test configuration for the vendored Zaptec API client (tests/zaptec/*).""" + +import asyncio + +import pytest + +from custom_components.zaptec.zaptec.api import Zaptec + + +@pytest.fixture(scope="session") +def zaptec_constants() -> dict: + """Get latest constants from Zaptec API. + + Uses a self-contained event loop instead of `asyncio.run()`: under + pytest-hacc's `HassEventLoopPolicy`, `asyncio.run()` resets the thread's + event loop to `None` on exit, breaking later `asyncio_mode=auto` tests. + Saving/restoring the previous loop avoids clobbering that global state. + """ + + async def get_zaptec_constants() -> dict: + async with Zaptec("N/A", "N/A") as zaptec: + # the constants API endpoint does not require login + const: dict = await zaptec.request("constants") + return const + + try: + previous_loop = asyncio.get_event_loop() + except RuntimeError: + previous_loop = None + + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + return loop.run_until_complete(get_zaptec_constants()) + finally: + loop.close() + asyncio.set_event_loop(previous_loop)