init home-assistant

This commit is contained in:
2026-11-19 15:15:32 -05:00
parent 2e81d9d300
commit feec6ef9fb
19230 changed files with 3335526 additions and 0 deletions

View File

@@ -0,0 +1 @@
"""Tests for the UniFi Network integration."""

View File

@@ -0,0 +1,422 @@
"""Fixtures for UniFi Network methods."""
from __future__ import annotations
import asyncio
from collections.abc import Callable, Coroutine, Generator
from datetime import timedelta
from types import MappingProxyType
from typing import Any, Protocol
from unittest.mock import AsyncMock, patch
from aiounifi.models.message import MessageKey
import orjson
import pytest
from homeassistant.components.unifi import STORAGE_KEY, STORAGE_VERSION
from homeassistant.components.unifi.const import CONF_SITE_ID, DOMAIN as UNIFI_DOMAIN
from homeassistant.components.unifi.hub.websocket import RETRY_TIMER
from homeassistant.const import (
CONF_HOST,
CONF_PASSWORD,
CONF_PORT,
CONF_USERNAME,
CONF_VERIFY_SSL,
CONTENT_TYPE_JSON,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
import homeassistant.util.dt as dt_util
from tests.common import MockConfigEntry, async_fire_time_changed
from tests.test_util.aiohttp import AiohttpClientMocker
DEFAULT_CONFIG_ENTRY_ID = "1"
DEFAULT_HOST = "1.2.3.4"
DEFAULT_PORT = 1234
DEFAULT_SITE = "site_id"
CONTROLLER_HOST = {
"hostname": "controller_host",
"ip": DEFAULT_HOST,
"is_wired": True,
"last_seen": 1562600145,
"mac": "10:00:00:00:00:01",
"name": "Controller host",
"oui": "Producer",
"sw_mac": "00:00:00:00:01:01",
"sw_port": 1,
"wired-rx_bytes": 1234000000,
"wired-tx_bytes": 5678000000,
"uptime": 1562600160,
}
type ConfigEntryFactoryType = Callable[[], Coroutine[Any, Any, MockConfigEntry]]
class WebsocketMessageMock(Protocol):
"""Fixture to mock websocket message."""
def __call__(
self,
*,
message: MessageKey | None = None,
data: list[dict[str, Any]] | dict[str, Any] | None = None,
) -> None:
"""Send websocket message."""
@pytest.fixture(autouse=True, name="mock_discovery")
def fixture_discovery():
"""No real network traffic allowed."""
with patch(
"homeassistant.components.unifi.config_flow._async_discover_unifi",
return_value=None,
) as mock:
yield mock
@pytest.fixture(name="mock_device_registry")
def fixture_device_registry(hass: HomeAssistant, device_registry: dr.DeviceRegistry):
"""Mock device registry."""
config_entry = MockConfigEntry(domain="something_else")
config_entry.add_to_hass(hass)
for idx, device in enumerate(
(
"00:00:00:00:00:01",
"00:00:00:00:00:02",
"00:00:00:00:00:03",
"00:00:00:00:00:04",
"00:00:00:00:00:05",
"00:00:00:00:00:06",
"00:00:00:00:01:01",
"00:00:00:00:02:02",
)
):
device_registry.async_get_or_create(
name=f"Device {idx}",
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, device)},
)
# Config entry fixtures
@pytest.fixture(name="config_entry")
def fixture_config_entry(
hass: HomeAssistant,
config_entry_data: MappingProxyType[str, Any],
config_entry_options: MappingProxyType[str, Any],
) -> MockConfigEntry:
"""Define a config entry fixture."""
config_entry = MockConfigEntry(
domain=UNIFI_DOMAIN,
entry_id="1",
unique_id="1",
data=config_entry_data,
options=config_entry_options,
)
config_entry.add_to_hass(hass)
return config_entry
@pytest.fixture(name="config_entry_data")
def fixture_config_entry_data() -> MappingProxyType[str, Any]:
"""Define a config entry data fixture."""
return {
CONF_HOST: DEFAULT_HOST,
CONF_USERNAME: "username",
CONF_PASSWORD: "password",
CONF_PORT: DEFAULT_PORT,
CONF_SITE_ID: DEFAULT_SITE,
CONF_VERIFY_SSL: False,
}
@pytest.fixture(name="config_entry_options")
def fixture_config_entry_options() -> MappingProxyType[str, Any]:
"""Define a config entry options fixture."""
return {}
# Known wireless clients
@pytest.fixture(name="known_wireless_clients")
def fixture_known_wireless_clients() -> list[str]:
"""Known previously observed wireless clients."""
return []
@pytest.fixture(autouse=True, name="mock_wireless_client_storage")
def fixture_wireless_client_storage(
hass_storage: dict[str, Any], known_wireless_clients: list[str]
):
"""Mock the known wireless storage."""
data: dict[str, list[str]] = (
{"wireless_clients": known_wireless_clients} if known_wireless_clients else {}
)
hass_storage[STORAGE_KEY] = {"version": STORAGE_VERSION, "data": data}
# UniFi request mocks
@pytest.fixture(name="mock_requests")
def fixture_request(
aioclient_mock: AiohttpClientMocker,
client_payload: list[dict[str, Any]],
clients_all_payload: list[dict[str, Any]],
device_payload: list[dict[str, Any]],
dpi_app_payload: list[dict[str, Any]],
dpi_group_payload: list[dict[str, Any]],
port_forward_payload: list[dict[str, Any]],
traffic_rule_payload: list[dict[str, Any]],
site_payload: list[dict[str, Any]],
system_information_payload: list[dict[str, Any]],
wlan_payload: list[dict[str, Any]],
) -> Callable[[str], None]:
"""Mock default UniFi requests responses."""
def __mock_requests(host: str = DEFAULT_HOST, site_id: str = DEFAULT_SITE) -> None:
url = f"https://{host}:{DEFAULT_PORT}"
def mock_get_request(path: str, payload: list[dict[str, Any]]) -> None:
# APIV2 request respoonses have `meta` and `data` automatically appended
json = {}
if path.startswith("/v2"):
json = payload
else:
json = {"meta": {"rc": "OK"}, "data": payload}
aioclient_mock.get(
f"{url}{path}",
json=json,
headers={"content-type": CONTENT_TYPE_JSON},
)
aioclient_mock.get(url, status=302) # UniFI OS check
aioclient_mock.post(
f"{url}/api/login",
json={"data": "login successful", "meta": {"rc": "ok"}},
headers={"content-type": CONTENT_TYPE_JSON},
)
mock_get_request("/api/self/sites", site_payload)
mock_get_request(f"/api/s/{site_id}/stat/sta", client_payload)
mock_get_request(f"/api/s/{site_id}/rest/user", clients_all_payload)
mock_get_request(f"/api/s/{site_id}/stat/device", device_payload)
mock_get_request(f"/api/s/{site_id}/rest/dpiapp", dpi_app_payload)
mock_get_request(f"/api/s/{site_id}/rest/dpigroup", dpi_group_payload)
mock_get_request(f"/api/s/{site_id}/rest/portforward", port_forward_payload)
mock_get_request(f"/api/s/{site_id}/stat/sysinfo", system_information_payload)
mock_get_request(f"/api/s/{site_id}/rest/wlanconf", wlan_payload)
mock_get_request(f"/v2/api/site/{site_id}/trafficrules", traffic_rule_payload)
return __mock_requests
# Request payload fixtures
@pytest.fixture(name="client_payload")
def fixture_client_data() -> list[dict[str, Any]]:
"""Client data."""
return []
@pytest.fixture(name="clients_all_payload")
def fixture_clients_all_data() -> list[dict[str, Any]]:
"""Clients all data."""
return []
@pytest.fixture(name="device_payload")
def fixture_device_data() -> list[dict[str, Any]]:
"""Device data."""
return []
@pytest.fixture(name="dpi_app_payload")
def fixture_dpi_app_data() -> list[dict[str, Any]]:
"""DPI app data."""
return []
@pytest.fixture(name="dpi_group_payload")
def fixture_dpi_group_data() -> list[dict[str, Any]]:
"""DPI group data."""
return []
@pytest.fixture(name="port_forward_payload")
def fixture_port_forward_data() -> list[dict[str, Any]]:
"""Port forward data."""
return []
@pytest.fixture(name="site_payload")
def fixture_site_data() -> list[dict[str, Any]]:
"""Site data."""
return [{"desc": "Site name", "name": "site_id", "role": "admin", "_id": "1"}]
@pytest.fixture(name="system_information_payload")
def fixture_system_information_data() -> list[dict[str, Any]]:
"""System information data."""
return [
{
"anonymous_controller_id": "24f81231-a456-4c32-abcd-f5612345385f",
"build": "atag_7.4.162_21057",
"console_display_version": "3.1.15",
"hostname": "UDMP",
"name": "UDMP",
"previous_version": "7.4.156",
"timezone": "Europe/Stockholm",
"ubnt_device_type": "UDMPRO",
"udm_version": "3.0.20.9281",
"update_available": False,
"update_downloaded": False,
"uptime": 1196290,
"version": "7.4.162",
}
]
@pytest.fixture(name="traffic_rule_payload")
def traffic_rule_payload_data() -> list[dict[str, Any]]:
"""Traffic rule data."""
return []
@pytest.fixture(name="wlan_payload")
def fixture_wlan_data() -> list[dict[str, Any]]:
"""WLAN data."""
return []
@pytest.fixture(name="mock_default_requests")
def fixture_default_requests(
mock_requests: Callable[[str, str], None],
) -> None:
"""Mock UniFi requests responses with default host and site."""
mock_requests(DEFAULT_HOST, DEFAULT_SITE)
@pytest.fixture(name="config_entry_factory")
async def fixture_config_entry_factory(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_requests: Callable[[str, str], None],
) -> ConfigEntryFactoryType:
"""Fixture factory that can set up UniFi network integration."""
async def __mock_setup_config_entry() -> MockConfigEntry:
mock_requests(config_entry.data[CONF_HOST], config_entry.data[CONF_SITE_ID])
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
return config_entry
return __mock_setup_config_entry
@pytest.fixture(name="config_entry_setup")
async def fixture_config_entry_setup(
config_entry_factory: ConfigEntryFactoryType,
) -> MockConfigEntry:
"""Fixture providing a set up instance of UniFi network integration."""
return await config_entry_factory()
# Websocket fixtures
class WebsocketStateManager(asyncio.Event):
"""Keep an async event that simules websocket context manager.
Prepares disconnect and reconnect flows.
"""
def __init__(
self, hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Store hass object and initialize asyncio.Event."""
self.hass = hass
self.aioclient_mock = aioclient_mock
super().__init__()
async def waiter(self, input: Callable[[bytes], None]) -> None:
"""Consume message_handler new_data callback."""
await self.wait()
async def disconnect(self) -> None:
"""Mark future as done to make 'await self.api.start_websocket' return."""
self.set()
await self.hass.async_block_till_done()
async def reconnect(self, fail: bool = False) -> None:
"""Set up new future to make 'await self.api.start_websocket' block.
Mock api calls done by 'await self.api.login'.
Fail will make 'await self.api.start_websocket' return immediately.
"""
# Check UniFi OS
self.aioclient_mock.get(f"https://{DEFAULT_HOST}:1234", status=302)
self.aioclient_mock.post(
f"https://{DEFAULT_HOST}:1234/api/login",
json={"data": "login successful", "meta": {"rc": "ok"}},
headers={"content-type": CONTENT_TYPE_JSON},
)
if not fail:
self.clear()
new_time = dt_util.utcnow() + timedelta(seconds=RETRY_TIMER)
async_fire_time_changed(self.hass, new_time)
await self.hass.async_block_till_done()
@pytest.fixture(autouse=True, name="_mock_websocket")
def fixture_aiounifi_websocket_method() -> Generator[AsyncMock]:
"""Mock aiounifi websocket context manager."""
with patch("aiounifi.controller.Connectivity.websocket") as ws_mock:
yield ws_mock
@pytest.fixture(autouse=True, name="mock_websocket_state")
def fixture_aiounifi_websocket_state(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, _mock_websocket: AsyncMock
) -> WebsocketStateManager:
"""Provide a state manager for UniFi websocket."""
websocket_state_manager = WebsocketStateManager(hass, aioclient_mock)
_mock_websocket.side_effect = websocket_state_manager.waiter
return websocket_state_manager
@pytest.fixture(name="mock_websocket_message")
def fixture_aiounifi_websocket_message(
_mock_websocket: AsyncMock,
) -> WebsocketMessageMock:
"""No real websocket allowed."""
def make_websocket_call(
*,
message: MessageKey | None = None,
data: list[dict[str, Any]] | dict[str, Any] | None = None,
) -> None:
"""Generate a websocket call."""
message_handler = _mock_websocket.call_args[0][0]
if data and not message:
message_handler(orjson.dumps(data))
elif data and message:
if not isinstance(data, list):
data = [data]
message_handler(
orjson.dumps({"meta": {"message": message.value}, "data": data})
)
else:
raise NotImplementedError
return make_websocket_call

View File

@@ -0,0 +1,142 @@
# serializer version: 1
# name: test_entity_and_device_data[site_payload0-wlan_payload0-device_payload0][button.ssid_1_regenerate_password-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'button',
'entity_category': <EntityCategory.CONFIG: 'config'>,
'entity_id': 'button.ssid_1_regenerate_password',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <ButtonDeviceClass.UPDATE: 'update'>,
'original_icon': None,
'original_name': 'Regenerate Password',
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'wlan_regenerate_password',
'unique_id': 'regenerate_password-012345678910111213141516',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-device_payload0][button.ssid_1_regenerate_password-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'update',
'friendly_name': 'SSID 1 Regenerate Password',
}),
'context': <ANY>,
'entity_id': 'button.ssid_1_regenerate_password',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'unknown',
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-device_payload0][button.switch_port_1_power_cycle-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'button',
'entity_category': <EntityCategory.CONFIG: 'config'>,
'entity_id': 'button.switch_port_1_power_cycle',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <ButtonDeviceClass.RESTART: 'restart'>,
'original_icon': None,
'original_name': 'Port 1 Power Cycle',
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': None,
'unique_id': 'power_cycle-00:00:00:00:01:01_1',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-device_payload0][button.switch_port_1_power_cycle-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'restart',
'friendly_name': 'switch Port 1 Power Cycle',
}),
'context': <ANY>,
'entity_id': 'button.switch_port_1_power_cycle',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'unknown',
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-device_payload0][button.switch_restart-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'button',
'entity_category': <EntityCategory.CONFIG: 'config'>,
'entity_id': 'button.switch_restart',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <ButtonDeviceClass.RESTART: 'restart'>,
'original_icon': None,
'original_name': 'Restart',
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': None,
'unique_id': 'device_restart-00:00:00:00:01:01',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-device_payload0][button.switch_restart-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'restart',
'friendly_name': 'switch Restart',
}),
'context': <ANY>,
'entity_id': 'button.switch_restart',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'unknown',
})
# ---

View File

@@ -0,0 +1,149 @@
# serializer version: 1
# name: test_entity_and_device_data[site_payload0-device_payload0-client_payload0][device_tracker.switch_1-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'device_tracker',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'device_tracker.switch_1',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'Switch 1',
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': None,
'unique_id': '00:00:00:00:01:01',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-device_payload0-client_payload0][device_tracker.switch_1-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'Switch 1',
'ip': '10.0.1.1',
'mac': '00:00:00:00:01:01',
'source_type': <SourceType.ROUTER: 'router'>,
}),
'context': <ANY>,
'entity_id': 'device_tracker.switch_1',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'home',
})
# ---
# name: test_entity_and_device_data[site_payload0-device_payload0-client_payload0][device_tracker.wd_client_1-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'device_tracker',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'device_tracker.wd_client_1',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'wd_client_1',
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': None,
'unique_id': 'site_id-00:00:00:00:00:02',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-device_payload0-client_payload0][device_tracker.wd_client_1-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'wd_client_1',
'host_name': 'wd_client_1',
'mac': '00:00:00:00:00:02',
'source_type': <SourceType.ROUTER: 'router'>,
}),
'context': <ANY>,
'entity_id': 'device_tracker.wd_client_1',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'not_home',
})
# ---
# name: test_entity_and_device_data[site_payload0-device_payload0-client_payload0][device_tracker.ws_client_1-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'device_tracker',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'device_tracker.ws_client_1',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'ws_client_1',
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': None,
'unique_id': 'site_id-00:00:00:00:00:01',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-device_payload0-client_payload0][device_tracker.ws_client_1-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'ws_client_1',
'host_name': 'ws_client_1',
'ip': '10.0.0.1',
'mac': '00:00:00:00:00:01',
'source_type': <SourceType.ROUTER: 'router'>,
}),
'context': <ANY>,
'entity_id': 'device_tracker.ws_client_1',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'not_home',
})
# ---

View File

@@ -0,0 +1,131 @@
# serializer version: 1
# name: test_entry_diagnostics[dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0]
dict({
'clients': dict({
'00:00:00:00:00:00': dict({
'blocked': False,
'hostname': 'client_1',
'ip': '10.0.0.1',
'is_wired': True,
'last_seen': 1562600145,
'mac': '00:00:00:00:00:00',
'name': 'POE Client 1',
'oui': 'Producer',
'sw_mac': '00:00:00:00:00:01',
'sw_port': 1,
'wired-rx_bytes': 1234000000,
'wired-tx_bytes': 5678000000,
}),
}),
'config': dict({
'data': dict({
'host': '**REDACTED**',
'password': '**REDACTED**',
'port': 1234,
'site': 'site_id',
'username': '**REDACTED**',
'verify_ssl': False,
}),
'disabled_by': None,
'discovery_keys': dict({
}),
'domain': 'unifi',
'entry_id': '1',
'minor_version': 1,
'options': dict({
'allow_bandwidth_sensors': True,
'allow_uptime_sensors': True,
'block_client': list([
'00:00:00:00:00:00',
]),
}),
'pref_disable_new_entities': False,
'pref_disable_polling': False,
'source': 'user',
'title': 'Mock Title',
'unique_id': '1',
'version': 1,
}),
'devices': dict({
'00:00:00:00:00:01': dict({
'board_rev': '1.2.3',
'device_id': 'mock-id',
'ethernet_table': list([
dict({
'mac': '00:00:00:00:00:02',
'name': 'eth0',
'num_port': 2,
}),
]),
'ip': '10.0.1.1',
'last_seen': 1562600145,
'mac': '00:00:00:00:00:01',
'model': 'US16P150',
'name': 'mock-name',
'port_overrides': list([
]),
'port_table': list([
dict({
'mac_table': list([
dict({
'age': 1,
'mac': '00:00:00:00:00:00',
'static': False,
'uptime': 3971792,
'vlan': 1,
}),
dict({
'age': 1,
'mac': '**REDACTED**',
'static': True,
'uptime': 0,
'vlan': 0,
}),
]),
'media': 'GE',
'name': 'Port 1',
'poe_class': 'Class 4',
'poe_enable': True,
'poe_mode': 'auto',
'poe_power': '2.56',
'poe_voltage': '53.40',
'port_idx': 1,
'port_poe': True,
'portconf_id': '1a1',
'up': True,
}),
]),
'state': 1,
'type': 'usw',
'version': '4.0.42.10433',
}),
}),
'dpi_apps': dict({
'5f976f62e3c58f018ec7e17d': dict({
'_id': '5f976f62e3c58f018ec7e17d',
'apps': list([
]),
'blocked': True,
'cats': list([
'4',
]),
'enabled': True,
'log': True,
'site_id': 'name',
}),
}),
'dpi_groups': dict({
'5f976f4ae3c58f018ec7dff6': dict({
'_id': '5f976f4ae3c58f018ec7dff6',
'dpiapp_ids': list([
'5f976f62e3c58f018ec7e17d',
]),
'name': 'Block Media Streaming',
'site_id': 'name',
}),
}),
'role_is_admin': True,
'wlans': dict({
}),
})
# ---

View File

@@ -0,0 +1,55 @@
# serializer version: 1
# name: test_entity_and_device_data[site_payload0-wlan_payload0][image.ssid_1_qr_code-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'image',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'image.ssid_1_qr_code',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'QR Code',
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'wlan_qr_code',
'unique_id': 'qr_code-012345678910111213141516',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0][image.ssid_1_qr_code-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'access_token': '1',
'entity_picture': '/api/image_proxy/image.ssid_1_qr_code?token=1',
'friendly_name': 'SSID 1 QR Code',
}),
'context': <ANY>,
'entity_id': 'image.ssid_1_qr_code',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '2021-01-01T01:01:00+00:00',
})
# ---
# name: test_wlan_qr_code[wlan_payload0]
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x84\x00\x00\x00\x84\x01\x00\x00\x00\x00y?\xbe\n\x00\x00\x00\xcaIDATx\xda\xedV[\n\xc30\x0c\x13\xbb\x80\xef\x7fK\xdd\xc0\x93\x94\xfd\xac\x1fcL\xfbl(\xc4\x04*\xacG\xdcb/\x8b\xb8O\xdeO\x00\xccP\x95\x8b\xe5\x03\xd7\xf5\xcd\x89pF\xcf\x8c \\48\x08\nS\x948\x03p\xfe\x80C\xa8\x9d\x16\xc7P\xabvJ}\xe2\xd7\x84[\xe5W\xfc7\xbbS\xfd\xde\xcfB\xf115\xa2\xe3%\x99\xad\x93\xa0:\xbf6\xbeS\xec\x1a^\xb4\xed\xfb\xb2\xab\xd1\x99\xc9\xcdAjx\x89\x0e\xc5\xea\xf4T\xf9\xee\xe40m58\xb6<\x1b\xab~\xf4\xban\xd7:\xceu\x9e\x05\xc4I\xa6\xbb\xfb%q<7:\xbf\xa2\x90wo\xf5<t_\xf5\\]\xe7\xa7\xe5\x15\x1c\xa5\xd1\xdf\x8cV\x1f#,*\x9c\xccC+S\xce\x9f\xfb\xaf\xe0\xc3\xc9\x13/\xb7\x08A\x10\xbe\x06\xd0\x00\x00\x00\x00IEND\xaeB`\x82'
# ---
# name: test_wlan_qr_code[wlan_payload0].1
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x94\x00\x00\x00\x94\x01\x00\x00\x00\x00]G=y\x00\x00\x00\xfdIDATx\xda\xedV1\x8e\x041\x0cB\xf7\x01\xff\xff\x97\xfc\xc0\x0bd\xb6\xda\xe6\xeeB\xb9V\xa4dR \xc7`<\xd8\x8f \xbew\x7f\xb9\x030\x98!\xb5\xe9\xb8\xfc\xc1g\xfc\xf6Nx\xa3%\x9c\x84\xbf\xae\xf1\x84\xb5 \xe796\xf0\\\npjx~1[xZ\\\xbfy+\xf5\xc3\x9b\x8c\xe9\xf0\xeb\xd0k]\xbe\xa3\xa1\xeb\xfaI\x850\xa2Ex\x9f\x1f-\xeb\xe46!\xba\xc0G\x18\xde\xb0|\x8f\x07e8\xca\xd0\xc0,\xd4/\xed&PA\x1a\xf5\xbe~R2m\x07\x8fa\\\xe3\x9d\xc4DnG\x7f\xb0F&\xc4L\xa3~J\xcciy\xdfF\xff\x9a`i\xda$w\xfcom\xcc\x02Kw\x14\xf4\xc2\xd3fn\xba-\xf0A&A\xe2\x0c\x92\x8e\xbfL<\xcb.\xd8\xf1?0~o\xc14\xfcy\xdc\xc48\xa6\xd0\x98\x1f\x99\xbd\xfb\xd0\xd3\x98o\xd1tFR\x07\x8f\xe95lo\xbeE\x88`\x8f\xdf\x8c`lE\x7f\xdf\xff\xc4\x7f\xde\xbd\x00\xfc\xb3\x80\x95k\x06#\x19\x00\x00\x00\x00IEND\xaeB`\x82'
# ---

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,517 @@
# serializer version: 1
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.block_client_1-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'switch',
'entity_category': <EntityCategory.CONFIG: 'config'>,
'entity_id': 'switch.block_client_1',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <SwitchDeviceClass.SWITCH: 'switch'>,
'original_icon': None,
'original_name': None,
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'block_client',
'unique_id': 'block-00:00:00:00:01:01',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.block_client_1-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'switch',
'friendly_name': 'Block Client 1',
}),
'context': <ANY>,
'entity_id': 'switch.block_client_1',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'off',
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.block_media_streaming-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'switch',
'entity_category': <EntityCategory.CONFIG: 'config'>,
'entity_id': 'switch.block_media_streaming',
'has_entity_name': False,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'Block Media Streaming',
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'dpi_restriction',
'unique_id': '5f976f4ae3c58f018ec7dff6',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.block_media_streaming-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'Block Media Streaming',
}),
'context': <ANY>,
'entity_id': 'switch.block_media_streaming',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.dummy_usp_pdu_pro_outlet_2-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'switch',
'entity_category': None,
'entity_id': 'switch.dummy_usp_pdu_pro_outlet_2',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <SwitchDeviceClass.OUTLET: 'outlet'>,
'original_icon': None,
'original_name': 'Outlet 2',
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': None,
'unique_id': 'outlet-01:02:03:04:05:ff_2',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.dummy_usp_pdu_pro_outlet_2-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'outlet',
'friendly_name': 'Dummy USP-PDU-Pro Outlet 2',
}),
'context': <ANY>,
'entity_id': 'switch.dummy_usp_pdu_pro_outlet_2',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.dummy_usp_pdu_pro_usb_outlet_1-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'switch',
'entity_category': None,
'entity_id': 'switch.dummy_usp_pdu_pro_usb_outlet_1',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <SwitchDeviceClass.OUTLET: 'outlet'>,
'original_icon': None,
'original_name': 'USB Outlet 1',
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': None,
'unique_id': 'outlet-01:02:03:04:05:ff_1',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.dummy_usp_pdu_pro_usb_outlet_1-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'outlet',
'friendly_name': 'Dummy USP-PDU-Pro USB Outlet 1',
}),
'context': <ANY>,
'entity_id': 'switch.dummy_usp_pdu_pro_usb_outlet_1',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.mock_name_port_1_poe-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'switch',
'entity_category': <EntityCategory.CONFIG: 'config'>,
'entity_id': 'switch.mock_name_port_1_poe',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <SwitchDeviceClass.OUTLET: 'outlet'>,
'original_icon': None,
'original_name': 'Port 1 PoE',
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'poe_port_control',
'unique_id': 'poe-10:00:00:00:01:01_1',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.mock_name_port_1_poe-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'outlet',
'friendly_name': 'mock-name Port 1 PoE',
}),
'context': <ANY>,
'entity_id': 'switch.mock_name_port_1_poe',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.mock_name_port_2_poe-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'switch',
'entity_category': <EntityCategory.CONFIG: 'config'>,
'entity_id': 'switch.mock_name_port_2_poe',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <SwitchDeviceClass.OUTLET: 'outlet'>,
'original_icon': None,
'original_name': 'Port 2 PoE',
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'poe_port_control',
'unique_id': 'poe-10:00:00:00:01:01_2',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.mock_name_port_2_poe-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'outlet',
'friendly_name': 'mock-name Port 2 PoE',
}),
'context': <ANY>,
'entity_id': 'switch.mock_name_port_2_poe',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.mock_name_port_4_poe-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'switch',
'entity_category': <EntityCategory.CONFIG: 'config'>,
'entity_id': 'switch.mock_name_port_4_poe',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <SwitchDeviceClass.OUTLET: 'outlet'>,
'original_icon': None,
'original_name': 'Port 4 PoE',
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'poe_port_control',
'unique_id': 'poe-10:00:00:00:01:01_4',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.mock_name_port_4_poe-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'outlet',
'friendly_name': 'mock-name Port 4 PoE',
}),
'context': <ANY>,
'entity_id': 'switch.mock_name_port_4_poe',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.plug_outlet_1-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'switch',
'entity_category': None,
'entity_id': 'switch.plug_outlet_1',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <SwitchDeviceClass.OUTLET: 'outlet'>,
'original_icon': None,
'original_name': 'Outlet 1',
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': None,
'unique_id': 'outlet-fc:ec:da:76:4f:5f_1',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.plug_outlet_1-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'outlet',
'friendly_name': 'Plug Outlet 1',
}),
'context': <ANY>,
'entity_id': 'switch.plug_outlet_1',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.ssid_1-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'switch',
'entity_category': <EntityCategory.CONFIG: 'config'>,
'entity_id': 'switch.ssid_1',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <SwitchDeviceClass.SWITCH: 'switch'>,
'original_icon': None,
'original_name': None,
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'wlan_control',
'unique_id': 'wlan-012345678910111213141516',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.ssid_1-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'switch',
'friendly_name': 'SSID 1',
}),
'context': <ANY>,
'entity_id': 'switch.ssid_1',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.unifi_network_plex-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'switch',
'entity_category': <EntityCategory.CONFIG: 'config'>,
'entity_id': 'switch.unifi_network_plex',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <SwitchDeviceClass.SWITCH: 'switch'>,
'original_icon': None,
'original_name': 'plex',
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'port_forward_control',
'unique_id': 'port_forward-5a32aa4ee4b0412345678911',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.unifi_network_plex-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'switch',
'friendly_name': 'UniFi Network plex',
}),
'context': <ANY>,
'entity_id': 'switch.unifi_network_plex',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.unifi_network_test_traffic_rule-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'switch',
'entity_category': <EntityCategory.CONFIG: 'config'>,
'entity_id': 'switch.unifi_network_test_traffic_rule',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <SwitchDeviceClass.SWITCH: 'switch'>,
'original_icon': None,
'original_name': 'Test Traffic Rule',
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'traffic_rule_control',
'unique_id': 'traffic_rule-6452cd9b859d5b11aa002ea1',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-wlan_payload0-traffic_rule_payload0-port_forward_payload0-dpi_group_payload0-dpi_app_payload0-device_payload0-client_payload0-config_entry_options0][switch.unifi_network_test_traffic_rule-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'switch',
'friendly_name': 'UniFi Network Test Traffic Rule',
}),
'context': <ANY>,
'entity_id': 'switch.unifi_network_test_traffic_rule',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---

View File

@@ -0,0 +1,237 @@
# serializer version: 1
# name: test_entity_and_device_data[site_payload0-device_payload0][update.device_1-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'update',
'entity_category': <EntityCategory.CONFIG: 'config'>,
'entity_id': 'update.device_1',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <UpdateDeviceClass.FIRMWARE: 'firmware'>,
'original_icon': None,
'original_name': None,
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': <UpdateEntityFeature: 5>,
'translation_key': None,
'unique_id': 'device_update-00:00:00:00:01:01',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-device_payload0][update.device_1-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'auto_update': False,
'device_class': 'firmware',
'display_precision': 0,
'entity_picture': 'https://brands.home-assistant.io/_/unifi/icon.png',
'friendly_name': 'Device 1',
'in_progress': False,
'installed_version': '4.0.42.10433',
'latest_version': '4.3.17.11279',
'release_summary': None,
'release_url': None,
'skipped_version': None,
'supported_features': <UpdateEntityFeature: 5>,
'title': None,
'update_percentage': None,
}),
'context': <ANY>,
'entity_id': 'update.device_1',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
# name: test_entity_and_device_data[site_payload0-device_payload0][update.device_2-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'update',
'entity_category': <EntityCategory.CONFIG: 'config'>,
'entity_id': 'update.device_2',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <UpdateDeviceClass.FIRMWARE: 'firmware'>,
'original_icon': None,
'original_name': None,
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': <UpdateEntityFeature: 5>,
'translation_key': None,
'unique_id': 'device_update-00:00:00:00:01:02',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload0-device_payload0][update.device_2-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'auto_update': False,
'device_class': 'firmware',
'display_precision': 0,
'entity_picture': 'https://brands.home-assistant.io/_/unifi/icon.png',
'friendly_name': 'Device 2',
'in_progress': False,
'installed_version': '4.0.42.10433',
'latest_version': '4.0.42.10433',
'release_summary': None,
'release_url': None,
'skipped_version': None,
'supported_features': <UpdateEntityFeature: 5>,
'title': None,
'update_percentage': None,
}),
'context': <ANY>,
'entity_id': 'update.device_2',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'off',
})
# ---
# name: test_entity_and_device_data[site_payload1-device_payload0][update.device_1-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'update',
'entity_category': <EntityCategory.CONFIG: 'config'>,
'entity_id': 'update.device_1',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <UpdateDeviceClass.FIRMWARE: 'firmware'>,
'original_icon': None,
'original_name': None,
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': <UpdateEntityFeature: 4>,
'translation_key': None,
'unique_id': 'device_update-00:00:00:00:01:01',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload1-device_payload0][update.device_1-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'auto_update': False,
'device_class': 'firmware',
'display_precision': 0,
'entity_picture': 'https://brands.home-assistant.io/_/unifi/icon.png',
'friendly_name': 'Device 1',
'in_progress': False,
'installed_version': '4.0.42.10433',
'latest_version': '4.3.17.11279',
'release_summary': None,
'release_url': None,
'skipped_version': None,
'supported_features': <UpdateEntityFeature: 4>,
'title': None,
'update_percentage': None,
}),
'context': <ANY>,
'entity_id': 'update.device_1',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
# name: test_entity_and_device_data[site_payload1-device_payload0][update.device_2-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'update',
'entity_category': <EntityCategory.CONFIG: 'config'>,
'entity_id': 'update.device_2',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <UpdateDeviceClass.FIRMWARE: 'firmware'>,
'original_icon': None,
'original_name': None,
'platform': 'unifi',
'previous_unique_id': None,
'supported_features': <UpdateEntityFeature: 4>,
'translation_key': None,
'unique_id': 'device_update-00:00:00:00:01:02',
'unit_of_measurement': None,
})
# ---
# name: test_entity_and_device_data[site_payload1-device_payload0][update.device_2-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'auto_update': False,
'device_class': 'firmware',
'display_precision': 0,
'entity_picture': 'https://brands.home-assistant.io/_/unifi/icon.png',
'friendly_name': 'Device 2',
'in_progress': False,
'installed_version': '4.0.42.10433',
'latest_version': '4.0.42.10433',
'release_summary': None,
'release_url': None,
'skipped_version': None,
'supported_features': <UpdateEntityFeature: 4>,
'title': None,
'update_percentage': None,
}),
'context': <ANY>,
'entity_id': 'update.device_2',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'off',
})
# ---

View File

@@ -0,0 +1,340 @@
"""UniFi Network button platform tests."""
from copy import deepcopy
from datetime import timedelta
from typing import Any
from unittest.mock import patch
from aiounifi.models.message import MessageKey
import pytest
from syrupy import SnapshotAssertion
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN
from homeassistant.components.unifi.const import CONF_SITE_ID
from homeassistant.config_entries import RELOAD_AFTER_UPDATE_DELAY
from homeassistant.const import (
CONF_HOST,
CONTENT_TYPE_JSON,
STATE_UNAVAILABLE,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.entity_registry import RegistryEntryDisabler
import homeassistant.util.dt as dt_util
from .conftest import (
ConfigEntryFactoryType,
WebsocketMessageMock,
WebsocketStateManager,
)
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
from tests.test_util.aiohttp import AiohttpClientMocker
RANDOM_TOKEN = "random_token"
@pytest.fixture(autouse=True)
def mock_secret():
"""Mock secret."""
with patch("secrets.token_urlsafe", return_value=RANDOM_TOKEN):
yield
DEVICE_RESTART = [
{
"board_rev": 3,
"device_id": "mock-id",
"ip": "10.0.0.1",
"last_seen": 1562600145,
"mac": "00:00:00:00:01:01",
"model": "US16P150",
"name": "switch",
"state": 1,
"type": "usw",
"version": "4.0.42.10433",
}
]
DEVICE_POWER_CYCLE_POE = [
{
"board_rev": 3,
"device_id": "mock-id",
"ip": "10.0.0.1",
"last_seen": 1562600145,
"mac": "00:00:00:00:01:01",
"model": "US16P150",
"name": "switch",
"state": 1,
"type": "usw",
"version": "4.0.42.10433",
"port_table": [
{
"media": "GE",
"name": "Port 1",
"port_idx": 1,
"poe_caps": 7,
"poe_class": "Class 4",
"poe_enable": True,
"poe_mode": "auto",
"poe_power": "2.56",
"poe_voltage": "53.40",
"portconf_id": "1a1",
"port_poe": True,
"up": True,
},
],
}
]
WLAN_REGENERATE_PASSWORD = [
{
"_id": "012345678910111213141516",
"bc_filter_enabled": False,
"bc_filter_list": [],
"dtim_mode": "default",
"dtim_na": 1,
"dtim_ng": 1,
"enabled": True,
"group_rekey": 3600,
"mac_filter_enabled": False,
"mac_filter_list": [],
"mac_filter_policy": "allow",
"minrate_na_advertising_rates": False,
"minrate_na_beacon_rate_kbps": 6000,
"minrate_na_data_rate_kbps": 6000,
"minrate_na_enabled": False,
"minrate_na_mgmt_rate_kbps": 6000,
"minrate_ng_advertising_rates": False,
"minrate_ng_beacon_rate_kbps": 1000,
"minrate_ng_data_rate_kbps": 1000,
"minrate_ng_enabled": False,
"minrate_ng_mgmt_rate_kbps": 1000,
"name": "SSID 1",
"no2ghz_oui": False,
"schedule": [],
"security": "wpapsk",
"site_id": "5a32aa4ee4b0412345678910",
"usergroup_id": "012345678910111213141518",
"wep_idx": 1,
"wlangroup_id": "012345678910111213141519",
"wpa_enc": "ccmp",
"wpa_mode": "wpa2",
"x_iapp_key": "01234567891011121314151617181920",
"x_passphrase": "password",
}
]
@pytest.mark.parametrize("device_payload", [DEVICE_RESTART + DEVICE_POWER_CYCLE_POE])
@pytest.mark.parametrize("wlan_payload", [WLAN_REGENERATE_PASSWORD])
@pytest.mark.parametrize(
"site_payload",
[
[{"desc": "Site name", "name": "site_id", "role": "admin", "_id": "1"}],
[{"desc": "Site name", "name": "site_id", "role": "not admin", "_id": "1"}],
],
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_entity_and_device_data(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
config_entry_factory: ConfigEntryFactoryType,
site_payload: dict[str, Any],
snapshot: SnapshotAssertion,
) -> None:
"""Validate entity and device data with and without admin rights."""
with patch("homeassistant.components.unifi.PLATFORMS", [Platform.BUTTON]):
config_entry = await config_entry_factory()
if site_payload[0]["role"] == "admin":
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
else:
assert len(hass.states.async_entity_ids(BUTTON_DOMAIN)) == 0
async def _test_button_entity(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
mock_websocket_state: WebsocketStateManager,
config_entry: MockConfigEntry,
entity_id: str,
request_method: str,
request_path: str,
request_data: dict[str, Any],
call: dict[str, str],
) -> None:
"""Test button entity."""
# Send and validate device command
aioclient_mock.clear_requests()
aioclient_mock.request(
request_method,
f"https://{config_entry.data[CONF_HOST]}:1234"
f"/api/s/{config_entry.data[CONF_SITE_ID]}{request_path}",
**request_data,
)
await hass.services.async_call(
BUTTON_DOMAIN, "press", {"entity_id": entity_id}, blocking=True
)
assert aioclient_mock.call_count == 1
assert aioclient_mock.mock_calls[0][2] == call
# Availability signalling
# Controller disconnects
await mock_websocket_state.disconnect()
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
# Controller reconnects
await mock_websocket_state.reconnect()
assert hass.states.get(entity_id).state != STATE_UNAVAILABLE
@pytest.mark.parametrize(
(
"device_payload",
"entity_id",
"request_method",
"request_path",
"call",
),
[
(
DEVICE_RESTART,
"button.switch_restart",
"post",
"/cmd/devmgr",
{
"cmd": "restart",
"mac": "00:00:00:00:01:01",
"reboot_type": "soft",
},
),
(
DEVICE_POWER_CYCLE_POE,
"button.switch_port_1_power_cycle",
"post",
"/cmd/devmgr",
{
"cmd": "power-cycle",
"mac": "00:00:00:00:01:01",
"port_idx": 1,
},
),
],
)
async def test_device_button_entities(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
config_entry_setup: MockConfigEntry,
mock_websocket_state: WebsocketStateManager,
entity_id: str,
request_method: str,
request_path: str,
call: dict[str, str],
) -> None:
"""Test button entities based on device sources."""
await _test_button_entity(
hass,
aioclient_mock,
mock_websocket_state,
config_entry_setup,
entity_id,
request_method,
request_path,
{},
call,
)
@pytest.mark.parametrize(
(
"wlan_payload",
"entity_id",
"request_method",
"request_path",
"request_data",
"call",
),
[
(
WLAN_REGENERATE_PASSWORD,
"button.ssid_1_regenerate_password",
"put",
f"/rest/wlanconf/{WLAN_REGENERATE_PASSWORD[0]["_id"]}",
{
"json": {"data": "password changed successfully", "meta": {"rc": "ok"}},
"headers": {"content-type": CONTENT_TYPE_JSON},
},
{"x_passphrase": RANDOM_TOKEN},
),
],
)
async def test_wlan_button_entities(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
aioclient_mock: AiohttpClientMocker,
config_entry_setup: MockConfigEntry,
mock_websocket_state: WebsocketStateManager,
entity_id: str,
request_method: str,
request_path: str,
request_data: dict[str, Any],
call: dict[str, str],
) -> None:
"""Test button entities based on WLAN sources."""
assert len(hass.states.async_entity_ids(BUTTON_DOMAIN)) == 0
ent_reg_entry = entity_registry.async_get(entity_id)
assert ent_reg_entry.disabled_by == RegistryEntryDisabler.INTEGRATION
# Enable entity
entity_registry.async_update_entity(entity_id=entity_id, disabled_by=None)
async_fire_time_changed(
hass,
dt_util.utcnow() + timedelta(seconds=RELOAD_AFTER_UPDATE_DELAY + 1),
)
await hass.async_block_till_done()
await _test_button_entity(
hass,
aioclient_mock,
mock_websocket_state,
config_entry_setup,
entity_id,
request_method,
request_path,
request_data,
call,
)
@pytest.mark.parametrize("device_payload", [DEVICE_POWER_CYCLE_POE])
@pytest.mark.usefixtures("config_entry_setup")
async def test_power_cycle_availability(
hass: HomeAssistant,
mock_websocket_message: WebsocketMessageMock,
device_payload: dict[str, Any],
) -> None:
"""Verify that disabling PoE marks entity as unavailable."""
entity_id = "button.switch_port_1_power_cycle"
assert hass.states.get(entity_id).state != STATE_UNAVAILABLE
# PoE disabled
device_1 = deepcopy(device_payload[0])
device_1["port_table"][0]["poe_enable"] = False
mock_websocket_message(message=MessageKey.DEVICE, data=device_1)
await hass.async_block_till_done()
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
# PoE enabled
device_1 = deepcopy(device_payload[0])
device_1["port_table"][0]["poe_enable"] = True
mock_websocket_message(message=MessageKey.DEVICE, data=device_1)
await hass.async_block_till_done()
assert hass.states.get(entity_id).state != STATE_UNAVAILABLE

View File

@@ -0,0 +1,607 @@
"""Test UniFi Network config flow."""
import socket
from unittest.mock import PropertyMock, patch
import aiounifi
import pytest
from homeassistant import config_entries
from homeassistant.components import ssdp
from homeassistant.components.unifi.config_flow import _async_discover_unifi
from homeassistant.components.unifi.const import (
CONF_ALLOW_BANDWIDTH_SENSORS,
CONF_ALLOW_UPTIME_SENSORS,
CONF_BLOCK_CLIENT,
CONF_CLIENT_SOURCE,
CONF_DETECTION_TIME,
CONF_DPI_RESTRICTIONS,
CONF_IGNORE_WIRED_BUG,
CONF_SITE_ID,
CONF_SSID_FILTER,
CONF_TRACK_CLIENTS,
CONF_TRACK_DEVICES,
CONF_TRACK_WIRED_CLIENTS,
DOMAIN as UNIFI_DOMAIN,
)
from homeassistant.const import (
CONF_HOST,
CONF_PASSWORD,
CONF_PORT,
CONF_USERNAME,
CONF_VERIFY_SSL,
)
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .conftest import ConfigEntryFactoryType
from tests.common import MockConfigEntry
CLIENTS = [{"mac": "00:00:00:00:00:01"}]
DEVICES = [
{
"board_rev": 21,
"device_id": "mock-id",
"ip": "10.0.1.1",
"last_seen": 0,
"mac": "00:00:00:00:01:01",
"model": "U7PG2",
"name": "access_point",
"state": 1,
"type": "uap",
"version": "4.0.80.10875",
"wlan_overrides": [
{
"name": "SSID 3",
"radio": "na",
"radio_name": "wifi1",
"wlan_id": "012345678910111213141516",
},
{
"name": "",
"radio": "na",
"radio_name": "wifi1",
"wlan_id": "012345678910111213141516",
},
{
"radio": "na",
"radio_name": "wifi1",
"wlan_id": "012345678910111213141516",
},
],
}
]
WLANS = [
{"_id": "1", "name": "SSID 1", "enabled": True},
{
"_id": "2",
"name": "SSID 2",
"name_combine_enabled": False,
"name_combine_suffix": "_IOT",
"enabled": True,
},
{"_id": "3", "name": "SSID 4", "name_combine_enabled": False, "enabled": True},
]
DPI_GROUPS = [
{
"_id": "5ba29dd8e3c58f026e9d7c4a",
"name": "Default",
"site_id": "5ba29dd4e3c58f026e9d7c38",
},
]
@pytest.mark.usefixtures("mock_default_requests")
async def test_flow_works(hass: HomeAssistant, mock_discovery) -> None:
"""Test config flow."""
mock_discovery.return_value = "1"
result = await hass.config_entries.flow.async_init(
UNIFI_DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["data_schema"]({CONF_USERNAME: "", CONF_PASSWORD: ""}) == {
CONF_HOST: "unifi",
CONF_USERNAME: "",
CONF_PASSWORD: "",
CONF_PORT: 443,
CONF_VERIFY_SSL: False,
}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_HOST: "1.2.3.4",
CONF_USERNAME: "username",
CONF_PASSWORD: "password",
CONF_PORT: 1234,
CONF_VERIFY_SSL: True,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Site name"
assert result["data"] == {
CONF_HOST: "1.2.3.4",
CONF_USERNAME: "username",
CONF_PASSWORD: "password",
CONF_PORT: 1234,
CONF_SITE_ID: "site_id",
CONF_VERIFY_SSL: True,
}
async def test_flow_works_negative_discovery(hass: HomeAssistant) -> None:
"""Test config flow with a negative outcome of async_discovery_unifi."""
result = await hass.config_entries.flow.async_init(
UNIFI_DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["data_schema"]({CONF_USERNAME: "", CONF_PASSWORD: ""}) == {
CONF_HOST: "",
CONF_USERNAME: "",
CONF_PASSWORD: "",
CONF_PORT: 443,
CONF_VERIFY_SSL: False,
}
@pytest.mark.parametrize(
"site_payload",
[
[
{"name": "default", "role": "admin", "desc": "site name", "_id": "1"},
{"name": "site2", "role": "admin", "desc": "site2 name", "_id": "2"},
]
],
)
@pytest.mark.usefixtures("mock_default_requests")
async def test_flow_multiple_sites(hass: HomeAssistant) -> None:
"""Test config flow works when finding multiple sites."""
result = await hass.config_entries.flow.async_init(
UNIFI_DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_HOST: "1.2.3.4",
CONF_USERNAME: "username",
CONF_PASSWORD: "password",
CONF_PORT: 1234,
CONF_VERIFY_SSL: True,
},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "site"
assert result["data_schema"]({"site": "1"})
assert result["data_schema"]({"site": "2"})
@pytest.mark.usefixtures("config_entry_setup")
async def test_flow_raise_already_configured(hass: HomeAssistant) -> None:
"""Test config flow aborts since a connected config entry already exists."""
result = await hass.config_entries.flow.async_init(
UNIFI_DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_HOST: "1.2.3.4",
CONF_USERNAME: "username",
CONF_PASSWORD: "password",
CONF_PORT: 1234,
CONF_VERIFY_SSL: True,
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.usefixtures("config_entry_setup")
async def test_flow_aborts_configuration_updated(hass: HomeAssistant) -> None:
"""Test config flow aborts since a connected config entry already exists."""
result = await hass.config_entries.flow.async_init(
UNIFI_DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
with patch("homeassistant.components.unifi.async_setup_entry") and patch(
"homeassistant.components.unifi.UnifiHub.available", new_callable=PropertyMock
) as ws_mock:
ws_mock.return_value = False
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_HOST: "1.2.3.4",
CONF_USERNAME: "username",
CONF_PASSWORD: "password",
CONF_PORT: 12345,
CONF_VERIFY_SSL: True,
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "configuration_updated"
@pytest.mark.usefixtures("mock_default_requests")
async def test_flow_fails_user_credentials_faulty(hass: HomeAssistant) -> None:
"""Test config flow."""
result = await hass.config_entries.flow.async_init(
UNIFI_DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
with patch("aiounifi.Controller.login", side_effect=aiounifi.errors.Unauthorized):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_HOST: "1.2.3.4",
CONF_USERNAME: "username",
CONF_PASSWORD: "password",
CONF_PORT: 1234,
CONF_VERIFY_SSL: True,
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "faulty_credentials"}
@pytest.mark.usefixtures("mock_default_requests")
async def test_flow_fails_hub_unavailable(hass: HomeAssistant) -> None:
"""Test config flow."""
result = await hass.config_entries.flow.async_init(
UNIFI_DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
with patch("aiounifi.Controller.login", side_effect=aiounifi.errors.RequestError):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_HOST: "1.2.3.4",
CONF_USERNAME: "username",
CONF_PASSWORD: "password",
CONF_PORT: 1234,
CONF_VERIFY_SSL: True,
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "service_unavailable"}
async def test_reauth_flow_update_configuration(
hass: HomeAssistant, config_entry_setup: MockConfigEntry
) -> None:
"""Verify reauth flow can update hub configuration."""
config_entry = config_entry_setup
result = await config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
with patch(
"homeassistant.components.unifi.UnifiHub.available", new_callable=PropertyMock
) as ws_mock:
ws_mock.return_value = False
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_HOST: "1.2.3.4",
CONF_USERNAME: "new_name",
CONF_PASSWORD: "new_pass",
CONF_PORT: 1234,
CONF_VERIFY_SSL: True,
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert config_entry.data[CONF_HOST] == "1.2.3.4"
assert config_entry.data[CONF_USERNAME] == "new_name"
assert config_entry.data[CONF_PASSWORD] == "new_pass"
async def test_reauth_flow_update_configuration_on_not_loaded_entry(
hass: HomeAssistant, config_entry_factory: ConfigEntryFactoryType
) -> None:
"""Verify reauth flow can update hub configuration on a not loaded entry."""
with patch("aiounifi.Controller.login", side_effect=aiounifi.errors.RequestError):
config_entry = await config_entry_factory()
result = await config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_HOST: "1.2.3.4",
CONF_USERNAME: "new_name",
CONF_PASSWORD: "new_pass",
CONF_PORT: 1234,
CONF_VERIFY_SSL: True,
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert config_entry.data[CONF_HOST] == "1.2.3.4"
assert config_entry.data[CONF_USERNAME] == "new_name"
assert config_entry.data[CONF_PASSWORD] == "new_pass"
@pytest.mark.parametrize("client_payload", [CLIENTS])
@pytest.mark.parametrize("device_payload", [DEVICES])
@pytest.mark.parametrize("wlan_payload", [WLANS])
@pytest.mark.parametrize("dpi_group_payload", [DPI_GROUPS])
async def test_advanced_option_flow(
hass: HomeAssistant, config_entry_setup: MockConfigEntry
) -> None:
"""Test advanced config flow options."""
config_entry = config_entry_setup
result = await hass.config_entries.options.async_init(
config_entry.entry_id, context={"show_advanced_options": True}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "configure_entity_sources"
assert not result["last_step"]
assert list(result["data_schema"].schema[CONF_CLIENT_SOURCE].options.keys()) == [
"00:00:00:00:00:01"
]
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={CONF_CLIENT_SOURCE: ["00:00:00:00:00:01"]},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "device_tracker"
assert not result["last_step"]
assert list(result["data_schema"].schema[CONF_SSID_FILTER].options.keys()) == [
"",
"SSID 1",
"SSID 2",
"SSID 2_IOT",
"SSID 3",
"SSID 4",
]
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={
CONF_TRACK_CLIENTS: False,
CONF_TRACK_WIRED_CLIENTS: False,
CONF_TRACK_DEVICES: False,
CONF_SSID_FILTER: ["SSID 1", "SSID 2_IOT", "SSID 3", "SSID 4"],
CONF_DETECTION_TIME: 100,
},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "client_control"
assert not result["last_step"]
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={
CONF_BLOCK_CLIENT: [CLIENTS[0]["mac"]],
CONF_DPI_RESTRICTIONS: False,
},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "statistics_sensors"
assert result["last_step"]
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={
CONF_ALLOW_BANDWIDTH_SENSORS: True,
CONF_ALLOW_UPTIME_SENSORS: True,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
CONF_CLIENT_SOURCE: ["00:00:00:00:00:01"],
CONF_TRACK_CLIENTS: False,
CONF_TRACK_WIRED_CLIENTS: False,
CONF_TRACK_DEVICES: False,
CONF_SSID_FILTER: ["SSID 1", "SSID 2_IOT", "SSID 3", "SSID 4"],
CONF_DETECTION_TIME: 100,
CONF_IGNORE_WIRED_BUG: False,
CONF_DPI_RESTRICTIONS: False,
CONF_BLOCK_CLIENT: [CLIENTS[0]["mac"]],
CONF_ALLOW_BANDWIDTH_SENSORS: True,
CONF_ALLOW_UPTIME_SENSORS: True,
}
@pytest.mark.parametrize("client_payload", [CLIENTS])
async def test_simple_option_flow(
hass: HomeAssistant, config_entry_setup: MockConfigEntry
) -> None:
"""Test simple config flow options."""
config_entry = config_entry_setup
result = await hass.config_entries.options.async_init(
config_entry.entry_id, context={"show_advanced_options": False}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "simple_options"
assert result["last_step"]
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={
CONF_TRACK_CLIENTS: False,
CONF_TRACK_DEVICES: False,
CONF_BLOCK_CLIENT: [CLIENTS[0]["mac"]],
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
CONF_TRACK_CLIENTS: False,
CONF_TRACK_DEVICES: False,
CONF_BLOCK_CLIENT: [CLIENTS[0]["mac"]],
}
async def test_form_ssdp(hass: HomeAssistant) -> None:
"""Test we get the form with ssdp source."""
result = await hass.config_entries.flow.async_init(
UNIFI_DOMAIN,
context={"source": config_entries.SOURCE_SSDP},
data=ssdp.SsdpServiceInfo(
ssdp_usn="mock_usn",
ssdp_st="mock_st",
ssdp_location="http://192.168.208.1:41417/rootDesc.xml",
upnp={
"friendlyName": "UniFi Dream Machine",
"modelDescription": "UniFi Dream Machine Pro",
"serialNumber": "e0:63:da:20:14:a9",
},
),
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {}
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
assert (
flows[0].get("context", {}).get("configuration_url")
== "https://192.168.208.1:443"
)
context = next(
flow["context"]
for flow in hass.config_entries.flow.async_progress()
if flow["flow_id"] == result["flow_id"]
)
assert context["title_placeholders"] == {
"host": "192.168.208.1",
"site": "default",
}
@pytest.mark.usefixtures("config_entry")
async def test_form_ssdp_aborts_if_host_already_exists(hass: HomeAssistant) -> None:
"""Test we abort if the host is already configured."""
result = await hass.config_entries.flow.async_init(
UNIFI_DOMAIN,
context={"source": config_entries.SOURCE_SSDP},
data=ssdp.SsdpServiceInfo(
ssdp_usn="mock_usn",
ssdp_st="mock_st",
ssdp_location="http://1.2.3.4:1234/rootDesc.xml",
upnp={
"friendlyName": "UniFi Dream Machine",
"modelDescription": "UniFi Dream Machine Pro",
"serialNumber": "e0:63:da:20:14:a9",
},
),
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.usefixtures("config_entry")
async def test_form_ssdp_aborts_if_serial_already_exists(hass: HomeAssistant) -> None:
"""Test we abort if the serial is already configured."""
result = await hass.config_entries.flow.async_init(
UNIFI_DOMAIN,
context={"source": config_entries.SOURCE_SSDP},
data=ssdp.SsdpServiceInfo(
ssdp_usn="mock_usn",
ssdp_st="mock_st",
ssdp_location="http://1.2.3.4:1234/rootDesc.xml",
upnp={
"friendlyName": "UniFi Dream Machine",
"modelDescription": "UniFi Dream Machine Pro",
"serialNumber": "1",
},
),
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_form_ssdp_gets_form_with_ignored_entry(hass: HomeAssistant) -> None:
"""Test we can still setup if there is an ignored never configured entry."""
entry = MockConfigEntry(
domain=UNIFI_DOMAIN,
data={"not_controller_key": None},
source=config_entries.SOURCE_IGNORE,
)
entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
UNIFI_DOMAIN,
context={"source": config_entries.SOURCE_SSDP},
data=ssdp.SsdpServiceInfo(
ssdp_usn="mock_usn",
ssdp_st="mock_st",
ssdp_location="http://1.2.3.4:1234/rootDesc.xml",
upnp={
"friendlyName": "UniFi Dream Machine New",
"modelDescription": "UniFi Dream Machine Pro",
"serialNumber": "1",
},
),
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {}
context = next(
flow["context"]
for flow in hass.config_entries.flow.async_progress()
if flow["flow_id"] == result["flow_id"]
)
assert context["title_placeholders"] == {
"host": "1.2.3.4",
"site": "default",
}
async def test_discover_unifi_positive(hass: HomeAssistant) -> None:
"""Verify positive run of UniFi discovery."""
with patch("socket.gethostbyname", return_value=True):
assert await _async_discover_unifi(hass)
async def test_discover_unifi_negative(hass: HomeAssistant) -> None:
"""Verify negative run of UniFi discovery."""
with patch("socket.gethostbyname", side_effect=socket.gaierror):
assert await _async_discover_unifi(hass) is None

View File

@@ -0,0 +1,694 @@
"""The tests for the UniFi Network device tracker platform."""
from datetime import timedelta
from types import MappingProxyType
from typing import Any
from unittest.mock import patch
from aiounifi.models.event import EventKey
from aiounifi.models.message import MessageKey
from freezegun.api import FrozenDateTimeFactory, freeze_time
import pytest
from syrupy import SnapshotAssertion
from homeassistant.components.device_tracker import DOMAIN as TRACKER_DOMAIN
from homeassistant.components.unifi.const import (
CONF_BLOCK_CLIENT,
CONF_CLIENT_SOURCE,
CONF_IGNORE_WIRED_BUG,
CONF_SSID_FILTER,
CONF_TRACK_CLIENTS,
CONF_TRACK_DEVICES,
CONF_TRACK_WIRED_CLIENTS,
DEFAULT_DETECTION_TIME,
DOMAIN as UNIFI_DOMAIN,
)
from homeassistant.const import STATE_HOME, STATE_NOT_HOME, STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant, State
from homeassistant.helpers import entity_registry as er
import homeassistant.util.dt as dt_util
from .conftest import (
ConfigEntryFactoryType,
WebsocketMessageMock,
WebsocketStateManager,
)
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
WIRED_CLIENT_1 = {
"hostname": "wd_client_1",
"is_wired": True,
"last_seen": 1562600145,
"mac": "00:00:00:00:00:02",
}
WIRELESS_CLIENT_1 = {
"ap_mac": "00:00:00:00:02:01",
"essid": "ssid",
"hostname": "ws_client_1",
"ip": "10.0.0.1",
"is_wired": False,
"last_seen": 1562600145,
"mac": "00:00:00:00:00:01",
}
WIRED_BUG_CLIENT = {
"essid": "ssid",
"hostname": "wd_bug_client",
"ip": "10.0.0.3",
"is_wired": True,
"last_seen": 1562600145,
"mac": "00:00:00:00:00:03",
}
UNSEEN_CLIENT = {
"essid": "ssid",
"hostname": "unseen_client",
"ip": "10.0.0.4",
"is_wired": True,
"last_seen": None,
"mac": "00:00:00:00:00:04",
}
SWITCH_1 = {
"board_rev": 3,
"device_id": "mock-id-1",
"has_fan": True,
"fan_level": 0,
"ip": "10.0.1.1",
"last_seen": 1562600145,
"mac": "00:00:00:00:01:01",
"model": "US16P150",
"name": "Switch 1",
"next_interval": 20,
"overheating": True,
"state": 1,
"type": "usw",
"upgradable": True,
"version": "4.0.42.10433",
}
@pytest.mark.parametrize("client_payload", [[WIRED_CLIENT_1, WIRELESS_CLIENT_1]])
@pytest.mark.parametrize("device_payload", [[SWITCH_1]])
@pytest.mark.parametrize(
"site_payload",
[[{"desc": "Site name", "name": "site_id", "role": "not admin", "_id": "1"}]],
)
@pytest.mark.usefixtures("mock_device_registry")
async def test_entity_and_device_data(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
config_entry_factory: ConfigEntryFactoryType,
snapshot: SnapshotAssertion,
) -> None:
"""Validate entity and device data with and without admin rights."""
with patch("homeassistant.components.unifi.PLATFORMS", [Platform.DEVICE_TRACKER]):
config_entry = await config_entry_factory()
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
@pytest.mark.parametrize(
"client_payload", [[WIRELESS_CLIENT_1, WIRED_BUG_CLIENT, UNSEEN_CLIENT]]
)
@pytest.mark.parametrize("known_wireless_clients", [[WIRED_BUG_CLIENT["mac"]]])
@pytest.mark.usefixtures("mock_device_registry")
async def test_client_state_update(
hass: HomeAssistant,
mock_websocket_message: WebsocketMessageMock,
config_entry_factory: ConfigEntryFactoryType,
client_payload: list[dict[str, Any]],
) -> None:
"""Verify tracking of wireless clients."""
# A normal client with current timestamp should have STATE_HOME, this is wired bug
client_payload[1] |= {"last_seen": dt_util.as_timestamp(dt_util.utcnow())}
await config_entry_factory()
assert len(hass.states.async_entity_ids(TRACKER_DOMAIN)) == 3
assert hass.states.get("device_tracker.ws_client_1").state == STATE_NOT_HOME
assert (
hass.states.get("device_tracker.ws_client_1").attributes["host_name"]
== "ws_client_1"
)
# Wireless client with wired bug, if bug active on restart mark device away
assert hass.states.get("device_tracker.wd_bug_client").state == STATE_NOT_HOME
# A client that has never been seen should be marked away.
assert hass.states.get("device_tracker.unseen_client").state == STATE_NOT_HOME
# Updated timestamp marks client as home
ws_client_1 = client_payload[0] | {
"last_seen": dt_util.as_timestamp(dt_util.utcnow())
}
mock_websocket_message(message=MessageKey.CLIENT, data=ws_client_1)
await hass.async_block_till_done()
assert hass.states.get("device_tracker.ws_client_1").state == STATE_HOME
# Change time to mark client as away
new_time = dt_util.utcnow() + timedelta(seconds=DEFAULT_DETECTION_TIME)
with freeze_time(new_time):
async_fire_time_changed(hass, new_time)
await hass.async_block_till_done()
assert hass.states.get("device_tracker.ws_client_1").state == STATE_NOT_HOME
# Same timestamp doesn't explicitly mark client as away
mock_websocket_message(message=MessageKey.CLIENT, data=ws_client_1)
await hass.async_block_till_done()
assert hass.states.get("device_tracker.ws_client_1").state == STATE_HOME
@pytest.mark.parametrize("client_payload", [[WIRELESS_CLIENT_1]])
@pytest.mark.usefixtures("config_entry_setup")
@pytest.mark.usefixtures("mock_device_registry")
async def test_client_state_from_event_source(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_websocket_message: WebsocketMessageMock,
client_payload: list[dict[str, Any]],
) -> None:
"""Verify update state of client based on event source."""
async def mock_event(client: dict[str, Any], event_key: EventKey) -> dict[str, Any]:
"""Create and send event based on client payload."""
event = {
"user": client["mac"],
"ssid": client["essid"],
"hostname": client["hostname"],
"ap": client["ap_mac"],
"duration": 467,
"bytes": 459039,
"key": event_key,
"subsystem": "wlan",
"site_id": "name",
"time": 1587752927000,
"datetime": "2020-04-24T18:28:47Z",
"_id": "5ea32ff730c49e00f90dca1a",
}
mock_websocket_message(message=MessageKey.EVENT, data=event)
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids(TRACKER_DOMAIN)) == 1
assert hass.states.get("device_tracker.ws_client_1").state == STATE_NOT_HOME
# State change signalling works with events
# Connected event
await mock_event(client_payload[0], EventKey.WIRELESS_CLIENT_CONNECTED)
assert hass.states.get("device_tracker.ws_client_1").state == STATE_HOME
# Disconnected event
await mock_event(client_payload[0], EventKey.WIRELESS_CLIENT_DISCONNECTED)
assert hass.states.get("device_tracker.ws_client_1").state == STATE_HOME
# Change time to mark client as away
freezer.tick(timedelta(seconds=(DEFAULT_DETECTION_TIME + 1)))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get("device_tracker.ws_client_1").state == STATE_NOT_HOME
# To limit false positives in client tracker
# data sources are prioritized when available
# once real data is received events will be ignored.
# New data
ws_client_1 = client_payload[0] | {
"last_seen": dt_util.as_timestamp(dt_util.utcnow())
}
mock_websocket_message(message=MessageKey.CLIENT, data=ws_client_1)
await hass.async_block_till_done()
assert hass.states.get("device_tracker.ws_client_1").state == STATE_HOME
# Disconnection event will be ignored
await mock_event(client_payload[0], EventKey.WIRELESS_CLIENT_DISCONNECTED)
assert hass.states.get("device_tracker.ws_client_1").state == STATE_HOME
# Change time to mark client as away
freezer.tick(timedelta(seconds=(DEFAULT_DETECTION_TIME + 1)))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get("device_tracker.ws_client_1").state == STATE_NOT_HOME
@pytest.mark.parametrize("device_payload", [[SWITCH_1]])
@pytest.mark.usefixtures("mock_device_registry")
@pytest.mark.parametrize(
("state", "interval", "expected"),
[
# Start home, new signal but still home, heartbeat timer triggers away
(1, 20, (STATE_HOME, STATE_HOME, STATE_NOT_HOME)),
# Start away, new signal but still home, heartbeat time do not trigger
(0, 40, (STATE_NOT_HOME, STATE_HOME, STATE_HOME)),
],
)
async def test_tracked_device_state_change(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
config_entry_factory: ConfigEntryFactoryType,
mock_websocket_message: WebsocketMessageMock,
device_payload: list[dict[str, Any]],
state: int,
interval: int,
expected: list[str],
) -> None:
"""Test the update_items function with some devices."""
device_payload[0] = device_payload[0] | {"state": state}
await config_entry_factory()
assert len(hass.states.async_entity_ids(TRACKER_DOMAIN)) == 1
assert hass.states.get("device_tracker.switch_1").state == expected[0]
# State change signalling work
switch_1 = device_payload[0] | {"state": 1, "next_interval": interval}
mock_websocket_message(message=MessageKey.DEVICE, data=[switch_1])
await hass.async_block_till_done()
# Too little time has passed
assert hass.states.get("device_tracker.switch_1").state == expected[1]
# Change of time can mark device not_home outside of expected reporting interval
new_time = dt_util.utcnow() + timedelta(seconds=90)
freezer.move_to(new_time)
async_fire_time_changed(hass, new_time)
await hass.async_block_till_done()
# Heartbeat to update state is interval + 60 seconds
assert hass.states.get("device_tracker.switch_1").state == expected[2]
# Disabled device is unavailable
switch_1["disabled"] = True
mock_websocket_message(message=MessageKey.DEVICE, data=switch_1)
await hass.async_block_till_done()
assert hass.states.get("device_tracker.switch_1").state == STATE_UNAVAILABLE
@pytest.mark.parametrize("client_payload", [[WIRELESS_CLIENT_1, WIRED_CLIENT_1]])
@pytest.mark.usefixtures("config_entry_setup")
@pytest.mark.usefixtures("mock_device_registry")
async def test_remove_clients(
hass: HomeAssistant,
mock_websocket_message: WebsocketMessageMock,
client_payload: list[dict[str, Any]],
) -> None:
"""Test the remove_items function with some clients."""
assert len(hass.states.async_entity_ids(TRACKER_DOMAIN)) == 2
assert hass.states.get("device_tracker.ws_client_1")
assert hass.states.get("device_tracker.wd_client_1")
# Remove client
mock_websocket_message(message=MessageKey.CLIENT_REMOVED, data=client_payload[0])
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids(TRACKER_DOMAIN)) == 1
assert not hass.states.get("device_tracker.ws_client_1")
assert hass.states.get("device_tracker.wd_client_1")
@pytest.mark.parametrize("client_payload", [[WIRELESS_CLIENT_1]])
@pytest.mark.parametrize("device_payload", [[SWITCH_1]])
@pytest.mark.usefixtures("config_entry_setup")
@pytest.mark.usefixtures("mock_device_registry")
async def test_hub_state_change(
hass: HomeAssistant,
mock_websocket_state: WebsocketStateManager,
) -> None:
"""Verify entities state reflect on hub connection becoming unavailable."""
assert len(hass.states.async_entity_ids(TRACKER_DOMAIN)) == 2
assert hass.states.get("device_tracker.ws_client_1").state == STATE_NOT_HOME
assert hass.states.get("device_tracker.switch_1").state == STATE_HOME
# Controller unavailable
await mock_websocket_state.disconnect()
assert hass.states.get("device_tracker.ws_client_1").state == STATE_UNAVAILABLE
assert hass.states.get("device_tracker.switch_1").state == STATE_UNAVAILABLE
# Controller available
await mock_websocket_state.reconnect()
assert hass.states.get("device_tracker.ws_client_1").state == STATE_NOT_HOME
assert hass.states.get("device_tracker.switch_1").state == STATE_HOME
@pytest.mark.usefixtures("mock_device_registry")
async def test_option_ssid_filter(
hass: HomeAssistant,
mock_websocket_message,
config_entry_factory: ConfigEntryFactoryType,
client_payload: list[dict[str, Any]],
) -> None:
"""Test the SSID filter works.
Client will travel from a supported SSID to an unsupported ssid.
Client on SSID2 will be removed on change of options.
"""
client_payload += [
WIRELESS_CLIENT_1 | {"last_seen": dt_util.as_timestamp(dt_util.utcnow())},
{
"essid": "ssid2",
"hostname": "client_on_ssid2",
"is_wired": False,
"last_seen": 1562600145,
"mac": "00:00:00:00:00:02",
},
]
config_entry = await config_entry_factory()
assert len(hass.states.async_entity_ids(TRACKER_DOMAIN)) == 2
assert hass.states.get("device_tracker.ws_client_1").state == STATE_HOME
assert hass.states.get("device_tracker.client_on_ssid2").state == STATE_NOT_HOME
# Setting SSID filter will remove clients outside of filter
hass.config_entries.async_update_entry(
config_entry, options={CONF_SSID_FILTER: ["ssid"]}
)
await hass.async_block_till_done()
# Not affected by SSID filter
assert hass.states.get("device_tracker.ws_client_1").state == STATE_HOME
# Removed due to SSID filter
assert not hass.states.get("device_tracker.client_on_ssid2")
# Roams to SSID outside of filter
ws_client_1 = client_payload[0] | {"essid": "other_ssid"}
mock_websocket_message(message=MessageKey.CLIENT, data=ws_client_1)
# Data update while SSID filter is in effect shouldn't create the client
client_on_ssid2 = client_payload[1] | {
"last_seen": dt_util.as_timestamp(dt_util.utcnow())
}
mock_websocket_message(message=MessageKey.CLIENT, data=client_on_ssid2)
await hass.async_block_till_done()
new_time = dt_util.utcnow() + timedelta(seconds=(DEFAULT_DETECTION_TIME + 1))
with freeze_time(new_time):
async_fire_time_changed(hass, new_time)
await hass.async_block_till_done()
# SSID filter marks client as away
assert hass.states.get("device_tracker.ws_client_1").state == STATE_NOT_HOME
# SSID still outside of filter
assert not hass.states.get("device_tracker.client_on_ssid2")
# Remove SSID filter
hass.config_entries.async_update_entry(config_entry, options={CONF_SSID_FILTER: []})
await hass.async_block_till_done()
ws_client_1["last_seen"] += 1
client_on_ssid2["last_seen"] += 1
mock_websocket_message(
message=MessageKey.CLIENT, data=[ws_client_1, client_on_ssid2]
)
await hass.async_block_till_done()
assert hass.states.get("device_tracker.ws_client_1").state == STATE_HOME
assert hass.states.get("device_tracker.client_on_ssid2").state == STATE_HOME
# Time pass to mark client as away
new_time += timedelta(seconds=(DEFAULT_DETECTION_TIME + 1))
with freeze_time(new_time):
async_fire_time_changed(hass, new_time)
await hass.async_block_till_done()
assert hass.states.get("device_tracker.ws_client_1").state == STATE_NOT_HOME
client_on_ssid2["last_seen"] += 1
mock_websocket_message(message=MessageKey.CLIENT, data=client_on_ssid2)
await hass.async_block_till_done()
# Client won't go away until after next update
assert hass.states.get("device_tracker.client_on_ssid2").state == STATE_HOME
# Trigger update to get client marked as away
client_on_ssid2["last_seen"] += 1
mock_websocket_message(message=MessageKey.CLIENT, data=client_on_ssid2)
await hass.async_block_till_done()
new_time += timedelta(seconds=DEFAULT_DETECTION_TIME)
with freeze_time(new_time):
async_fire_time_changed(hass, new_time)
await hass.async_block_till_done()
assert hass.states.get("device_tracker.client_on_ssid2").state == STATE_NOT_HOME
@pytest.mark.usefixtures("mock_device_registry")
async def test_wireless_client_go_wired_issue(
hass: HomeAssistant,
mock_websocket_message,
config_entry_factory: ConfigEntryFactoryType,
client_payload: list[dict[str, Any]],
) -> None:
"""Test the solution to catch wireless device go wired UniFi issue.
UniFi Network has a known issue that when a wireless device goes away it sometimes gets marked as wired.
"""
client_payload.append(
WIRELESS_CLIENT_1 | {"last_seen": dt_util.as_timestamp(dt_util.utcnow())}
)
await config_entry_factory()
assert len(hass.states.async_entity_ids(TRACKER_DOMAIN)) == 1
# Client is wireless
assert hass.states.get("device_tracker.ws_client_1").state == STATE_HOME
# Trigger wired bug
ws_client_1 = client_payload[0] | {
"last_seen": dt_util.as_timestamp(dt_util.utcnow()),
"is_wired": True,
}
mock_websocket_message(message=MessageKey.CLIENT, data=ws_client_1)
await hass.async_block_till_done()
# Wired bug fix keeps client marked as wireless
assert hass.states.get("device_tracker.ws_client_1").state == STATE_HOME
# Pass time
new_time = dt_util.utcnow() + timedelta(seconds=DEFAULT_DETECTION_TIME)
with freeze_time(new_time):
async_fire_time_changed(hass, new_time)
await hass.async_block_till_done()
# Marked as home according to the timer
assert hass.states.get("device_tracker.ws_client_1").state == STATE_NOT_HOME
# Try to mark client as connected
ws_client_1["last_seen"] += 1
mock_websocket_message(message=MessageKey.CLIENT, data=ws_client_1)
await hass.async_block_till_done()
# Make sure it don't go online again until wired bug disappears
assert hass.states.get("device_tracker.ws_client_1").state == STATE_NOT_HOME
# Make client wireless
ws_client_1["last_seen"] += 1
ws_client_1["is_wired"] = False
mock_websocket_message(message=MessageKey.CLIENT, data=ws_client_1)
await hass.async_block_till_done()
# Client is no longer affected by wired bug and can be marked online
assert hass.states.get("device_tracker.ws_client_1").state == STATE_HOME
@pytest.mark.parametrize("config_entry_options", [{CONF_IGNORE_WIRED_BUG: True}])
@pytest.mark.usefixtures("mock_device_registry")
async def test_option_ignore_wired_bug(
hass: HomeAssistant,
mock_websocket_message,
config_entry_factory: ConfigEntryFactoryType,
client_payload: list[dict[str, Any]],
) -> None:
"""Test option to ignore wired bug."""
client_payload.append(
WIRELESS_CLIENT_1 | {"last_seen": dt_util.as_timestamp(dt_util.utcnow())}
)
await config_entry_factory()
assert len(hass.states.async_entity_ids(TRACKER_DOMAIN)) == 1
# Client is wireless
assert hass.states.get("device_tracker.ws_client_1").state == STATE_HOME
# Trigger wired bug
ws_client_1 = client_payload[0]
ws_client_1["is_wired"] = True
mock_websocket_message(message=MessageKey.CLIENT, data=ws_client_1)
await hass.async_block_till_done()
# Wired bug in effect
assert hass.states.get("device_tracker.ws_client_1").state == STATE_HOME
# Pass time
new_time = dt_util.utcnow() + timedelta(seconds=DEFAULT_DETECTION_TIME)
with freeze_time(new_time):
async_fire_time_changed(hass, new_time)
await hass.async_block_till_done()
# Timer marks client as away
assert hass.states.get("device_tracker.ws_client_1").state == STATE_NOT_HOME
# Mark client as connected again
ws_client_1["last_seen"] += 1
mock_websocket_message(message=MessageKey.CLIENT, data=ws_client_1)
await hass.async_block_till_done()
# Ignoring wired bug allows client to go home again even while affected
assert hass.states.get("device_tracker.ws_client_1").state == STATE_HOME
# Make client wireless
ws_client_1["last_seen"] += 1
ws_client_1["is_wired"] = False
mock_websocket_message(message=MessageKey.CLIENT, data=ws_client_1)
await hass.async_block_till_done()
# Client is wireless and still connected
assert hass.states.get("device_tracker.ws_client_1").state == STATE_HOME
@pytest.mark.parametrize(
"config_entry_options", [{CONF_BLOCK_CLIENT: ["00:00:00:00:00:03"]}]
)
@pytest.mark.parametrize("client_payload", [[WIRED_CLIENT_1]])
@pytest.mark.parametrize(
"clients_all_payload",
[
[
{
"hostname": "restored",
"is_wired": True,
"last_seen": 1562600145,
"mac": "00:00:00:00:00:03",
},
{ # Not previously seen by integration, will not be restored
"hostname": "not_restored",
"is_wired": True,
"last_seen": 1562600145,
"mac": "00:00:00:00:00:04",
},
]
],
)
@pytest.mark.usefixtures("mock_device_registry")
async def test_restoring_client(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
config_entry: MockConfigEntry,
config_entry_factory: ConfigEntryFactoryType,
client_payload: list[dict[str, Any]],
clients_all_payload: list[dict[str, Any]],
) -> None:
"""Verify clients are restored from clients_all if they ever was registered to entity registry."""
entity_registry.async_get_or_create( # Make sure unique ID converts to site_id-mac
TRACKER_DOMAIN,
UNIFI_DOMAIN,
f'{clients_all_payload[0]["mac"]}-site_id',
suggested_object_id=clients_all_payload[0]["hostname"],
config_entry=config_entry,
)
entity_registry.async_get_or_create( # Unique ID already follow format site_id-mac
TRACKER_DOMAIN,
UNIFI_DOMAIN,
f'site_id-{client_payload[0]["mac"]}',
suggested_object_id=client_payload[0]["hostname"],
config_entry=config_entry,
)
await config_entry_factory()
assert len(hass.states.async_entity_ids(TRACKER_DOMAIN)) == 2
assert hass.states.get("device_tracker.wd_client_1")
assert hass.states.get("device_tracker.restored")
assert not hass.states.get("device_tracker.not_restored")
@pytest.mark.parametrize(
("config_entry_options", "counts", "expected"),
[
(
{CONF_TRACK_CLIENTS: True},
(3, 1),
((True, True, True), (None, None, True)),
),
(
{CONF_TRACK_CLIENTS: True, CONF_SSID_FILTER: ["ssid"]},
(3, 1),
((True, True, True), (None, None, True)),
),
(
{CONF_TRACK_CLIENTS: True, CONF_SSID_FILTER: ["ssid-2"]},
(2, 1),
((None, True, True), (None, None, True)),
),
(
{CONF_TRACK_CLIENTS: False, CONF_CLIENT_SOURCE: ["00:00:00:00:00:01"]},
(2, 1),
((True, None, True), (None, None, True)),
),
(
{CONF_TRACK_CLIENTS: False, CONF_CLIENT_SOURCE: ["00:00:00:00:00:02"]},
(2, 1),
((None, True, True), (None, None, True)),
),
(
{CONF_TRACK_WIRED_CLIENTS: True},
(3, 2),
((True, True, True), (True, None, True)),
),
(
{CONF_TRACK_DEVICES: True},
(3, 2),
((True, True, True), (True, True, None)),
),
],
)
@pytest.mark.parametrize("client_payload", [[WIRELESS_CLIENT_1, WIRED_CLIENT_1]])
@pytest.mark.parametrize("device_payload", [[SWITCH_1]])
@pytest.mark.usefixtures("mock_device_registry")
async def test_config_entry_options_track(
hass: HomeAssistant,
config_entry_setup: MockConfigEntry,
config_entry_options: MappingProxyType[str, Any],
counts: tuple[int],
expected: tuple[tuple[bool | None, ...], ...],
) -> None:
"""Test the different config entry options.
Validates how many entities are created
and that the specific ones exist as expected.
"""
option = next(iter(config_entry_options))
def assert_state(state: State | None, expected: bool | None):
"""Assert if state expected."""
assert state is None if expected is None else state
assert len(hass.states.async_entity_ids(TRACKER_DOMAIN)) == counts[0]
assert_state(hass.states.get("device_tracker.ws_client_1"), expected[0][0])
assert_state(hass.states.get("device_tracker.wd_client_1"), expected[0][1])
assert_state(hass.states.get("device_tracker.switch_1"), expected[0][2])
# Keep only the primary option and turn it off, everything else uses default
hass.config_entries.async_update_entry(config_entry_setup, options={option: False})
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids(TRACKER_DOMAIN)) == counts[1]
assert_state(hass.states.get("device_tracker.ws_client_1"), expected[1][0])
assert_state(hass.states.get("device_tracker.wd_client_1"), expected[1][1])
assert_state(hass.states.get("device_tracker.switch_1"), expected[1][2])
# Turn on the primary option, everything else uses default
hass.config_entries.async_update_entry(config_entry_setup, options={option: True})
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids(TRACKER_DOMAIN)) == 3
assert_state(hass.states.get("device_tracker.ws_client_1"), True)
assert_state(hass.states.get("device_tracker.wd_client_1"), True)
assert_state(hass.states.get("device_tracker.switch_1"), True)

View File

@@ -0,0 +1,131 @@
"""Test UniFi Network diagnostics."""
import pytest
from syrupy.assertion import SnapshotAssertion
from syrupy.filters import props
from homeassistant.components.unifi.const import (
CONF_ALLOW_BANDWIDTH_SENSORS,
CONF_ALLOW_UPTIME_SENSORS,
CONF_BLOCK_CLIENT,
)
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
CLIENT_DATA = [
{
"blocked": False,
"hostname": "client_1",
"ip": "10.0.0.1",
"is_wired": True,
"last_seen": 1562600145,
"mac": "00:00:00:00:00:01",
"name": "POE Client 1",
"oui": "Producer",
"sw_mac": "00:00:00:00:01:01",
"sw_port": 1,
"wired-rx_bytes": 1234000000,
"wired-tx_bytes": 5678000000,
}
]
DEVICE_DATA = [
{
"board_rev": "1.2.3",
"ethernet_table": [
{
"mac": "22:22:22:22:22:22",
"num_port": 2,
"name": "eth0",
}
],
"device_id": "mock-id",
"ip": "10.0.1.1",
"mac": "00:00:00:00:01:01",
"last_seen": 1562600145,
"model": "US16P150",
"name": "mock-name",
"port_overrides": [],
"port_table": [
{
"mac_table": [
{
"age": 1,
"mac": "00:00:00:00:00:01",
"static": False,
"uptime": 3971792,
"vlan": 1,
},
{
"age": 1,
"mac": "11:11:11:11:11:11",
"static": True,
"uptime": 0,
"vlan": 0,
},
],
"media": "GE",
"name": "Port 1",
"port_idx": 1,
"poe_class": "Class 4",
"poe_enable": True,
"poe_mode": "auto",
"poe_power": "2.56",
"poe_voltage": "53.40",
"portconf_id": "1a1",
"port_poe": True,
"up": True,
},
],
"state": 1,
"type": "usw",
"version": "4.0.42.10433",
}
]
DPI_APP_DATA = [
{
"_id": "5f976f62e3c58f018ec7e17d",
"apps": [],
"blocked": True,
"cats": ["4"],
"enabled": True,
"log": True,
"site_id": "name",
}
]
DPI_GROUP_DATA = [
{
"_id": "5f976f4ae3c58f018ec7dff6",
"name": "Block Media Streaming",
"site_id": "name",
"dpiapp_ids": ["5f976f62e3c58f018ec7e17d"],
}
]
@pytest.mark.parametrize(
"config_entry_options",
[
{
CONF_ALLOW_BANDWIDTH_SENSORS: True,
CONF_ALLOW_UPTIME_SENSORS: True,
CONF_BLOCK_CLIENT: ["00:00:00:00:00:01"],
}
],
)
@pytest.mark.parametrize("client_payload", [CLIENT_DATA])
@pytest.mark.parametrize("device_payload", [DEVICE_DATA])
@pytest.mark.parametrize("dpi_app_payload", [DPI_APP_DATA])
@pytest.mark.parametrize("dpi_group_payload", [DPI_GROUP_DATA])
async def test_entry_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
config_entry_setup: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test config entry diagnostics."""
assert await get_diagnostics_for_config_entry(
hass, hass_client, config_entry_setup
) == snapshot(exclude=props("created_at", "modified_at"))

View File

@@ -0,0 +1,187 @@
"""Test UniFi Network."""
from http import HTTPStatus
from types import MappingProxyType
from typing import Any
from unittest.mock import patch
import aiounifi
import pytest
from homeassistant.components.unifi.const import DOMAIN as UNIFI_DOMAIN
from homeassistant.components.unifi.errors import AuthenticationRequired, CannotConnect
from homeassistant.components.unifi.hub import get_unifi_api
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_HOST, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
import homeassistant.util.dt as dt_util
from .conftest import ConfigEntryFactoryType, WebsocketStateManager
from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
async def test_hub_setup(
device_registry: dr.DeviceRegistry,
config_entry_factory: ConfigEntryFactoryType,
) -> None:
"""Successful setup."""
with patch(
"homeassistant.config_entries.ConfigEntries.async_forward_entry_setups",
return_value=True,
) as forward_entry_setup:
config_entry = await config_entry_factory()
assert len(forward_entry_setup.mock_calls) == 1
assert forward_entry_setup.mock_calls[0][1] == (
config_entry,
[
Platform.BUTTON,
Platform.DEVICE_TRACKER,
Platform.IMAGE,
Platform.SENSOR,
Platform.SWITCH,
Platform.UPDATE,
],
)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
identifiers={(UNIFI_DOMAIN, config_entry.unique_id)},
)
assert device_entry.sw_version == "7.4.162"
async def test_reset_after_successful_setup(
hass: HomeAssistant, config_entry_setup: MockConfigEntry
) -> None:
"""Calling reset when the entry has been setup."""
assert config_entry_setup.state is ConfigEntryState.LOADED
assert await hass.config_entries.async_unload(config_entry_setup.entry_id)
assert config_entry_setup.state is ConfigEntryState.NOT_LOADED
async def test_reset_fails(
hass: HomeAssistant, config_entry_setup: MockConfigEntry
) -> None:
"""Calling reset when the entry has been setup can return false."""
assert config_entry_setup.state is ConfigEntryState.LOADED
with patch(
"homeassistant.config_entries.ConfigEntries.async_forward_entry_unload",
return_value=False,
):
assert not await hass.config_entries.async_unload(config_entry_setup.entry_id)
assert config_entry_setup.state is ConfigEntryState.LOADED
@pytest.mark.usefixtures("mock_device_registry")
async def test_connection_state_signalling(
hass: HomeAssistant,
config_entry_factory: ConfigEntryFactoryType,
mock_websocket_state: WebsocketStateManager,
client_payload: list[dict[str, Any]],
) -> None:
"""Verify connection statesignalling and connection state are working."""
client_payload.append(
{
"hostname": "client",
"ip": "10.0.0.1",
"is_wired": True,
"last_seen": dt_util.as_timestamp(dt_util.utcnow()),
"mac": "00:00:00:00:00:01",
}
)
await config_entry_factory()
# Controller is connected
assert hass.states.get("device_tracker.client").state == "home"
await mock_websocket_state.disconnect()
# Controller is disconnected
assert hass.states.get("device_tracker.client").state == "unavailable"
await mock_websocket_state.reconnect()
# Controller is once again connected
assert hass.states.get("device_tracker.client").state == "home"
async def test_reconnect_mechanism(
aioclient_mock: AiohttpClientMocker,
config_entry_setup: MockConfigEntry,
mock_websocket_state: WebsocketStateManager,
) -> None:
"""Verify reconnect prints only on first reconnection try."""
aioclient_mock.clear_requests()
aioclient_mock.get(
f"https://{config_entry_setup.data[CONF_HOST]}:1234/",
status=HTTPStatus.BAD_GATEWAY,
)
await mock_websocket_state.disconnect()
assert aioclient_mock.call_count == 0
await mock_websocket_state.reconnect(fail=True)
assert aioclient_mock.call_count == 1
await mock_websocket_state.reconnect(fail=True)
assert aioclient_mock.call_count == 2
@pytest.mark.parametrize(
"exception",
[
TimeoutError,
aiounifi.BadGateway,
aiounifi.ServiceUnavailable,
aiounifi.AiounifiException,
],
)
@pytest.mark.usefixtures("config_entry_setup")
async def test_reconnect_mechanism_exceptions(
mock_websocket_state: WebsocketStateManager,
exception: Exception,
) -> None:
"""Verify async_reconnect calls expected methods."""
with (
patch("aiounifi.Controller.login", side_effect=exception),
patch(
"homeassistant.components.unifi.hub.hub.UnifiWebsocket.reconnect"
) as mock_reconnect,
):
await mock_websocket_state.disconnect()
await mock_websocket_state.reconnect()
mock_reconnect.assert_called_once()
@pytest.mark.parametrize(
("side_effect", "raised_exception"),
[
(TimeoutError, CannotConnect),
(aiounifi.BadGateway, CannotConnect),
(aiounifi.Forbidden, CannotConnect),
(aiounifi.ServiceUnavailable, CannotConnect),
(aiounifi.RequestError, CannotConnect),
(aiounifi.ResponseError, CannotConnect),
(aiounifi.Unauthorized, AuthenticationRequired),
(aiounifi.LoginRequired, AuthenticationRequired),
(aiounifi.AiounifiException, AuthenticationRequired),
],
)
async def test_get_unifi_api_fails_to_connect(
hass: HomeAssistant,
side_effect: Exception,
raised_exception: Exception,
config_entry_data: MappingProxyType[str, Any],
) -> None:
"""Check that get_unifi_api can handle UniFi Network being unavailable."""
with (
patch("aiounifi.Controller.login", side_effect=side_effect),
pytest.raises(raised_exception),
):
await get_unifi_api(hass, config_entry_data)

