diff --git a/CODEOWNERS b/CODEOWNERS index 5d5afe68e0d0..4ce90761f1f6 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -1225,6 +1225,8 @@ AGENTS.md @home-assistant/core /tests/components/melissa/ @kennedyshead /homeassistant/components/melnor/ @vanstinator /tests/components/melnor/ @vanstinator +/homeassistant/components/meraki/ @felixblang +/tests/components/meraki/ @felixblang /homeassistant/components/met/ @danielhiversen /tests/components/met/ @danielhiversen /homeassistant/components/met_eireann/ @DylanGore diff --git a/homeassistant/components/meraki/__init__.py b/homeassistant/components/meraki/__init__.py index ad9cf4abcaf2..74c5f25f5730 100644 --- a/homeassistant/components/meraki/__init__.py +++ b/homeassistant/components/meraki/__init__.py @@ -1 +1,40 @@ -"""The meraki component.""" +"""The Meraki integration.""" + +from contextlib import AsyncExitStack + +from homeassistant.const import CONF_API_KEY, EVENT_HOMEASSISTANT_STOP, Platform +from homeassistant.core import Event, HomeAssistant + +from .api import async_create_client +from .coordinator import MerakiConfigEntry, MerakiDataUpdateCoordinator + +PLATFORMS: list[Platform] = [Platform.DEVICE_TRACKER] + + +async def async_setup_entry(hass: HomeAssistant, entry: MerakiConfigEntry) -> None: + """Set up Meraki from a config entry.""" + # The client only closes its connections when used as a context manager. + stack = AsyncExitStack() + entry.async_on_unload(stack.aclose) + client = await stack.enter_async_context( + await async_create_client(hass, entry.data[CONF_API_KEY]) + ) + + # Config entries are not unloaded when Home Assistant stops. + async def _async_close(_: Event) -> None: + await stack.aclose() + + entry.async_on_unload( + hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_close) + ) + + coordinator = MerakiDataUpdateCoordinator(hass, entry, client) + await coordinator.async_config_entry_first_refresh() + entry.runtime_data = coordinator + + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + + +async def async_unload_entry(hass: HomeAssistant, entry: MerakiConfigEntry) -> None: + """Unload a config entry.""" + await hass.config_entries.async_unload_platforms_or_raise(entry, PLATFORMS) diff --git a/homeassistant/components/meraki/api.py b/homeassistant/components/meraki/api.py new file mode 100644 index 000000000000..684556b503b8 --- /dev/null +++ b/homeassistant/components/meraki/api.py @@ -0,0 +1,45 @@ +"""Create clients for the Meraki Dashboard API.""" + +from functools import partial + +from meraki import APIError +from meraki.aio import AsyncDashboardAPI + +from homeassistant.const import __version__ as HA_VERSION +from homeassistant.core import HomeAssistant + +# Meraki asks API callers to identify as "/ ". +CALLER = f"HomeAssistant/{HA_VERSION} HomeAssistant" + + +async def async_create_client(hass: HomeAssistant, api_key: str) -> AsyncDashboardAPI: + """Create a Dashboard API client.""" + # The library creates its own httpx client, which loads SSL certificates + # when it is created. That blocks, and the library takes no client from us. + return await hass.async_add_executor_job( + partial( + AsyncDashboardAPI, + # The library falls back to an environment variable without a key. + api_key=api_key, + caller=CALLER, + # Log through the "meraki" logger only, without the library's own + # log file in the working directory or console output. + inherit_logging_config=True, + output_log=False, + print_console=False, + # Smart flow writes a cache to the home directory. It also cannot map + # the networks of getOrganizationNetworks to their organization, so it + # would not throttle the client requests. + smart_flow_enabled=False, + # The library defaults (60 s timeout, 5 attempts, 60 s waits on 429) + # are too long for an update every minute. + single_request_timeout=10, + maximum_retries=2, + nginx_429_retry_wait_time=5, + ) + ) + + +def is_auth_error(err: APIError) -> bool: + """Return True if the API key is invalid or has no access.""" + return err.status in (401, 403) diff --git a/homeassistant/components/meraki/config_flow.py b/homeassistant/components/meraki/config_flow.py new file mode 100644 index 000000000000..bd6ce32e0bc5 --- /dev/null +++ b/homeassistant/components/meraki/config_flow.py @@ -0,0 +1,113 @@ +"""Config flow for the Meraki integration.""" + +import logging +from typing import Any, override + +from meraki import APIError +import probatio + +from homeassistant.config_entries import ConfigFlow, ConfigFlowResult +from homeassistant.const import CONF_API_KEY +from homeassistant.helpers.selector import ( + SelectOptionDict, + SelectSelector, + SelectSelectorConfig, + SelectSelectorMode, +) + +from .api import async_create_client, is_auth_error +from .const import CONF_ORGANIZATION_ID, DOMAIN + +_LOGGER = logging.getLogger(__name__) + +API_KEY_SCHEMA = probatio.Schema( + {probatio.Required(probatio.Secret(CONF_API_KEY)): str} +) + + +class MerakiConfigFlow(ConfigFlow, domain=DOMAIN): + """Handle a config flow for Meraki.""" + + VERSION = 1 + + def __init__(self) -> None: + """Initialize the flow.""" + self._api_key = "" + self._organizations: dict[str, str] = {} + + @override + async def async_step_user( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Ask for the API key.""" + errors: dict[str, str] = {} + if user_input is not None: + self._api_key = user_input[CONF_API_KEY] + errors = await self._async_fetch_organizations(self._api_key) + if not errors: + if len(self._organizations) == 1: + return await self._async_create_organization_entry( + next(iter(self._organizations)) + ) + return await self.async_step_organization() + + return self.async_show_form( + step_id="user", data_schema=API_KEY_SCHEMA, errors=errors + ) + + async def async_step_organization( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Let the user choose one of the organizations the API key can access.""" + if user_input is not None: + return await self._async_create_organization_entry( + user_input[CONF_ORGANIZATION_ID] + ) + + options = [ + SelectOptionDict(value=organization_id, label=name) + for organization_id, name in sorted( + self._organizations.items(), key=lambda item: item[1].lower() + ) + ] + return self.async_show_form( + step_id="organization", + data_schema=probatio.Schema( + { + probatio.Required(CONF_ORGANIZATION_ID): SelectSelector( + SelectSelectorConfig( + options=options, mode=SelectSelectorMode.DROPDOWN + ) + ) + } + ), + ) + + async def _async_create_organization_entry( + self, organization_id: str + ) -> ConfigFlowResult: + await self.async_set_unique_id(organization_id) + self._abort_if_unique_id_configured() + return self.async_create_entry( + title=self._organizations[organization_id], + data={CONF_API_KEY: self._api_key, CONF_ORGANIZATION_ID: organization_id}, + ) + + async def _async_fetch_organizations(self, api_key: str) -> dict[str, str]: + """Look up the organizations of an API key; return errors, if any.""" + try: + async with await async_create_client(self.hass, api_key) as client: + organizations = await client.organizations.getOrganizations( + total_pages="all" + ) + except APIError as err: + return {"base": "invalid_auth" if is_auth_error(err) else "cannot_connect"} + except Exception: + _LOGGER.exception("Unexpected exception") + return {"base": "unknown"} + if not organizations: + return {"base": "no_organizations"} + self._organizations = { + organization["id"]: organization["name"] for organization in organizations + } + return {} diff --git a/homeassistant/components/meraki/const.py b/homeassistant/components/meraki/const.py new file mode 100644 index 000000000000..d212800b11c9 --- /dev/null +++ b/homeassistant/components/meraki/const.py @@ -0,0 +1,5 @@ +"""Constants for the Meraki integration.""" + +DOMAIN = "meraki" + +CONF_ORGANIZATION_ID = "organization_id" diff --git a/homeassistant/components/meraki/coordinator.py b/homeassistant/components/meraki/coordinator.py new file mode 100644 index 000000000000..e195c9283e34 --- /dev/null +++ b/homeassistant/components/meraki/coordinator.py @@ -0,0 +1,181 @@ +"""Data update coordinator for the Meraki integration.""" + +import asyncio +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from datetime import datetime, timedelta +from functools import partial +import logging +from typing import Any, override + +from meraki import APIError +from meraki.aio import AsyncDashboardAPI + +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import ConfigEntryError +from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed +from homeassistant.util import dt as dt_util + +from .api import is_auth_error +from .const import CONF_ORGANIZATION_ID, DOMAIN + +_LOGGER = logging.getLogger(__name__) + +UPDATE_INTERVAL = timedelta(minutes=1) + +# A request can take 30 s with retries, and a 429 response can ask for a longer +# wait. This keeps an update shorter than the update interval. +UPDATE_TIMEOUT = 50 + +# Meraki allows 10 requests per second per organization. A request takes a few +# hundred milliseconds, so this many in parallel stays below that limit. +MAX_PARALLEL_REQUESTS = 3 + +# Clients seen in this window are returned, connected or not. +CLIENT_TIMESPAN = timedelta(hours=1) + +# Networks with these products have clients. +CLIENT_PRODUCT_TYPES = frozenset({"appliance", "cellularGateway", "switch", "wireless"}) + +type MerakiConfigEntry = ConfigEntry[MerakiDataUpdateCoordinator] + + +@dataclass(frozen=True, kw_only=True) +class MerakiClient: + """A Wi-Fi or wired client of a Meraki network.""" + + mac: str + network_id: str + description: str | None + ip: str | None + online: bool + last_seen: datetime + + +@dataclass(frozen=True, kw_only=True) +class MerakiData: + """The clients of a Meraki organization, by MAC address.""" + + clients: dict[str, MerakiClient] + + +class MerakiDataUpdateCoordinator(DataUpdateCoordinator[MerakiData]): + """Poll the clients of a Meraki organization's networks.""" + + config_entry: MerakiConfigEntry + + def __init__( + self, + hass: HomeAssistant, + config_entry: MerakiConfigEntry, + client: AsyncDashboardAPI, + ) -> None: + """Initialize the coordinator.""" + super().__init__( + hass, + _LOGGER, + config_entry=config_entry, + name=DOMAIN, + update_interval=UPDATE_INTERVAL, + ) + self.client = client + self.organization_id: str = config_entry.data[CONF_ORGANIZATION_ID] + self._request_limit = asyncio.Semaphore(MAX_PARALLEL_REQUESTS) + + @override + async def _async_update_data(self) -> MerakiData: + """Fetch the clients of all networks of the organization.""" + try: + async with asyncio.timeout(UPDATE_TIMEOUT): + return await self._async_fetch_clients() + except TimeoutError as err: + raise UpdateFailed( + translation_domain=DOMAIN, translation_key="update_timeout" + ) from err + + async def _async_fetch_clients(self) -> MerakiData: + networks = await self._async_call( + partial( + self.client.organizations.getOrganizationNetworks, + self.organization_id, + total_pages="all", + ) + ) + client_networks = [ + network["id"] + for network in networks + if CLIENT_PRODUCT_TYPES.intersection(network["productTypes"]) + ] + timespan = int(CLIENT_TIMESPAN.total_seconds()) + # Let every request finish before raising, as they share the client. + results = await asyncio.gather( + *( + self._async_call( + partial( + self.client.networks.getNetworkClients, + network_id, + total_pages="all", + perPage=5000, + timespan=timespan, + ) + ) + for network_id in client_networks + ), + return_exceptions=True, + ) + client_lists: list[list[dict[str, Any]]] = [] + for result in results: + if isinstance(result, BaseException): + raise result + client_lists.append(result) + clients: dict[str, MerakiClient] = {} + for network_id, items in zip(client_networks, client_lists, strict=True): + for item in items: + client = _parse_client(network_id, item) + # A client that moved between networks is listed in both. + if (known := clients.get(client.mac)) is None or _is_more_recent( + client, known + ): + clients[client.mac] = client + + return MerakiData(clients=clients) + + async def _async_call[_T](self, request: Callable[[], Awaitable[_T]]) -> _T: + """Send an API request and translate its errors.""" + try: + async with self._request_limit: + return await request() + except APIError as err: + if is_auth_error(err): + raise ConfigEntryError( + translation_domain=DOMAIN, translation_key="invalid_auth" + ) from err + raise UpdateFailed( + translation_domain=DOMAIN, + translation_key="update_failed", + translation_placeholders={"error": str(err)}, + ) from err + + +def _parse_client(network_id: str, item: dict[str, Any]) -> MerakiClient: + last_seen = item["lastSeen"] + return MerakiClient( + mac=item["mac"], + network_id=network_id, + description=item["description"], + ip=item["ip"], + online=item["status"] == "Online", + # Meraki documents lastSeen as a Unix timestamp, but the API returned ISO + # strings for every client during testing; both are accepted. + last_seen=( + dt_util.utc_from_timestamp(last_seen) + if isinstance(last_seen, int | float) + else dt_util.parse_datetime(last_seen, raise_on_error=True) + ), + ) + + +def _is_more_recent(client: MerakiClient, other: MerakiClient) -> bool: + """Return True if client is the more recent sighting of the same MAC.""" + return (client.online, client.last_seen) > (other.online, other.last_seen) diff --git a/homeassistant/components/meraki/device_tracker.py b/homeassistant/components/meraki/device_tracker.py index 5b8ac5e269c6..1ef14cb79847 100644 --- a/homeassistant/components/meraki/device_tracker.py +++ b/homeassistant/components/meraki/device_tracker.py @@ -1,21 +1,35 @@ -"""Support for the Meraki CMX location service.""" +"""Device trackers for the clients of Meraki networks.""" from http import HTTPStatus import json import logging +from typing import override import probatio from homeassistant.components.device_tracker import ( PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, AsyncSeeCallback, + ScannerEntity, SourceType, ) from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.core import HomeAssistant, callback -from homeassistant.helpers import config_validation as cv +from homeassistant.helpers import ( + config_validation as cv, + entity_registry as er, + issue_registry as ir, +) +from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType +from .const import DOMAIN +from .coordinator import MerakiConfigEntry, MerakiDataUpdateCoordinator +from .entity import MerakiEntity + +PARALLEL_UPDATES = 0 + CONF_VALIDATOR = "validator" CONF_SECRET = "secret" URL = "/api/meraki" @@ -40,6 +54,16 @@ async def async_setup_scanner( discovery_info: DiscoveryInfoType | None = None, ) -> bool: """Set up an endpoint for the Meraki tracker.""" + ir.async_create_issue( + hass, + DOMAIN, + "deprecated_cmx", + breaks_in_ha_version="2027.5.0", + is_fixable=False, + severity=ir.IssueSeverity.WARNING, + translation_key="deprecated_cmx", + learn_more_url="https://www.home-assistant.io/integrations/meraki", + ) hass.http.register_view(MerakiView(config, async_see)) return True @@ -135,3 +159,91 @@ class MerakiView(HomeAssistantView): attributes=attrs, ) ) + + +async def async_setup_entry( + hass: HomeAssistant, + entry: MerakiConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Set up trackers for the clients of the organization's networks.""" + coordinator = entry.runtime_data + org_id = coordinator.organization_id + + # The API forgets clients after an hour; their trackers stay, as away. + registry_entries = er.async_entries_for_config_entry( + er.async_get(hass), entry.entry_id + ) + tracked = {registry_entry.unique_id for registry_entry in registry_entries} + async_add_entities( + MerakiClientTracker( + coordinator, + registry_entry.unique_id.removeprefix(f"{org_id}_"), + None, + ) + for registry_entry in registry_entries + ) + + @callback + def _async_add_new_clients() -> None: + new: list[MerakiClientTracker] = [] + for mac, client in coordinator.data.clients.items(): + if (unique_id := _unique_id(org_id, mac)) not in tracked: + tracked.add(unique_id) + new.append( + MerakiClientTracker(coordinator, mac, client.description or mac) + ) + async_add_entities(new) + + _async_add_new_clients() + entry.async_on_unload(coordinator.async_add_listener(_async_add_new_clients)) + + +def _unique_id(org_id: str, mac: str) -> str: + # The same device can be a client in several organizations. + return f"{org_id}_{mac}" + + +class MerakiClientTracker(MerakiEntity, ScannerEntity): + """A Wi-Fi or wired client, home while it is connected to the network.""" + + _attr_has_entity_name = True + _attr_name = None + + def __init__( + self, coordinator: MerakiDataUpdateCoordinator, mac: str, name: str | None + ) -> None: + """Initialize the tracker, naming its device if the name is known.""" + super().__init__(coordinator) + self.mac = mac + self._attr_mac_address = mac + self._attr_device_info = DeviceInfo(connections={(CONNECTION_NETWORK_MAC, mac)}) + # Restored trackers keep the name their device already has. + if name is not None: + self._attr_device_info["name"] = name + self._async_update_attrs() + + @property + @override + def unique_id(self) -> str: + """Return the MAC, scoped to the organization.""" + return _unique_id(self.coordinator.organization_id, self.mac) + + @property + @override + def is_connected(self) -> bool: + """Return True if Meraki reports the client as online.""" + client = self.coordinator.data.clients.get(self.mac) + return client is not None and client.online + + @callback + @override + def _handle_coordinator_update(self) -> None: + self._async_update_attrs() + super()._handle_coordinator_update() + + @callback + def _async_update_attrs(self) -> None: + if client := self.coordinator.data.clients.get(self.mac): + self._attr_hostname = client.description + self._attr_ip_address = client.ip diff --git a/homeassistant/components/meraki/entity.py b/homeassistant/components/meraki/entity.py new file mode 100644 index 000000000000..307f98bde779 --- /dev/null +++ b/homeassistant/components/meraki/entity.py @@ -0,0 +1,9 @@ +"""Base entity for the Meraki integration.""" + +from homeassistant.helpers.update_coordinator import CoordinatorEntity + +from .coordinator import MerakiDataUpdateCoordinator + + +class MerakiEntity(CoordinatorEntity[MerakiDataUpdateCoordinator]): + """An entity updated by the Meraki coordinator.""" diff --git a/homeassistant/components/meraki/manifest.json b/homeassistant/components/meraki/manifest.json index 3329a4987624..39fbacbbaaab 100644 --- a/homeassistant/components/meraki/manifest.json +++ b/homeassistant/components/meraki/manifest.json @@ -5,10 +5,13 @@ "presence_location.network_presence", "computers_network.routers_network" ], - "codeowners": [], - "connectivity": ["cloud"], + "codeowners": ["@felixblang"], + "config_flow": true, "dependencies": ["http"], "documentation": "https://www.home-assistant.io/integrations/meraki", + "integration_type": "hub", "iot_class": "cloud_polling", - "quality_scale": "legacy" + "loggers": ["meraki"], + "quality_scale": "legacy", + "requirements": ["meraki==4.7.0"] } diff --git a/homeassistant/components/meraki/strings.json b/homeassistant/components/meraki/strings.json new file mode 100644 index 000000000000..55b237258667 --- /dev/null +++ b/homeassistant/components/meraki/strings.json @@ -0,0 +1,49 @@ +{ + "config": { + "abort": { + "already_configured": "[%key:common::config_flow::abort::already_configured_account%]" + }, + "error": { + "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", + "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", + "no_organizations": "The API key does not have access to any organization.", + "unknown": "[%key:common::config_flow::error::unknown%]" + }, + "step": { + "organization": { + "data": { + "organization_id": "Organization" + }, + "data_description": { + "organization_id": "The Meraki organization to add. Add the integration again for other organizations." + }, + "description": "The API key has access to several organizations." + }, + "user": { + "data": { + "api_key": "[%key:common::config_flow::data::api_key%]" + }, + "data_description": { + "api_key": "A Meraki Dashboard API key, created under Organization > API & Webhooks in the Meraki Dashboard." + } + } + } + }, + "exceptions": { + "invalid_auth": { + "message": "The Meraki API key is invalid or no longer has access to the organization." + }, + "update_failed": { + "message": "Error communicating with the Meraki Dashboard API: {error}" + }, + "update_timeout": { + "message": "Fetching the clients from the Meraki Dashboard API took too long." + } + }, + "issues": { + "deprecated_cmx": { + "description": "Setting up Meraki presence detection with the CMX location service in YAML is deprecated and will stop working. To switch to the Meraki integration:\n\n1. Remove the `meraki` platform from the `device_tracker` section of your `configuration.yaml` file, and the devices it tracked from your `known_devices.yaml` file.\n2. Restart Home Assistant.\n3. Add the Meraki integration in the UI with a Meraki Dashboard API key.\n4. Enable the trackers of the devices you want to follow, as they start disabled, and update automations and scripts that used the old trackers.\n\nThe integration tracks whether Wi-Fi and wired clients are connected, without their position on the map. Bluetooth devices are not tracked yet.", + "title": "Meraki presence detection with the CMX location service is being removed" + } + } +} diff --git a/homeassistant/generated/config_flows.py b/homeassistant/generated/config_flows.py index 9140298190aa..1a586a896f12 100644 --- a/homeassistant/generated/config_flows.py +++ b/homeassistant/generated/config_flows.py @@ -514,6 +514,7 @@ FLOWS = { "melcloud", "melcloud_home", "melnor", + "meraki", "met", "met_eireann", "meteo_france", diff --git a/homeassistant/generated/integrations.json b/homeassistant/generated/integrations.json index d9398fa9ad32..c16f5a80c5a4 100644 --- a/homeassistant/generated/integrations.json +++ b/homeassistant/generated/integrations.json @@ -2337,15 +2337,12 @@ }, "meraki": { "integration_type": "hub", - "config_flow": false, + "config_flow": true, "iot_class": "cloud_polling", "categories": [ "presence_location.network_presence", "computers_network.routers_network" ], - "connectivity": [ - "cloud" - ], "name": "Meraki" } } diff --git a/requirements_all.txt b/requirements_all.txt index 2f74b48a66b1..f95bf8d5d4cf 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1666,6 +1666,9 @@ medcom-ble==0.1.1 # homeassistant.components.melnor melnor-bluetooth==0.0.25 +# homeassistant.components.meraki +meraki==4.7.0 + # homeassistant.components.message_bird messagebird==1.2.1 diff --git a/tests/components/meraki/__init__.py b/tests/components/meraki/__init__.py index e0ab288f4667..69185a1d9c37 100644 --- a/tests/components/meraki/__init__.py +++ b/tests/components/meraki/__init__.py @@ -1 +1,22 @@ -"""Tests for the meraki component.""" +"""Tests for the Meraki integration.""" + +from unittest.mock import MagicMock + +from meraki import APIError +from pytest_homeassistant.common import MockConfigEntry + +from homeassistant.core import HomeAssistant + + +async def setup_integration(hass: HomeAssistant, config_entry: MockConfigEntry) -> None: + """Set up the Meraki integration.""" + config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + +def api_error(status: int) -> APIError: + """Return an error like the Meraki library raises it.""" + response = MagicMock(status_code=status, reason_phrase="Error") + response.json.return_value = {"errors": ["Error"]} + return APIError({"tags": ["organizations"], "operation": "test"}, response) diff --git a/tests/components/meraki/conftest.py b/tests/components/meraki/conftest.py new file mode 100644 index 000000000000..3050583d0d11 --- /dev/null +++ b/tests/components/meraki/conftest.py @@ -0,0 +1,55 @@ +"""Fixtures for the Meraki tests.""" + +from collections.abc import Generator +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from pytest_homeassistant.common import MockConfigEntry, load_json_array_fixture + +from homeassistant.components.meraki.const import CONF_ORGANIZATION_ID, DOMAIN +from homeassistant.const import CONF_API_KEY + +API_KEY = "0123456789abcdef" +ORGANIZATION_ID = "123456" + + +@pytest.fixture +def mock_setup_entry() -> Generator[AsyncMock]: + """Override async_setup_entry.""" + with patch( + "homeassistant.components.meraki.async_setup_entry", return_value=None + ) as mock_setup_entry: + yield mock_setup_entry + + +@pytest.fixture +def mock_config_entry() -> MockConfigEntry: + """Return a config entry for the test organization.""" + return MockConfigEntry( + domain=DOMAIN, + title="Home Lab", + unique_id=ORGANIZATION_ID, + data={CONF_API_KEY: API_KEY, CONF_ORGANIZATION_ID: ORGANIZATION_ID}, + ) + + +@pytest.fixture +def mock_meraki_client() -> Generator[MagicMock]: + """Mock the Meraki Dashboard API client.""" + with patch( + "homeassistant.components.meraki.api.AsyncDashboardAPI", autospec=True + ) as mock_client: + client = mock_client.return_value + client.__aenter__.return_value = client + organizations = client.organizations = MagicMock() + organizations.getOrganizations = AsyncMock( + return_value=load_json_array_fixture("organizations.json", DOMAIN) + ) + organizations.getOrganizationNetworks = AsyncMock( + return_value=load_json_array_fixture("networks.json", DOMAIN) + ) + networks = client.networks = MagicMock() + networks.getNetworkClients = AsyncMock( + return_value=load_json_array_fixture("clients.json", DOMAIN) + ) + yield client diff --git a/tests/components/meraki/fixtures/clients.json b/tests/components/meraki/fixtures/clients.json new file mode 100644 index 000000000000..a1ac9db849e0 --- /dev/null +++ b/tests/components/meraki/fixtures/clients.json @@ -0,0 +1,56 @@ +[ + { + "id": "k111111", + "mac": "aa:bb:cc:00:00:01", + "description": "Pixel 9", + "ip": "192.168.1.20", + "ip6": null, + "firstSeen": "2026-04-29T10:10:49Z", + "lastSeen": "2026-10-20T20:59:00Z", + "manufacturer": "Google", + "os": "Android", + "recentDeviceSerial": "Q2AA-AAAA-AAAA", + "recentDeviceName": "Office AP", + "recentDeviceConnection": "Wireless", + "ssid": "Home", + "vlan": "10", + "switchport": null, + "status": "Online" + }, + { + "id": "k222222", + "mac": "aa:bb:cc:00:00:02", + "description": "NAS", + "ip": "192.168.1.30", + "ip6": null, + "firstSeen": "2026-05-14T17:03:39Z", + "lastSeen": "2026-10-20T20:59:30Z", + "manufacturer": "Synology", + "os": null, + "recentDeviceSerial": "Q2BB-BBBB-BBBB", + "recentDeviceName": "Office switch", + "recentDeviceConnection": "Wired", + "ssid": null, + "vlan": "20", + "switchport": "4", + "status": "Online" + }, + { + "id": "k333333", + "mac": "aa:bb:cc:00:00:03", + "description": null, + "ip": "192.168.1.40", + "ip6": null, + "firstSeen": "2026-10-01T08:00:00Z", + "lastSeen": "2026-10-20T20:15:00Z", + "manufacturer": "Apple", + "os": null, + "recentDeviceSerial": "Q2AA-AAAA-AAAA", + "recentDeviceName": "Office AP", + "recentDeviceConnection": "Wireless", + "ssid": "Home", + "vlan": "10", + "switchport": null, + "status": "Offline" + } +] diff --git a/tests/components/meraki/fixtures/networks.json b/tests/components/meraki/fixtures/networks.json new file mode 100644 index 000000000000..c78a56918ef0 --- /dev/null +++ b/tests/components/meraki/fixtures/networks.json @@ -0,0 +1,14 @@ +[ + { + "id": "L_111", + "organizationId": "123456", + "name": "Home", + "productTypes": ["appliance", "switch", "wireless"] + }, + { + "id": "L_222", + "organizationId": "123456", + "name": "Cameras", + "productTypes": ["camera"] + } +] diff --git a/tests/components/meraki/fixtures/organizations.json b/tests/components/meraki/fixtures/organizations.json new file mode 100644 index 000000000000..d4922b9da74b --- /dev/null +++ b/tests/components/meraki/fixtures/organizations.json @@ -0,0 +1 @@ +[{ "id": "123456", "name": "Home Lab" }] diff --git a/tests/components/meraki/snapshots/test_device_tracker.ambr b/tests/components/meraki/snapshots/test_device_tracker.ambr new file mode 100644 index 000000000000..606a845f3983 --- /dev/null +++ b/tests/components/meraki/snapshots/test_device_tracker.ambr @@ -0,0 +1,179 @@ +# serializer version: 1 +# name: test_trackers[device_tracker.aa_bb_cc_00_00_03-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : , + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'device_tracker', + 'entity_category': , + 'entity_id': 'device_tracker.aa_bb_cc_00_00_03', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': None, + 'platform': 'meraki', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': None, + 'unique_id': '123456_aa:bb:cc:00:00:03', + 'unit_of_measurement': None, + }) +# --- +# name: test_trackers[device_tracker.aa_bb_cc_00_00_03-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'aa:bb:cc:00:00:03', + : list([ + ]), + : '192.168.1.40', + : 'aa:bb:cc:00:00:03', + : , + : , + }), + 'context': , + 'entity_id': 'device_tracker.aa_bb_cc_00_00_03', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'not_home', + }) +# --- +# name: test_trackers[device_tracker.nas-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : , + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'device_tracker', + 'entity_category': , + 'entity_id': 'device_tracker.nas', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': None, + 'platform': 'meraki', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': None, + 'unique_id': '123456_aa:bb:cc:00:00:02', + 'unit_of_measurement': None, + }) +# --- +# name: test_trackers[device_tracker.nas-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'NAS', + : 'NAS', + : list([ + 'zone.home', + ]), + : '192.168.1.30', + : 'aa:bb:cc:00:00:02', + : , + : , + }), + 'context': , + 'entity_id': 'device_tracker.nas', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'home', + }) +# --- +# name: test_trackers[device_tracker.pixel_9-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : , + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'device_tracker', + 'entity_category': , + 'entity_id': 'device_tracker.pixel_9', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': None, + 'platform': 'meraki', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': None, + 'unique_id': '123456_aa:bb:cc:00:00:01', + 'unit_of_measurement': None, + }) +# --- +# name: test_trackers[device_tracker.pixel_9-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Pixel 9', + : 'Pixel 9', + : list([ + 'zone.home', + ]), + : '192.168.1.20', + : 'aa:bb:cc:00:00:01', + : , + : , + }), + 'context': , + 'entity_id': 'device_tracker.pixel_9', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'home', + }) +# --- diff --git a/tests/components/meraki/test_config_flow.py b/tests/components/meraki/test_config_flow.py new file mode 100644 index 000000000000..ee7bfee7b732 --- /dev/null +++ b/tests/components/meraki/test_config_flow.py @@ -0,0 +1,117 @@ +"""Tests for the Meraki config flow.""" + +from unittest.mock import AsyncMock, MagicMock + +import pytest +from pytest_homeassistant.common import MockConfigEntry + +from homeassistant.components.meraki.const import CONF_ORGANIZATION_ID, DOMAIN +from homeassistant.config_entries import SOURCE_USER +from homeassistant.const import CONF_API_KEY +from homeassistant.core import HomeAssistant +from homeassistant.data_entry_flow import FlowResultType + +from . import api_error +from .conftest import API_KEY, ORGANIZATION_ID + + +@pytest.mark.usefixtures("mock_setup_entry", "mock_meraki_client") +async def test_full_flow(hass: HomeAssistant) -> None: + """Test an API key with one organization.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: API_KEY} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == "Home Lab" + assert result["data"] == { + CONF_API_KEY: API_KEY, + CONF_ORGANIZATION_ID: ORGANIZATION_ID, + } + assert result["result"].unique_id == ORGANIZATION_ID + + +@pytest.mark.usefixtures("mock_setup_entry") +async def test_multiple_organizations( + hass: HomeAssistant, mock_meraki_client: MagicMock +) -> None: + """Test choosing one of several organizations.""" + mock_meraki_client.organizations.getOrganizations.return_value = [ + {"id": ORGANIZATION_ID, "name": "Home Lab"}, + {"id": "999", "name": "Office"}, + ] + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: API_KEY} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "organization" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_ORGANIZATION_ID: "999"} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == "Office" + assert result["result"].unique_id == "999" + + +@pytest.mark.usefixtures("mock_setup_entry") +@pytest.mark.parametrize( + ("side_effect", "return_value", "error"), + [ + pytest.param(api_error(401), None, "invalid_auth", id="invalid_auth"), + pytest.param(api_error(503), None, "cannot_connect", id="cannot_connect"), + pytest.param(RuntimeError, None, "unknown", id="unknown"), + pytest.param(None, [], "no_organizations", id="no_organizations"), + ], +) +async def test_user_errors( + hass: HomeAssistant, + mock_meraki_client: MagicMock, + side_effect: Exception | type[Exception] | None, + return_value: list | None, + error: str, +) -> None: + """Test errors are shown and the flow can recover.""" + get_organizations: AsyncMock = mock_meraki_client.organizations.getOrganizations + original = get_organizations.return_value + get_organizations.side_effect = side_effect + get_organizations.return_value = return_value + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: API_KEY} + ) + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": error} + + get_organizations.side_effect = None + get_organizations.return_value = original + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: API_KEY} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + + +@pytest.mark.usefixtures("mock_meraki_client") +async def test_already_configured( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test an organization can only be added once.""" + mock_config_entry.add_to_hass(hass) + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: API_KEY} + ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" diff --git a/tests/components/meraki/test_device_tracker.py b/tests/components/meraki/test_device_tracker.py index 5c28f4dadbbd..f6b1f12a0805 100644 --- a/tests/components/meraki/test_device_tracker.py +++ b/tests/components/meraki/test_device_tracker.py @@ -2,22 +2,55 @@ from http import HTTPStatus import json +from unittest.mock import MagicMock from aiohttp.test_utils import TestClient +from freezegun.api import FrozenDateTimeFactory import pytest +from pytest_homeassistant.common import ( + MockConfigEntry, + async_fire_time_changed, + async_load_json_array_fixture, + snapshot_platform, +) from pytest_homeassistant.typing import ClientSessionGenerator +from syrupy.assertion import SnapshotAssertion from homeassistant.components import device_tracker from homeassistant.components.device_tracker import legacy +from homeassistant.components.meraki.const import CONF_ORGANIZATION_ID, DOMAIN +from homeassistant.components.meraki.coordinator import UPDATE_INTERVAL from homeassistant.components.meraki.device_tracker import ( CONF_SECRET, CONF_VALIDATOR, URL, ) -from homeassistant.const import CONF_PLATFORM +from homeassistant.const import ( + CONF_PLATFORM, + STATE_HOME, + STATE_NOT_HOME, + STATE_UNAVAILABLE, +) from homeassistant.core import HomeAssistant +from homeassistant.helpers import ( + device_registry as dr, + entity_registry as er, + issue_registry as ir, +) from homeassistant.setup import async_setup_component +from . import api_error, setup_integration +from .conftest import ORGANIZATION_ID + +PHONE = "device_tracker.pixel_9" + + +async def _async_poll(hass: HomeAssistant, freezer: FrozenDateTimeFactory) -> None: + """Let the coordinator poll the API again.""" + freezer.tick(UPDATE_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + @pytest.fixture async def meraki_client( @@ -41,6 +74,13 @@ async def meraki_client( return await hass_client() +@pytest.mark.usefixtures("meraki_client") +async def test_cmx_deprecated(issue_registry: ir.IssueRegistry) -> None: + """Test setting up the CMX location service in YAML raises a repair issue.""" + issue = issue_registry.async_get_issue(DOMAIN, "deprecated_cmx") + assert issue.breaks_in_ha_version == "2027.5.0" + + async def test_invalid_or_missing_data( mock_device_tracker_conf: list[legacy.Device], meraki_client ) -> None: @@ -139,3 +179,177 @@ async def test_data_will_be_saved( state_name = hass.states.get("device_tracker.00_26_ab_b8_a9_a5").state assert state_name == "home" + + +@pytest.mark.freeze_time("2026-10-20 21:00:00+00:00") +@pytest.mark.usefixtures("entity_registry_enabled_by_default", "mock_meraki_client") +async def test_trackers( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + entity_registry: er.EntityRegistry, + snapshot: SnapshotAssertion, +) -> None: + """Test the trackers of the clients.""" + await setup_integration(hass, mock_config_entry) + await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.freeze_time("2026-10-20 21:00:00+00:00") +@pytest.mark.usefixtures("mock_meraki_client") +async def test_trackers_disabled_by_default( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + entity_registry: er.EntityRegistry, + device_registry: dr.DeviceRegistry, +) -> None: + """Test trackers start disabled, with their own device, even for known MACs.""" + other_entry = MockConfigEntry(domain="other") + other_entry.add_to_hass(hass) + other_device = device_registry.async_get_or_create( + config_entry_id=other_entry.entry_id, + connections={(dr.CONNECTION_NETWORK_MAC, "aa:bb:cc:00:00:01")}, + ) + await setup_integration(hass, mock_config_entry) + + phone = entity_registry.async_get(PHONE) + assert phone.disabled_by is er.RegistryEntryDisabler.INTEGRATION + assert phone.device_id != other_device.id + device = device_registry.async_get(phone.device_id) + assert device.config_entry_id == mock_config_entry.entry_id + assert device.connections == {(dr.CONNECTION_NETWORK_MAC, "aa:bb:cc:00:00:01")} + assert device.name == "Pixel 9" + + +@pytest.mark.freeze_time("2026-10-20 21:00:00+00:00") +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_client_leaves( + hass: HomeAssistant, + mock_meraki_client: MagicMock, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, +) -> None: + """Test clients are away when offline or no longer listed.""" + await setup_integration(hass, mock_config_entry) + assert hass.states.get(PHONE).state == STATE_HOME + + clients = await async_load_json_array_fixture(hass, "clients.json", DOMAIN) + clients[0]["status"] = "Offline" + mock_meraki_client.networks.getNetworkClients.return_value = clients + await _async_poll(hass, freezer) + assert hass.states.get(PHONE).state == STATE_NOT_HOME + + # After an hour without connecting, the API stops listing a client. + mock_meraki_client.networks.getNetworkClients.return_value = clients[1:] + await _async_poll(hass, freezer) + assert hass.states.get(PHONE).state == STATE_NOT_HOME + + +@pytest.mark.freeze_time("2026-10-20 21:00:00+00:00") +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_new_client( + hass: HomeAssistant, + mock_meraki_client: MagicMock, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, +) -> None: + """Test clients that connect later get a tracker.""" + await setup_integration(hass, mock_config_entry) + clients = await async_load_json_array_fixture(hass, "clients.json", DOMAIN) + new_client = {**clients[0], "mac": "aa:bb:cc:00:00:04", "description": "Tablet"} + mock_meraki_client.networks.getNetworkClients.return_value = [*clients, new_client] + await _async_poll(hass, freezer) + assert hass.states.get("device_tracker.tablet").state == STATE_HOME + + +@pytest.mark.freeze_time("2026-10-20 21:00:00+00:00") +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_restore_unlisted_clients( + hass: HomeAssistant, + mock_meraki_client: MagicMock, + mock_config_entry: MockConfigEntry, + entity_registry: er.EntityRegistry, + device_registry: dr.DeviceRegistry, +) -> None: + """Test trackers of clients the API no longer lists are away after a restart.""" + await setup_integration(hass, mock_config_entry) + await hass.config_entries.async_unload(mock_config_entry.entry_id) + + mock_meraki_client.networks.getNetworkClients.return_value = [] + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + assert hass.states.get(PHONE).state == STATE_NOT_HOME + # Without the API's name, the device keeps the one it had. + device = device_registry.async_get(entity_registry.async_get(PHONE).device_id) + assert device.name == "Pixel 9" + + +@pytest.mark.freeze_time("2026-10-20 21:00:00+00:00") +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_client_in_several_networks( + hass: HomeAssistant, + mock_meraki_client: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test a client listed in two networks is home where it is online.""" + networks = await async_load_json_array_fixture(hass, "networks.json", DOMAIN) + networks[1]["productTypes"] = ["wireless"] + mock_meraki_client.organizations.getOrganizationNetworks.return_value = networks + clients = await async_load_json_array_fixture(hass, "clients.json", DOMAIN) + # Meraki documents lastSeen as a Unix timestamp; the fixture has the ISO + # strings the API actually returns. 1792528200 is 2026-10-20 20:30 UTC. + elsewhere = [ + {**client, "status": "Offline", "ip": "10.0.0.1", "lastSeen": 1792528200} + for client in clients + ] + mock_meraki_client.networks.getNetworkClients.side_effect = [clients, elsewhere] + await setup_integration(hass, mock_config_entry) + + phone = hass.states.get(PHONE) + assert phone.state == STATE_HOME + assert phone.attributes["ip"] == "192.168.1.20" + # Offline in both, the more recent sighting (20:30 rather than 20:15) wins. + laptop = hass.states.get("device_tracker.aa_bb_cc_00_00_03") + assert laptop.attributes["ip"] == "10.0.0.1" + + +@pytest.mark.freeze_time("2026-10-20 21:00:00+00:00") +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_update_failed( + hass: HomeAssistant, + mock_meraki_client: MagicMock, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, +) -> None: + """Test trackers become unavailable when the API fails.""" + await setup_integration(hass, mock_config_entry) + mock_meraki_client.networks.getNetworkClients.side_effect = api_error(503) + await _async_poll(hass, freezer) + assert hass.states.get(PHONE).state == STATE_UNAVAILABLE + + +@pytest.mark.freeze_time("2026-10-20 21:00:00+00:00") +@pytest.mark.usefixtures("entity_registry_enabled_by_default", "mock_meraki_client") +async def test_client_in_several_organizations( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + entity_registry: er.EntityRegistry, +) -> None: + """Test a device in two organizations is tracked in each.""" + other_entry = MockConfigEntry( + domain=DOMAIN, + title="Office", + unique_id="654321", + data={**mock_config_entry.data, CONF_ORGANIZATION_ID: "654321"}, + ) + await setup_integration(hass, mock_config_entry) + await setup_integration(hass, other_entry) + + first = entity_registry.async_get_entity_id( + "device_tracker", DOMAIN, f"{ORGANIZATION_ID}_aa:bb:cc:00:00:01" + ) + second = entity_registry.async_get_entity_id( + "device_tracker", DOMAIN, "654321_aa:bb:cc:00:00:01" + ) + assert first == PHONE + assert second == f"{PHONE}_2" + assert hass.states.get(second).state == STATE_HOME diff --git a/tests/components/meraki/test_init.py b/tests/components/meraki/test_init.py new file mode 100644 index 000000000000..6f5ca136c0da --- /dev/null +++ b/tests/components/meraki/test_init.py @@ -0,0 +1,193 @@ +"""Tests for setting up the Meraki integration.""" + +import asyncio +import logging +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch + +from meraki.aio import AsyncDashboardAPI +from meraki.aio.api.networks import AsyncNetworks +from meraki.aio.api.organizations import AsyncOrganizations +import pytest +from pytest_homeassistant.common import MockConfigEntry, async_load_json_array_fixture + +from homeassistant.components.meraki.const import DOMAIN +from homeassistant.components.meraki.coordinator import MAX_PARALLEL_REQUESTS +from homeassistant.config_entries import ConfigEntryState +from homeassistant.const import EVENT_HOMEASSISTANT_STOP +from homeassistant.core import HomeAssistant + +from . import api_error, setup_integration + + +async def test_load_unload( + hass: HomeAssistant, + mock_meraki_client: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test the client is closed when the entry is unloaded.""" + await setup_integration(hass, mock_config_entry) + assert mock_config_entry.state is ConfigEntryState.LOADED + + await hass.config_entries.async_unload(mock_config_entry.entry_id) + assert mock_config_entry.state is ConfigEntryState.NOT_LOADED + mock_meraki_client.__aexit__.assert_awaited_once() + + +async def test_client_closed_on_stop( + hass: HomeAssistant, + mock_meraki_client: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test the client is closed when Home Assistant stops.""" + await setup_integration(hass, mock_config_entry) + + hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) + await hass.async_block_till_done() + mock_meraki_client.__aexit__.assert_awaited_once() + + +@pytest.mark.parametrize( + ("status", "state"), + [ + pytest.param(401, ConfigEntryState.SETUP_ERROR, id="invalid_auth"), + pytest.param(503, ConfigEntryState.SETUP_RETRY, id="cannot_connect"), + ], +) +async def test_setup_errors( + hass: HomeAssistant, + mock_meraki_client: MagicMock, + mock_config_entry: MockConfigEntry, + status: int, + state: ConfigEntryState, +) -> None: + """Test API errors during setup.""" + mock_meraki_client.organizations.getOrganizationNetworks.side_effect = api_error( + status + ) + await setup_integration(hass, mock_config_entry) + assert mock_config_entry.state is state + + +async def test_setup_timeout( + hass: HomeAssistant, + mock_meraki_client: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test setup is retried when the update takes too long.""" + + async def _never_returns(*args: Any, **kwargs: Any) -> list[dict[str, Any]]: + await asyncio.Event().wait() + return [] + + mock_meraki_client.networks.getNetworkClients.side_effect = _never_returns + with patch("homeassistant.components.meraki.coordinator.UPDATE_TIMEOUT", 0): + await setup_integration(hass, mock_config_entry) + assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY + + +async def test_all_requests_finish_before_failing( + hass: HomeAssistant, + mock_meraki_client: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test the client is only closed once every network's request finished.""" + networks = await async_load_json_array_fixture(hass, "networks.json", DOMAIN) + networks[1]["productTypes"] = ["wireless"] + mock_meraki_client.organizations.getOrganizationNetworks.return_value = networks + first_failing = asyncio.Event() + running: set[str] = set() + + async def _get_clients(network_id: str, **kwargs: Any) -> list[dict[str, Any]]: + if network_id == networks[0]["id"]: + first_failing.set() + raise api_error(503) + running.add(network_id) + await first_failing.wait() + # Slower than the error takes to reach config entry setup. + for _ in range(100): + await asyncio.sleep(0) + running.discard(network_id) + return [] + + mock_meraki_client.networks.getNetworkClients.side_effect = _get_clients + running_when_closed: list[set[str]] = [] + mock_meraki_client.__aexit__.side_effect = lambda *args: running_when_closed.append( + set(running) + ) + await setup_integration(hass, mock_config_entry) + + assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY + assert running_when_closed == [set()] + + +async def test_parallel_requests_limited( + hass: HomeAssistant, + mock_meraki_client: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test only a few requests to the organization run at the same time.""" + network = (await async_load_json_array_fixture(hass, "networks.json", DOMAIN))[0] + mock_meraki_client.organizations.getOrganizationNetworks.return_value = [ + {**network, "id": f"N_{index}"} for index in range(10) + ] + running = 0 + most_running = 0 + + async def _get_clients(*args: Any, **kwargs: Any) -> list[dict[str, Any]]: + nonlocal running, most_running + running += 1 + most_running = max(most_running, running) + await asyncio.sleep(0) + running -= 1 + return [] + + mock_meraki_client.networks.getNetworkClients.side_effect = _get_clients + await setup_integration(hass, mock_config_entry) + + assert mock_config_entry.state is ConfigEntryState.LOADED + assert mock_meraki_client.networks.getNetworkClients.await_count == 10 + assert most_running == MAX_PARALLEL_REQUESTS + + +async def test_real_client_writes_no_files( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """Test the library client writes no files, prints nothing and logs via HA.""" + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("HOME", str(tmp_path)) + networks = await async_load_json_array_fixture(hass, "networks.json", DOMAIN) + clients = await async_load_json_array_fixture(hass, "clients.json", DOMAIN) + + with ( + patch.object( + AsyncOrganizations, + "getOrganizationNetworks", + new_callable=AsyncMock, + return_value=networks, + ), + patch.object( + AsyncNetworks, + "getNetworkClients", + new_callable=AsyncMock, + return_value=clients, + ), + ): + await setup_integration(hass, mock_config_entry) + assert mock_config_entry.state is ConfigEntryState.LOADED + client = mock_config_entry.runtime_data.client + assert isinstance(client, AsyncDashboardAPI) + assert client._session._smart_flow is None + + assert await hass.config_entries.async_unload(mock_config_entry.entry_id) + assert client._session._client.is_closed + + assert list(tmp_path.iterdir()) == [] + assert not any(Path(hass.config.config_dir).glob("meraki_api_*.log")) + assert capsys.readouterr().out == "" + assert logging.getLogger("meraki.aio").handlers == []