View File

@@ -0,0 +1,193 @@
"""UniFi Network image platform tests."""
from copy import deepcopy
from datetime import timedelta
from http import HTTPStatus
from typing import Any
from unittest.mock import patch
from aiounifi.models.message import MessageKey
import pytest
from syrupy import SnapshotAssertion
from homeassistant.components.image import DOMAIN as IMAGE_DOMAIN
from homeassistant.config_entries import RELOAD_AFTER_UPDATE_DELAY
from homeassistant.const import STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.entity_registry import RegistryEntryDisabler
from homeassistant.util import dt as dt_util
from .conftest import (
ConfigEntryFactoryType,
WebsocketMessageMock,
WebsocketStateManager,
)
from tests.common import async_fire_time_changed, snapshot_platform
from tests.typing import ClientSessionGenerator
@pytest.fixture(autouse=True)
def mock_getrandbits():
"""Mock image access token which normally is randomized."""
with patch(
"homeassistant.components.image.SystemRandom.getrandbits",
return_value=1,
):
yield
WLAN = {
"_id": "012345678910111213141516",
"bc_filter_enabled": False,
"bc_filter_list": [],
"dtim_mode": "default",
"dtim_na": 1,
"dtim_ng": 1,
"enabled": True,
"group_rekey": 3600,
"mac_filter_enabled": False,
"mac_filter_list": [],
"mac_filter_policy": "allow",
"minrate_na_advertising_rates": False,
"minrate_na_beacon_rate_kbps": 6000,
"minrate_na_data_rate_kbps": 6000,
"minrate_na_enabled": False,
"minrate_na_mgmt_rate_kbps": 6000,
"minrate_ng_advertising_rates": False,
"minrate_ng_beacon_rate_kbps": 1000,
"minrate_ng_data_rate_kbps": 1000,
"minrate_ng_enabled": False,
"minrate_ng_mgmt_rate_kbps": 1000,
"name": "SSID 1",
"no2ghz_oui": False,
"schedule": [],
"security": "wpapsk",
"site_id": "5a32aa4ee4b0412345678910",
"usergroup_id": "012345678910111213141518",
"wep_idx": 1,
"wlangroup_id": "012345678910111213141519",
"wpa_enc": "ccmp",
"wpa_mode": "wpa2",
"x_iapp_key": "01234567891011121314151617181920",
"x_passphrase": "password",
}
@pytest.mark.parametrize("wlan_payload", [[WLAN]])
@pytest.mark.parametrize(
"site_payload",
[
[{"desc": "Site name", "name": "site_id", "role": "admin", "_id": "1"}],
[{"desc": "Site name", "name": "site_id", "role": "not admin", "_id": "1"}],
],
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
@pytest.mark.freeze_time("2021-01-01 01:01:00")
async def test_entity_and_device_data(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
config_entry_factory: ConfigEntryFactoryType,
site_payload: dict[str, Any],
snapshot: SnapshotAssertion,
) -> None:
"""Validate entity and device data with and without admin rights."""
with patch("homeassistant.components.unifi.PLATFORMS", [Platform.IMAGE]):
config_entry = await config_entry_factory()
if site_payload[0]["role"] == "admin":
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
else:
assert len(hass.states.async_entity_ids(IMAGE_DOMAIN)) == 0
@pytest.mark.parametrize("wlan_payload", [[WLAN]])
@pytest.mark.usefixtures("config_entry_setup")
async def test_wlan_qr_code(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
hass_client: ClientSessionGenerator,
snapshot: SnapshotAssertion,
mock_websocket_message: WebsocketMessageMock,
) -> None:
"""Test the update_clients function when no clients are found."""
assert len(hass.states.async_entity_ids(IMAGE_DOMAIN)) == 0
ent_reg_entry = entity_registry.async_get("image.ssid_1_qr_code")
assert ent_reg_entry.disabled_by == RegistryEntryDisabler.INTEGRATION
# Enable entity
entity_registry.async_update_entity(
entity_id="image.ssid_1_qr_code", disabled_by=None
)
async_fire_time_changed(
hass,
dt_util.utcnow() + timedelta(seconds=RELOAD_AFTER_UPDATE_DELAY + 1),
)
await hass.async_block_till_done()
# Validate image
client = await hass_client()
resp = await client.get("/api/image_proxy/image.ssid_1_qr_code")
assert resp.status == HTTPStatus.OK
body = await resp.read()
assert body == snapshot
# Update state object - same password - no change to state
image_state_1 = hass.states.get("image.ssid_1_qr_code")
mock_websocket_message(message=MessageKey.WLAN_CONF_UPDATED, data=WLAN)
image_state_2 = hass.states.get("image.ssid_1_qr_code")
assert image_state_1.state == image_state_2.state
# Update state object - changed password - new state
data = deepcopy(WLAN)
data["x_passphrase"] = "new password"
mock_websocket_message(message=MessageKey.WLAN_CONF_UPDATED, data=data)
image_state_3 = hass.states.get("image.ssid_1_qr_code")
assert image_state_1.state != image_state_3.state
# Validate image
client = await hass_client()
resp = await client.get("/api/image_proxy/image.ssid_1_qr_code")
assert resp.status == HTTPStatus.OK
body = await resp.read()
assert body == snapshot
@pytest.mark.parametrize("wlan_payload", [[WLAN]])
@pytest.mark.usefixtures("config_entry_setup")
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_hub_state_change(
hass: HomeAssistant, mock_websocket_state: WebsocketStateManager
) -> None:
"""Verify entities state reflect on hub becoming unavailable."""
assert hass.states.get("image.ssid_1_qr_code").state != STATE_UNAVAILABLE
# Controller unavailable
await mock_websocket_state.disconnect()
assert hass.states.get("image.ssid_1_qr_code").state == STATE_UNAVAILABLE
# Controller available
await mock_websocket_state.reconnect()
assert hass.states.get("image.ssid_1_qr_code").state != STATE_UNAVAILABLE
@pytest.mark.parametrize("wlan_payload", [[WLAN]])
@pytest.mark.usefixtures("config_entry_setup")
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_source_availability(
hass: HomeAssistant, mock_websocket_message: WebsocketMessageMock
) -> None:
"""Verify entities state reflect on source becoming unavailable."""
assert hass.states.get("image.ssid_1_qr_code").state != STATE_UNAVAILABLE
# WLAN gets disabled
wlan_1 = deepcopy(WLAN)
wlan_1["enabled"] = False
mock_websocket_message(message=MessageKey.WLAN_CONF_UPDATED, data=wlan_1)
assert hass.states.get("image.ssid_1_qr_code").state == STATE_UNAVAILABLE
# WLAN gets re-enabled
wlan_1["enabled"] = True
mock_websocket_message(message=MessageKey.WLAN_CONF_UPDATED, data=wlan_1)
assert hass.states.get("image.ssid_1_qr_code").state != STATE_UNAVAILABLE

View File

@@ -0,0 +1,213 @@
"""Test UniFi Network integration setup process."""
from typing import Any
from unittest.mock import patch
from aiounifi.models.message import MessageKey
import pytest
from homeassistant.components import unifi
from homeassistant.components.unifi.const import (
CONF_ALLOW_BANDWIDTH_SENSORS,
CONF_ALLOW_UPTIME_SENSORS,
CONF_TRACK_CLIENTS,
CONF_TRACK_DEVICES,
)
from homeassistant.components.unifi.errors import AuthenticationRequired, CannotConnect
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from homeassistant.setup import async_setup_component
from .conftest import (
DEFAULT_CONFIG_ENTRY_ID,
ConfigEntryFactoryType,
WebsocketMessageMock,
)
from tests.common import flush_store
from tests.typing import WebSocketGenerator
async def test_setup_entry_fails_config_entry_not_ready(
hass: HomeAssistant, config_entry_factory: ConfigEntryFactoryType
) -> None:
"""Failed authentication trigger a reauthentication flow."""
with patch(
"homeassistant.components.unifi.get_unifi_api",
side_effect=CannotConnect,
):
config_entry = await config_entry_factory()
assert config_entry.state == ConfigEntryState.SETUP_RETRY
async def test_setup_entry_fails_trigger_reauth_flow(
hass: HomeAssistant, config_entry_factory: ConfigEntryFactoryType
) -> None:
"""Failed authentication trigger a reauthentication flow."""
with (
patch(
"homeassistant.components.unifi.get_unifi_api",
side_effect=AuthenticationRequired,
),
patch.object(hass.config_entries.flow, "async_init") as mock_flow_init,
):
config_entry = await config_entry_factory()
mock_flow_init.assert_called_once()
assert config_entry.state == ConfigEntryState.SETUP_ERROR
@pytest.mark.parametrize(
"client_payload",
[
[
{
"hostname": "client_1",
"ip": "10.0.0.1",
"is_wired": False,
"mac": "00:00:00:00:00:01",
},
{
"hostname": "client_2",
"ip": "10.0.0.2",
"is_wired": False,
"mac": "00:00:00:00:00:02",
},
]
],
)
async def test_wireless_clients(
hass: HomeAssistant,
hass_storage: dict[str, Any],
config_entry_factory: ConfigEntryFactoryType,
) -> None:
"""Verify wireless clients class."""
hass_storage[unifi.STORAGE_KEY] = {
"version": unifi.STORAGE_VERSION,
"data": {
DEFAULT_CONFIG_ENTRY_ID: {
"wireless_devices": ["00:00:00:00:00:00", "00:00:00:00:00:01"]
}
},
}
await config_entry_factory()
await flush_store(hass.data[unifi.UNIFI_WIRELESS_CLIENTS]._store)
assert sorted(hass_storage[unifi.STORAGE_KEY]["data"]["wireless_clients"]) == [
"00:00:00:00:00:00",
"00:00:00:00:00:01",
"00:00:00:00:00:02",
]
@pytest.mark.parametrize(
"client_payload",
[
[
{
"hostname": "Wired client",
"is_wired": True,
"mac": "00:00:00:00:00:01",
"oui": "Producer",
"wired-rx_bytes": 1234000000,
"wired-tx_bytes": 5678000000,
"uptime": 1600094505,
},
{
"is_wired": False,
"mac": "00:00:00:00:00:02",
"name": "Wireless client",
"oui": "Producer",
"rx_bytes": 2345000000,
"tx_bytes": 6789000000,
"uptime": 60,
},
]
],
)
@pytest.mark.parametrize(
"device_payload",
[
[
{
"board_rev": 3,
"device_id": "mock-id",
"has_fan": True,
"fan_level": 0,
"ip": "10.0.1.1",
"last_seen": 1562600145,
"mac": "00:00:00:00:01:01",
"model": "US16P150",
"name": "Device 1",
"next_interval": 20,
"overheating": True,
"state": 1,
"type": "usw",
"upgradable": True,
"version": "4.0.42.10433",
}
]
],
)
@pytest.mark.parametrize(
"config_entry_options",
[
{
CONF_ALLOW_BANDWIDTH_SENSORS: True,
CONF_ALLOW_UPTIME_SENSORS: True,
CONF_TRACK_CLIENTS: True,
CONF_TRACK_DEVICES: True,
}
],
)
async def test_remove_config_entry_device(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
config_entry_factory: ConfigEntryFactoryType,
client_payload: list[dict[str, Any]],
device_payload: list[dict[str, Any]],
mock_websocket_message: WebsocketMessageMock,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Verify removing a device manually."""
config_entry = await config_entry_factory()
assert await async_setup_component(hass, "config", {})
ws_client = await hass_ws_client(hass)
# Try to remove an active client from UI: not allowed
device_entry = device_registry.async_get_device(
connections={(dr.CONNECTION_NETWORK_MAC, client_payload[0]["mac"])}
)
response = await ws_client.remove_device(device_entry.id, config_entry.entry_id)
assert not response["success"]
assert device_registry.async_get_device(
connections={(dr.CONNECTION_NETWORK_MAC, client_payload[0]["mac"])}
)
# Try to remove an active device from UI: not allowed
device_entry = device_registry.async_get_device(
connections={(dr.CONNECTION_NETWORK_MAC, device_payload[0]["mac"])}
)
response = await ws_client.remove_device(device_entry.id, config_entry.entry_id)
assert not response["success"]
assert device_registry.async_get_device(
connections={(dr.CONNECTION_NETWORK_MAC, device_payload[0]["mac"])}
)
# Remove a client from Unifi API
mock_websocket_message(message=MessageKey.CLIENT_REMOVED, data=[client_payload[1]])
await hass.async_block_till_done()
# Try to remove an inactive client from UI: allowed
device_entry = device_registry.async_get_device(
connections={(dr.CONNECTION_NETWORK_MAC, client_payload[1]["mac"])}
)
response = await ws_client.remove_device(device_entry.id, config_entry.entry_id)
assert response["success"]
assert not device_registry.async_get_device(
connections={(dr.CONNECTION_NETWORK_MAC, client_payload[1]["mac"])}
)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,313 @@
"""deCONZ service tests."""
from typing import Any
from unittest.mock import PropertyMock, patch
import pytest
from homeassistant.components.unifi.const import CONF_SITE_ID, DOMAIN as UNIFI_DOMAIN
from homeassistant.components.unifi.services import (
SERVICE_RECONNECT_CLIENT,
SERVICE_REMOVE_CLIENTS,
)
from homeassistant.const import ATTR_DEVICE_ID, CONF_HOST
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
@pytest.mark.parametrize(
"client_payload", [[{"is_wired": False, "mac": "00:00:00:00:00:01"}]]
)
async def test_reconnect_client(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
aioclient_mock: AiohttpClientMocker,
config_entry_setup: MockConfigEntry,
client_payload: list[dict[str, Any]],
) -> None:
"""Verify call to reconnect client is performed as expected."""
aioclient_mock.clear_requests()
aioclient_mock.post(
f"https://{config_entry_setup.data[CONF_HOST]}:1234"
f"/api/s/{config_entry_setup.data[CONF_SITE_ID]}/cmd/stamgr",
)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry_setup.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, client_payload[0]["mac"])},
)
await hass.services.async_call(
UNIFI_DOMAIN,
SERVICE_RECONNECT_CLIENT,
service_data={ATTR_DEVICE_ID: device_entry.id},
blocking=True,
)
assert aioclient_mock.call_count == 1
@pytest.mark.usefixtures("config_entry_setup")
async def test_reconnect_non_existant_device(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Verify no call is made if device does not exist."""
aioclient_mock.clear_requests()
await hass.services.async_call(
UNIFI_DOMAIN,
SERVICE_RECONNECT_CLIENT,
service_data={ATTR_DEVICE_ID: "device_entry.id"},
blocking=True,
)
assert aioclient_mock.call_count == 0
async def test_reconnect_device_without_mac(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
aioclient_mock: AiohttpClientMocker,
config_entry_setup: MockConfigEntry,
) -> None:
"""Verify no call is made if device does not have a known mac."""
aioclient_mock.clear_requests()
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry_setup.entry_id,
connections={("other connection", "not mac")},
)
await hass.services.async_call(
UNIFI_DOMAIN,
SERVICE_RECONNECT_CLIENT,
service_data={ATTR_DEVICE_ID: device_entry.id},
blocking=True,
)
assert aioclient_mock.call_count == 0
@pytest.mark.parametrize(
"client_payload", [[{"is_wired": False, "mac": "00:00:00:00:00:01"}]]
)
async def test_reconnect_client_hub_unavailable(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
aioclient_mock: AiohttpClientMocker,
config_entry_setup: MockConfigEntry,
client_payload: list[dict[str, Any]],
) -> None:
"""Verify no call is made if hub is unavailable."""
aioclient_mock.clear_requests()
aioclient_mock.post(
f"https://{config_entry_setup.data[CONF_HOST]}:1234"
f"/api/s/{config_entry_setup.data[CONF_SITE_ID]}/cmd/stamgr",
)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry_setup.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, client_payload[0]["mac"])},
)
with patch(
"homeassistant.components.unifi.UnifiHub.available", new_callable=PropertyMock
) as ws_mock:
ws_mock.return_value = False
await hass.services.async_call(
UNIFI_DOMAIN,
SERVICE_RECONNECT_CLIENT,
service_data={ATTR_DEVICE_ID: device_entry.id},
blocking=True,
)
assert aioclient_mock.call_count == 0
async def test_reconnect_client_unknown_mac(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
aioclient_mock: AiohttpClientMocker,
config_entry_setup: MockConfigEntry,
) -> None:
"""Verify no call is made if trying to reconnect a mac unknown to hub."""
aioclient_mock.clear_requests()
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry_setup.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "mac unknown to hub")},
)
await hass.services.async_call(
UNIFI_DOMAIN,
SERVICE_RECONNECT_CLIENT,
service_data={ATTR_DEVICE_ID: device_entry.id},
blocking=True,
)
assert aioclient_mock.call_count == 0
@pytest.mark.parametrize(
"client_payload", [[{"is_wired": True, "mac": "00:00:00:00:00:01"}]]
)
async def test_reconnect_wired_client(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
aioclient_mock: AiohttpClientMocker,
config_entry_setup: MockConfigEntry,
client_payload: list[dict[str, Any]],
) -> None:
"""Verify no call is made if client is wired."""
aioclient_mock.clear_requests()
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry_setup.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, client_payload[0]["mac"])},
)
await hass.services.async_call(
UNIFI_DOMAIN,
SERVICE_RECONNECT_CLIENT,
service_data={ATTR_DEVICE_ID: device_entry.id},
blocking=True,
)
assert aioclient_mock.call_count == 0
@pytest.mark.parametrize(
"clients_all_payload",
[
[
{
"mac": "00:00:00:00:00:00",
},
{"first_seen": 100, "last_seen": 500, "mac": "00:00:00:00:00:01"},
{"first_seen": 100, "last_seen": 1100, "mac": "00:00:00:00:00:02"},
{
"first_seen": 100,
"last_seen": 500,
"fixed_ip": "1.2.3.4",
"mac": "00:00:00:00:00:03",
},
{
"first_seen": 100,
"last_seen": 500,
"hostname": "hostname",
"mac": "00:00:00:00:00:04",
},
{
"first_seen": 100,
"last_seen": 500,
"name": "name",
"mac": "00:00:00:00:00:05",
},
]
],
)
async def test_remove_clients(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
config_entry_setup: MockConfigEntry,
) -> None:
"""Verify removing different variations of clients work."""
aioclient_mock.clear_requests()
aioclient_mock.post(
f"https://{config_entry_setup.data[CONF_HOST]}:1234"
f"/api/s/{config_entry_setup.data[CONF_SITE_ID]}/cmd/stamgr",
)
await hass.services.async_call(UNIFI_DOMAIN, SERVICE_REMOVE_CLIENTS, blocking=True)
assert aioclient_mock.mock_calls[0][2] == {
"cmd": "forget-sta",
"macs": ["00:00:00:00:00:00", "00:00:00:00:00:01"],
}
assert await hass.config_entries.async_unload(config_entry_setup.entry_id)
@pytest.mark.parametrize(
"clients_all_payload",
[
[
{
"first_seen": 100,
"last_seen": 500,
"mac": "00:00:00:00:00:01",
}
]
],
)
@pytest.mark.usefixtures("config_entry_setup")
async def test_remove_clients_hub_unavailable(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Verify no call is made if UniFi Network is unavailable."""
aioclient_mock.clear_requests()
with patch(
"homeassistant.components.unifi.UnifiHub.available", new_callable=PropertyMock
) as ws_mock:
ws_mock.return_value = False
await hass.services.async_call(
UNIFI_DOMAIN, SERVICE_REMOVE_CLIENTS, blocking=True
)
assert aioclient_mock.call_count == 0
@pytest.mark.parametrize(
"clients_all_payload",
[
[
{
"first_seen": 100,
"last_seen": 1100,
"mac": "00:00:00:00:00:01",
}
]
],
)
@pytest.mark.usefixtures("config_entry_setup")
async def test_remove_clients_no_call_on_empty_list(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Verify no call is made if no fitting client has been added to the list."""
aioclient_mock.clear_requests()
await hass.services.async_call(UNIFI_DOMAIN, SERVICE_REMOVE_CLIENTS, blocking=True)
assert aioclient_mock.call_count == 0
@pytest.mark.parametrize(
"clients_all_payload",
[
[
{
"first_seen": 100,
"last_seen": 500,
"mac": "00:00:00:00:00:01",
}
]
],
)
async def test_services_handle_unloaded_config_entry(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
device_registry: dr.DeviceRegistry,
config_entry_setup: MockConfigEntry,
clients_all_payload: dict[str, Any],
) -> None:
"""Verify no call is made if config entry is unloaded."""
await hass.config_entries.async_unload(config_entry_setup.entry_id)
await hass.async_block_till_done()
aioclient_mock.clear_requests()
await hass.services.async_call(UNIFI_DOMAIN, SERVICE_REMOVE_CLIENTS, blocking=True)
assert aioclient_mock.call_count == 0
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry_setup.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, clients_all_payload[0]["mac"])},
)
await hass.services.async_call(
UNIFI_DOMAIN,
SERVICE_RECONNECT_CLIENT,
service_data={ATTR_DEVICE_ID: device_entry.id},
blocking=True,
)
assert aioclient_mock.call_count == 0

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,176 @@
"""The tests for the UniFi Network update platform."""
from copy import deepcopy
from unittest.mock import patch
from aiounifi.models.message import MessageKey
import pytest
from syrupy import SnapshotAssertion
from yarl import URL
from homeassistant.components.unifi.const import CONF_SITE_ID
from homeassistant.components.update import (
ATTR_IN_PROGRESS,
ATTR_INSTALLED_VERSION,
ATTR_LATEST_VERSION,
DOMAIN as UPDATE_DOMAIN,
SERVICE_INSTALL,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_HOST,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .conftest import (
ConfigEntryFactoryType,
WebsocketMessageMock,
WebsocketStateManager,
)
from tests.common import MockConfigEntry, snapshot_platform
from tests.test_util.aiohttp import AiohttpClientMocker
# Device with new firmware available
DEVICE_1 = {
"board_rev": 3,
"device_id": "mock-id",
"ip": "10.0.1.1",
"last_seen": 1562600145,
"mac": "00:00:00:00:01:01",
"model": "US16P150",
"name": "Device 1",
"next_interval": 20,
"state": 1,
"type": "usw",
"upgradable": True,
"version": "4.0.42.10433",
"upgrade_to_firmware": "4.3.17.11279",
}
# Device without new firmware available
DEVICE_2 = {
"board_rev": 3,
"device_id": "mock-id",
"ip": "10.0.1.2",
"mac": "00:00:00:00:01:02",
"model": "US16P150",
"name": "Device 2",
"next_interval": 20,
"state": 0,
"type": "usw",
"version": "4.0.42.10433",
}
@pytest.mark.parametrize("device_payload", [[DEVICE_1, DEVICE_2]])
@pytest.mark.parametrize(
"site_payload",
[
[{"desc": "Site name", "name": "site_id", "role": "admin", "_id": "1"}],
[{"desc": "Site name", "name": "site_id", "role": "not admin", "_id": "1"}],
],
)
async def test_entity_and_device_data(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
config_entry_factory: ConfigEntryFactoryType,
snapshot: SnapshotAssertion,
) -> None:
"""Validate entity and device data with and without admin rights."""
with patch("homeassistant.components.unifi.PLATFORMS", [Platform.UPDATE]):
config_entry = await config_entry_factory()
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
@pytest.mark.parametrize("device_payload", [[DEVICE_1]])
@pytest.mark.usefixtures("config_entry_setup")
async def test_device_updates(
hass: HomeAssistant, mock_websocket_message: WebsocketMessageMock
) -> None:
"""Test the update_items function with some devices."""
device_1_state = hass.states.get("update.device_1")
assert device_1_state.state == STATE_ON
assert device_1_state.attributes[ATTR_IN_PROGRESS] is False
# Simulate start of update
device_1 = deepcopy(DEVICE_1)
device_1["state"] = 4
mock_websocket_message(message=MessageKey.DEVICE, data=device_1)
device_1_state = hass.states.get("update.device_1")
assert device_1_state.state == STATE_ON
assert device_1_state.attributes[ATTR_INSTALLED_VERSION] == "4.0.42.10433"
assert device_1_state.attributes[ATTR_LATEST_VERSION] == "4.3.17.11279"
assert device_1_state.attributes[ATTR_IN_PROGRESS] is True
# Simulate update finished
device_1["state"] = 0
device_1["version"] = "4.3.17.11279"
device_1["upgradable"] = False
del device_1["upgrade_to_firmware"]
mock_websocket_message(message=MessageKey.DEVICE, data=device_1)
device_1_state = hass.states.get("update.device_1")
assert device_1_state.state == STATE_OFF
assert device_1_state.attributes[ATTR_INSTALLED_VERSION] == "4.3.17.11279"
assert device_1_state.attributes[ATTR_LATEST_VERSION] == "4.3.17.11279"
assert device_1_state.attributes[ATTR_IN_PROGRESS] is False
@pytest.mark.parametrize("device_payload", [[DEVICE_1]])
async def test_install(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
config_entry_setup: MockConfigEntry,
) -> None:
"""Test the device update install call."""
device_state = hass.states.get("update.device_1")
assert device_state.state == STATE_ON
url = (
f"https://{config_entry_setup.data[CONF_HOST]}:1234"
f"/api/s/{config_entry_setup.data[CONF_SITE_ID]}/cmd/devmgr"
)
aioclient_mock.clear_requests()
aioclient_mock.post(url)
await hass.services.async_call(
UPDATE_DOMAIN,
SERVICE_INSTALL,
{ATTR_ENTITY_ID: "update.device_1"},
blocking=True,
)
await hass.async_block_till_done()
assert aioclient_mock.call_count == 1
assert aioclient_mock.mock_calls[0] == (
"post",
URL(url),
{"cmd": "upgrade", "mac": "00:00:00:00:01:01"},
{},
)
@pytest.mark.parametrize("device_payload", [[DEVICE_1]])
@pytest.mark.usefixtures("config_entry_setup")
async def test_hub_state_change(
hass: HomeAssistant, mock_websocket_state: WebsocketStateManager
) -> None:
"""Verify entities state reflect on hub becoming unavailable."""
assert hass.states.get("update.device_1").state == STATE_ON
# Controller unavailable
await mock_websocket_state.disconnect()
assert hass.states.get("update.device_1").state == STATE_UNAVAILABLE
# Controller available
await mock_websocket_state.reconnect()
assert hass.states.get("update.device_1").state == STATE_ON