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,48 @@
"""Tests for the UniFi Protect integration."""
from contextlib import contextmanager
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from unifi_discovery import AIOUnifiScanner, UnifiDevice, UnifiService
DEVICE_HOSTNAME = "unvr"
DEVICE_IP_ADDRESS = "127.0.0.1"
DEVICE_MAC_ADDRESS = "aa:bb:cc:dd:ee:ff"
DIRECT_CONNECT_DOMAIN = "x.ui.direct"
UNIFI_DISCOVERY = UnifiDevice(
source_ip=DEVICE_IP_ADDRESS,
hw_addr=DEVICE_MAC_ADDRESS,
platform=DEVICE_HOSTNAME,
hostname=DEVICE_HOSTNAME,
services={UnifiService.Protect: True},
direct_connect_domain=DIRECT_CONNECT_DOMAIN,
)
UNIFI_DISCOVERY_PARTIAL = UnifiDevice(
source_ip=DEVICE_IP_ADDRESS,
hw_addr=DEVICE_MAC_ADDRESS,
services={UnifiService.Protect: True},
)
pytest.register_assert_rewrite("tests.components.unifiprotect.utils")
def _patch_discovery(device=None, no_device=False):
mock_aio_discovery = MagicMock(auto_spec=AIOUnifiScanner)
scanner_return = [] if no_device else [device or UNIFI_DISCOVERY]
mock_aio_discovery.async_scan = AsyncMock(return_value=scanner_return)
mock_aio_discovery.found_devices = scanner_return
@contextmanager
def _patcher():
with patch(
"homeassistant.components.unifiprotect.discovery.AIOUnifiScanner",
return_value=mock_aio_discovery,
):
yield
return _patcher()

View File

@@ -0,0 +1,385 @@
"""Fixtures and test data for UniFi Protect methods."""
from __future__ import annotations
from collections.abc import Callable
from datetime import datetime, timedelta
from functools import partial
from ipaddress import IPv4Address
import json
from pathlib import Path
from tempfile import gettempdir
from typing import Any
from unittest.mock import AsyncMock, Mock, patch
import pytest
from uiprotect import ProtectApiClient
from uiprotect.data import (
NVR,
Bootstrap,
Camera,
Chime,
CloudAccount,
Doorlock,
Light,
Liveview,
Sensor,
SmartDetectObjectType,
VideoMode,
Viewer,
WSSubscriptionMessage,
)
from uiprotect.websocket import WebsocketState
from homeassistant.components.unifiprotect.const import DOMAIN
from homeassistant.core import HomeAssistant
import homeassistant.util.dt as dt_util
from . import _patch_discovery
from .utils import MockUFPFixture
from tests.common import MockConfigEntry, load_fixture
MAC_ADDR = "aa:bb:cc:dd:ee:ff"
@pytest.fixture(name="nvr")
def mock_nvr():
"""Mock UniFi Protect Camera device."""
data = json.loads(load_fixture("sample_nvr.json", integration=DOMAIN))
nvr = NVR.from_unifi_dict(**data)
# disable pydantic validation so mocking can happen
NVR.model_config["validate_assignment"] = False
yield nvr
NVR.model_config["validate_assignment"] = True
@pytest.fixture(name="ufp_config_entry")
def mock_ufp_config_entry():
"""Mock the unifiprotect config entry."""
return MockConfigEntry(
domain=DOMAIN,
data={
"host": "1.1.1.1",
"username": "test-username",
"password": "test-password",
"id": "UnifiProtect",
"port": 443,
"verify_ssl": False,
},
version=2,
)
@pytest.fixture(name="old_nvr")
def old_nvr():
"""Mock UniFi Protect Camera device."""
data = json.loads(load_fixture("sample_nvr.json", integration=DOMAIN))
data["version"] = "1.19.0"
return NVR.from_unifi_dict(**data)
@pytest.fixture(name="bootstrap")
def bootstrap_fixture(nvr: NVR):
"""Mock Bootstrap fixture."""
data = json.loads(load_fixture("sample_bootstrap.json", integration=DOMAIN))
data["nvr"] = nvr
data["cameras"] = []
data["lights"] = []
data["sensors"] = []
data["viewers"] = []
data["liveviews"] = []
data["events"] = []
data["doorlocks"] = []
data["chimes"] = []
data["aiports"] = []
return Bootstrap.from_unifi_dict(**data)
@pytest.fixture(name="ufp_client")
def mock_ufp_client(bootstrap: Bootstrap):
"""Mock ProtectApiClient for testing."""
client = Mock()
client.bootstrap = bootstrap
client._bootstrap = bootstrap
client.api_path = "/api"
client.cache_dir = Path(gettempdir()) / "ufp_cache"
# functionality from API client tests actually need
client._stream_response = partial(ProtectApiClient._stream_response, client)
client.get_camera_video = partial(ProtectApiClient.get_camera_video, client)
nvr = client.bootstrap.nvr
nvr._api = client
client.bootstrap._api = client
client.base_url = "https://127.0.0.1"
client.connection_host = IPv4Address("127.0.0.1")
async def get_nvr(*args: Any, **kwargs: Any) -> NVR:
return client.bootstrap.nvr
client.get_nvr = get_nvr
client.get_bootstrap = AsyncMock(return_value=bootstrap)
client.update = AsyncMock(return_value=bootstrap)
client.async_disconnect_ws = AsyncMock()
return client
@pytest.fixture(name="ufp")
def mock_entry(
hass: HomeAssistant, ufp_config_entry: MockConfigEntry, ufp_client: ProtectApiClient
):
"""Mock ProtectApiClient for testing."""
with (
_patch_discovery(no_device=True),
patch(
"homeassistant.components.unifiprotect.utils.ProtectApiClient"
) as mock_api,
):
ufp_config_entry.add_to_hass(hass)
mock_api.return_value = ufp_client
ufp = MockUFPFixture(ufp_config_entry, ufp_client)
def subscribe(ws_callback: Callable[[WSSubscriptionMessage], None]) -> Any:
ufp.ws_subscription = ws_callback
return Mock()
def subscribe_websocket_state(
ws_state_subscription: Callable[[WebsocketState], None],
) -> Any:
ufp.ws_state_subscription = ws_state_subscription
return Mock()
ufp_client.subscribe_websocket = subscribe
ufp_client.subscribe_websocket_state = subscribe_websocket_state
yield ufp
@pytest.fixture
def liveview():
"""Mock UniFi Protect Liveview."""
data = json.loads(load_fixture("sample_liveview.json", integration=DOMAIN))
return Liveview.from_unifi_dict(**data)
@pytest.fixture(name="camera")
def camera_fixture(fixed_now: datetime):
"""Mock UniFi Protect Camera device."""
# disable pydantic validation so mocking can happen
Camera.model_config["validate_assignment"] = False
data = json.loads(load_fixture("sample_camera.json", integration=DOMAIN))
camera = Camera.from_unifi_dict(**data)
camera.last_motion = fixed_now - timedelta(hours=1)
yield camera
Camera.model_config["validate_assignment"] = True
@pytest.fixture(name="camera_all")
def camera_all_fixture(camera: Camera):
"""Mock UniFi Protect Camera device."""
all_camera = camera.model_copy()
all_camera.channels = [all_camera.channels[0].model_copy()]
medium_channel = all_camera.channels[0].model_copy()
medium_channel.name = "Medium"
medium_channel.id = 1
medium_channel.rtsp_alias = "test_medium_alias"
all_camera.channels.append(medium_channel)
low_channel = all_camera.channels[0].model_copy()
low_channel.name = "Low"
low_channel.id = 2
low_channel.rtsp_alias = "test_medium_alias"
all_camera.channels.append(low_channel)
return all_camera
@pytest.fixture(name="doorbell")
def doorbell_fixture(camera: Camera, fixed_now: datetime):
"""Mock UniFi Protect Camera device (with chime)."""
doorbell = camera.model_copy()
doorbell.channels = [c.model_copy() for c in doorbell.channels]
package_channel = doorbell.channels[0].model_copy()
package_channel.name = "Package Camera"
package_channel.id = 3
package_channel.fps = 2
package_channel.rtsp_alias = "test_package_alias"
doorbell.channels.append(package_channel)
doorbell.feature_flags.video_modes = [VideoMode.DEFAULT, VideoMode.HIGH_FPS]
doorbell.feature_flags.smart_detect_types = [
SmartDetectObjectType.PERSON,
SmartDetectObjectType.VEHICLE,
SmartDetectObjectType.ANIMAL,
SmartDetectObjectType.PACKAGE,
]
doorbell.has_speaker = True
doorbell.feature_flags.has_hdr = True
doorbell.feature_flags.has_lcd_screen = True
doorbell.feature_flags.has_speaker = True
doorbell.feature_flags.has_privacy_mask = True
doorbell.feature_flags.is_doorbell = True
doorbell.feature_flags.has_fingerprint_sensor = True
doorbell.feature_flags.support_nfc = True
doorbell.feature_flags.has_chime = True
doorbell.feature_flags.has_smart_detect = True
doorbell.feature_flags.has_package_camera = True
doorbell.feature_flags.has_led_status = True
doorbell.last_ring = fixed_now - timedelta(hours=1)
return doorbell
@pytest.fixture
def unadopted_camera(camera: Camera):
"""Mock UniFi Protect Camera device (unadopted)."""
no_camera = camera.model_copy()
no_camera.channels = [c.model_copy() for c in no_camera.channels]
no_camera.name = "Unadopted Camera"
no_camera.is_adopted = False
return no_camera
@pytest.fixture(name="light")
def light_fixture():
"""Mock UniFi Protect Light device."""
# disable pydantic validation so mocking can happen
Light.model_config["validate_assignment"] = False
data = json.loads(load_fixture("sample_light.json", integration=DOMAIN))
yield Light.from_unifi_dict(**data)
Light.model_config["validate_assignment"] = True
@pytest.fixture
def unadopted_light(light: Light):
"""Mock UniFi Protect Light device (unadopted)."""
no_light = light.model_copy()
no_light.name = "Unadopted Light"
no_light.is_adopted = False
return no_light
@pytest.fixture
def viewer():
"""Mock UniFi Protect Viewport device."""
# disable pydantic validation so mocking can happen
Viewer.model_config["validate_assignment"] = False
data = json.loads(load_fixture("sample_viewport.json", integration=DOMAIN))
yield Viewer.from_unifi_dict(**data)
Viewer.model_config["validate_assignment"] = True
@pytest.fixture(name="sensor")
def sensor_fixture(fixed_now: datetime):
"""Mock UniFi Protect Sensor device."""
# disable pydantic validation so mocking can happen
Sensor.model_config["validate_assignment"] = False
data = json.loads(load_fixture("sample_sensor.json", integration=DOMAIN))
sensor: Sensor = Sensor.from_unifi_dict(**data)
sensor.motion_detected_at = fixed_now - timedelta(hours=1)
sensor.open_status_changed_at = fixed_now - timedelta(hours=1)
sensor.alarm_triggered_at = fixed_now - timedelta(hours=1)
yield sensor
Sensor.model_config["validate_assignment"] = True
@pytest.fixture(name="sensor_all")
def csensor_all_fixture(sensor: Sensor):
"""Mock UniFi Protect Sensor device."""
all_sensor = sensor.model_copy()
all_sensor.light_settings.is_enabled = True
all_sensor.humidity_settings.is_enabled = True
all_sensor.temperature_settings.is_enabled = True
all_sensor.alarm_settings.is_enabled = True
all_sensor.led_settings.is_enabled = True
all_sensor.motion_settings.is_enabled = True
return all_sensor
@pytest.fixture(name="doorlock")
def doorlock_fixture():
"""Mock UniFi Protect Doorlock device."""
# disable pydantic validation so mocking can happen
Doorlock.model_config["validate_assignment"] = False
data = json.loads(load_fixture("sample_doorlock.json", integration=DOMAIN))
yield Doorlock.from_unifi_dict(**data)
Doorlock.model_config["validate_assignment"] = True
@pytest.fixture
def unadopted_doorlock(doorlock: Doorlock):
"""Mock UniFi Protect Light device (unadopted)."""
no_doorlock = doorlock.model_copy()
no_doorlock.name = "Unadopted Lock"
no_doorlock.is_adopted = False
return no_doorlock
@pytest.fixture
def chime():
"""Mock UniFi Protect Chime device."""
# disable pydantic validation so mocking can happen
Chime.model_config["validate_assignment"] = False
data = json.loads(load_fixture("sample_chime.json", integration=DOMAIN))
yield Chime.from_unifi_dict(**data)
Chime.model_config["validate_assignment"] = True
@pytest.fixture(name="fixed_now")
def fixed_now_fixture():
"""Return datetime object that will be consistent throughout test."""
return dt_util.utcnow()
@pytest.fixture(name="cloud_account")
def cloud_account() -> CloudAccount:
"""Return UI Cloud Account."""
return CloudAccount(
id="42",
first_name="Test",
last_name="User",
email="test@example.com",
user_id="42",
name="Test User",
location=None,
profile_img=None,
)

View File

@@ -0,0 +1,651 @@
{
"authUserId": "4c5f03a8c8bd48ad8e066285",
"accessKey": "8528571101220:340ff666bffb58bc404b859a:8f3f41a7b180b1ff7463fe4f7f13b528ac3d28668f25d0ecaa30c8e7888559e782b38d4335b40861030b75126eb7cea8385f3f9ab59dfa9a993e50757c277053",
"users": [
{
"permissions": [],
"lastLoginIp": null,
"lastLoginTime": null,
"isOwner": true,
"enableNotifications": false,
"settings": {
"flags": {}
},
"groups": ["b061186823695fb901973177"],
"alertRules": [],
"notificationsV2": {
"state": "custom",
"motionNotifications": {
"trigger": {
"when": "inherit",
"location": "away",
"schedules": []
},
"cameras": [
{
"inheritFromParent": true,
"motion": [],
"person": [],
"vehicle": [],
"camera": "61b3f5c7033ea703e7000424",
"trigger": {
"when": "always",
"location": "away",
"schedules": []
}
}
],
"doorbells": [],
"lights": [],
"doorlocks": [],
"sensors": []
},
"systemNotifications": {}
},
"featureFlags": {
"notificationsV2": true
},
"id": "fe4c12ae2c1348edb7854e2f",
"hasAcceptedInvite": true,
"allPermissions": [
"nvr:read:*",
"liveview:create",
"user:read,write,delete:$",
"nvr:write,delete:*",
"group:create,read,write,delete:*",
"user:create,read,write,delete:*",
"schedule:create,read,write,delete:*",
"legacyUFV:read,write,delete:*",
"bridge:create,read,write,delete:*",
"camera:create,read,write,delete,readmedia,readlive,deletemedia:*",
"light:create,read,write,delete:*",
"sensor:create,read,write,delete:*",
"doorlock:create,read,write,delete:*",
"viewer:create,read,write,delete:*",
"display:create,read,write,delete:*",
"chime:create,read,write,delete:*"
],
"cloudAccount": {
"firstName": "Qpvfly",
"lastName": "Ikjzilt",
"email": "QhoFvCv@example.com",
"profileImg": null,
"user": "fe4c12ae2c1348edb7854e2f",
"id": "9efc4511-4539-4402-9581-51cee8b65cf5",
"cloudId": "9efc4511-4539-4402-9581-51cee8b65cf5",
"name": "Qpvfly Ikjzilt",
"modelKey": "cloudIdentity"
},
"name": "Qpvfly Ikjzilt",
"firstName": "Qpvfly",
"lastName": "Ikjzilt",
"email": "QhoFvCv@example.com",
"localUsername": "QhoFvCv",
"modelKey": "user"
},
{
"permissions": [],
"lastLoginIp": null,
"lastLoginTime": null,
"isOwner": false,
"enableNotifications": false,
"settings": null,
"groups": ["a7f3b2eb71b4c4e56f1f45ac", "b061186823695fb901973177"],
"alertRules": [],
"notificationsV2": {
"state": "auto",
"motionNotifications": {
"trigger": {
"when": "inherit",
"location": "away",
"schedules": []
},
"cameras": [],
"doorbells": [],
"lights": [],
"doorlocks": [],
"sensors": []
},
"systemNotifications": {}
},
"featureFlags": {
"notificationsV2": true
},
"id": "dcaef9cb8aed05c7db658a46",
"hasAcceptedInvite": false,
"allPermissions": [
"nvr:read:*",
"liveview:create",
"user:read,write,delete:$",
"bridge:read:*",
"camera:read,readmedia,readlive:*",
"doorlock:read:*",
"light:read:*",
"sensor:read:*",
"viewer:read:*",
"display:read:*",
"chime:read:*",
"nvr:read:*",
"liveview:create",
"user:read,write,delete:$",
"nvr:write,delete:*",
"group:create,read,write,delete:*",
"user:create,read,write,delete:*",
"schedule:create,read,write,delete:*",
"legacyUFV:read,write,delete:*",
"bridge:create,read,write,delete:*",
"camera:create,read,write,delete,readmedia,readlive,deletemedia:*",
"light:create,read,write,delete:*",
"sensor:create,read,write,delete:*",
"doorlock:create,read,write,delete:*",
"viewer:create,read,write,delete:*",
"display:create,read,write,delete:*",
"chime:create,read,write,delete:*"
],
"cloudAccount": null,
"name": "Uxqg Wcbz",
"firstName": "Uxqg",
"lastName": "Wcbz",
"email": "epHDEhE@example.com",
"localUsername": "epHDEhE",
"modelKey": "user"
},
{
"permissions": [
"liveview:*:d65bb41c14d6aa92bfa4a6d1",
"liveview:*:49bbb5005424a0d35152671a",
"liveview:*:b28c38f1220f6b43f3930dff",
"liveview:*:b9861b533a87ea639fa4d438"
],
"lastLoginIp": null,
"lastLoginTime": null,
"isOwner": false,
"enableNotifications": false,
"settings": {
"flags": {},
"web": {
"dewarp": {
"61ddb66b018e2703e7008c19": {
"dewarp": false,
"state": {
"pan": 0,
"tilt": -1.5707963267948966,
"zoom": 1.5707963267948966,
"panning": 0,
"tilting": 0
}
}
},
"liveview.includeGlobal": true,
"elements.events_viewmode": "grid",
"elements.viewmode": "list"
}
},
"groups": ["b061186823695fb901973177"],
"location": {
"isAway": true,
"latitude": null,
"longitude": null
},
"alertRules": [],
"notificationsV2": {
"state": "custom",
"motionNotifications": {
"trigger": {
"when": "inherit",
"location": "away",
"schedules": []
},
"cameras": [
{
"inheritFromParent": true,
"motion": [],
"camera": "61b3f5c703d2a703e7000427",
"trigger": {
"when": "always",
"location": "away",
"schedules": []
}
},
{
"inheritFromParent": true,
"motion": [],
"person": [],
"vehicle": [],
"camera": "61b3f5c7033ea703e7000424",
"trigger": {
"when": "always",
"location": "away",
"schedules": []
}
}
],
"doorbells": [],
"lights": [],
"doorlocks": [],
"sensors": []
},
"systemNotifications": {}
},
"featureFlags": {
"notificationsV2": true
},
"id": "4c5f03a8c8bd48ad8e066285",
"hasAcceptedInvite": false,
"allPermissions": [
"liveview:*:d65bb41c14d6aa92bfa4a6d1",
"liveview:*:49bbb5005424a0d35152671a",
"liveview:*:b28c38f1220f6b43f3930dff",
"liveview:*:b9861b533a87ea639fa4d438",
"nvr:read:*",
"liveview:create",
"user:read,write,delete:$",
"nvr:write,delete:*",
"group:create,read,write,delete:*",
"user:create,read,write,delete:*",
"schedule:create,read,write,delete:*",
"legacyUFV:read,write,delete:*",
"bridge:create,read,write,delete:*",
"camera:create,read,write,delete,readmedia,readlive,deletemedia:*",
"light:create,read,write,delete:*",
"sensor:create,read,write,delete:*",
"doorlock:create,read,write,delete:*",
"viewer:create,read,write,delete:*",
"display:create,read,write,delete:*",
"chime:create,read,write,delete:*"
],
"cloudAccount": null,
"name": "Ptcmsdo Tfiyoep",
"firstName": "Ptcmsdo",
"lastName": "Tfiyoep",
"email": "EQAoXL@example.com",
"localUsername": "EQAoXL",
"modelKey": "user"
},
{
"permissions": [],
"lastLoginIp": null,
"lastLoginTime": null,
"isOwner": false,
"enableNotifications": false,
"settings": {
"flags": {},
"web": {
"dewarp": {
"61c4d1db02c82a03e700429c": {
"dewarp": false,
"state": {
"pan": 0,
"tilt": 0,
"zoom": 1.5707963267948966,
"panning": 0,
"tilting": 0
}
}
},
"liveview.includeGlobal": true
}
},
"groups": ["a7f3b2eb71b4c4e56f1f45ac"],
"alertRules": [],
"notificationsV2": {
"state": "auto",
"motionNotifications": {
"trigger": {
"when": "inherit",
"location": "away",
"schedules": []
},
"cameras": [],
"doorbells": [],
"lights": [],
"doorlocks": [],
"sensors": []
},
"systemNotifications": {}
},
"featureFlags": {
"notificationsV2": true
},
"id": "bc3dd633553907952a6fe20d",
"hasAcceptedInvite": false,
"allPermissions": [
"nvr:read:*",
"liveview:create",
"user:read,write,delete:$",
"bridge:read:*",
"camera:read,readmedia,readlive:*",
"doorlock:read:*",
"light:read:*",
"sensor:read:*",
"viewer:read:*",
"display:read:*",
"chime:read:*"
],
"cloudAccount": null,
"name": "Evdxou Zgyv",
"firstName": "Evdxou",
"lastName": "Zgyv",
"email": "FMZuD@example.com",
"localUsername": "FMZuD",
"modelKey": "user"
},
{
"permissions": [],
"lastLoginIp": null,
"lastLoginTime": null,
"isOwner": false,
"enableNotifications": false,
"settings": null,
"groups": ["a7f3b2eb71b4c4e56f1f45ac", "b061186823695fb901973177"],
"alertRules": [],
"notificationsV2": {
"state": "auto",
"motionNotifications": {
"trigger": {
"when": "inherit",
"location": "away",
"schedules": []
},
"cameras": [],
"doorbells": [],
"lights": [],
"doorlocks": [],
"sensors": []
},
"systemNotifications": {}
},
"featureFlags": {
"notificationsV2": true
},
"id": "adec5334b69f56f6a6c47520",
"hasAcceptedInvite": false,
"allPermissions": [
"nvr:read:*",
"liveview:create",
"user:read,write,delete:$",
"bridge:read:*",
"camera:read,readmedia,readlive:*",
"doorlock:read:*",
"light:read:*",
"sensor:read:*",
"viewer:read:*",
"display:read:*",
"chime:read:*",
"nvr:read:*",
"liveview:create",
"user:read,write,delete:$",
"nvr:write,delete:*",
"group:create,read,write,delete:*",
"user:create,read,write,delete:*",
"schedule:create,read,write,delete:*",
"legacyUFV:read,write,delete:*",
"bridge:create,read,write,delete:*",
"camera:create,read,write,delete,readmedia,readlive,deletemedia:*",
"light:create,read,write,delete:*",
"sensor:create,read,write,delete:*",
"doorlock:create,read,write,delete:*",
"viewer:create,read,write,delete:*",
"display:create,read,write,delete:*",
"chime:create,read,write,delete:*"
],
"cloudAccount": null,
"name": "Qpv Elqfgq",
"firstName": "Qpv",
"lastName": "Elqfgq",
"email": "xdr@example.com",
"localUsername": "xdr",
"modelKey": "user"
},
{
"permissions": [],
"lastLoginIp": null,
"lastLoginTime": null,
"isOwner": false,
"enableNotifications": false,
"settings": null,
"groups": ["a7f3b2eb71b4c4e56f1f45ac", "b061186823695fb901973177"],
"alertRules": [],
"notificationsV2": {
"state": "auto",
"motionNotifications": {
"trigger": {
"when": "inherit",
"location": "away",
"schedules": []
},
"cameras": [],
"doorbells": [],
"lights": [],
"doorlocks": [],
"sensors": []
},
"systemNotifications": {}
},
"featureFlags": {
"notificationsV2": true
},
"id": "8593657a25b7826a4288b6af",
"hasAcceptedInvite": false,
"allPermissions": [
"nvr:read:*",
"liveview:create",
"user:read,write,delete:$",
"bridge:read:*",
"camera:read,readmedia,readlive:*",
"doorlock:read:*",
"light:read:*",
"sensor:read:*",
"viewer:read:*",
"display:read:*",
"chime:read:*",
"nvr:read:*",
"liveview:create",
"user:read,write,delete:$",
"nvr:write,delete:*",
"group:create,read,write,delete:*",
"user:create,read,write,delete:*",
"schedule:create,read,write,delete:*",
"legacyUFV:read,write,delete:*",
"bridge:create,read,write,delete:*",
"camera:create,read,write,delete,readmedia,readlive,deletemedia:*",
"light:create,read,write,delete:*",
"sensor:create,read,write,delete:*",
"doorlock:create,read,write,delete:*",
"viewer:create,read,write,delete:*",
"display:create,read,write,delete:*",
"chime:create,read,write,delete:*"
],
"cloudAccount": null,
"name": "Sgpy Ooevsme",
"firstName": "Sgpy",
"lastName": "Ooevsme",
"email": "WQJNT@example.com",
"localUsername": "WQJNT",
"modelKey": "user"
},
{
"permissions": [],
"isOwner": false,
"enableNotifications": false,
"groups": ["a7f3b2eb71b4c4e56f1f45ac"],
"alertRules": [],
"notificationsV2": {
"state": "off",
"motionNotifications": {
"trigger": {
"when": "inherit",
"location": "away",
"schedules": []
},
"cameras": [],
"doorbells": [],
"lights": [],
"doorlocks": [],
"sensors": []
},
"systemNotifications": {}
},
"featureFlags": {
"notificationsV2": true
},
"id": "abf647aed3650a781ceba13f",
"hasAcceptedInvite": false,
"allPermissions": [
"nvr:read:*",
"liveview:create",
"user:read,write,delete:$",
"bridge:read:*",
"camera:read,readmedia,readlive:*",
"doorlock:read:*",
"light:read:*",
"sensor:read:*",
"viewer:read:*",
"display:read:*",
"chime:read:*"
],
"cloudAccount": null,
"name": "Yiiyq Glx",
"firstName": "Yiiyq",
"lastName": "Glx",
"email": "fBjmm@example.com",
"localUsername": "fBjmm",
"modelKey": "user"
}
],
"groups": [
{
"name": "Kubw Xnbb",
"permissions": [
"nvr:read:*",
"liveview:create",
"user:read,write,delete:$",
"nvr:write,delete:*",
"group:create,read,write,delete:*",
"user:create,read,write,delete:*",
"schedule:create,read,write,delete:*",
"legacyUFV:read,write,delete:*",
"bridge:create,read,write,delete:*",
"camera:create,read,write,delete,readmedia,readlive,deletemedia:*",
"light:create,read,write,delete:*",
"sensor:create,read,write,delete:*",
"doorlock:create,read,write,delete:*",
"viewer:create,read,write,delete:*",
"display:create,read,write,delete:*",
"chime:create,read,write,delete:*"
],
"type": "preset",
"isDefault": true,
"id": "b061186823695fb901973177",
"modelKey": "group"
},
{
"name": "Pmbrvp Wyzqs",
"permissions": [
"nvr:read:*",
"liveview:create",
"user:read,write,delete:$",
"bridge:read:*",
"camera:read,readmedia,readlive:*",
"doorlock:read:*",
"light:read:*",
"sensor:read:*",
"viewer:read:*",
"display:read:*",
"chime:read:*"
],
"type": "preset",
"isDefault": false,
"id": "a7f3b2eb71b4c4e56f1f45ac",
"modelKey": "group"
}
],
"schedules": [],
"legacyUFVs": [],
"lastUpdateId": "ebf25bac-d5a1-4f1d-a0ee-74c15981eb70",
"displays": [],
"ringtones": [
{
"id": "66a14fa502d44203e40003eb",
"name": "Default",
"size": 208,
"isDefault": true,
"nvrMac": "A1E00C826924",
"modelKey": "ringtone"
},
{
"id": "66a14fa502da4203e40003ec",
"name": "Traditional",
"size": 180,
"isDefault": false,
"nvrMac": "A1E00C826924",
"modelKey": "ringtone"
}
],
"bridges": [
{
"mac": "A28D0DB15AE1",
"host": "192.168.231.68",
"connectionHost": "192.168.102.63",
"type": "UFP-UAP-B",
"name": "Sffde Gxcaqe",
"upSince": 1639807977891,
"uptime": 3247782,
"lastSeen": 1643055759891,
"connectedSince": 1642374159304,
"state": "CONNECTED",
"hardwareRevision": 19,
"firmwareVersion": "0.3.1",
"latestFirmwareVersion": null,
"firmwareBuild": null,
"isUpdating": false,
"isAdopting": false,
"isAdopted": true,
"isAdoptedByOther": false,
"isProvisioned": false,
"isRebooting": false,
"isSshEnabled": false,
"canAdopt": false,
"isAttemptingToConnect": false,
"wiredConnectionState": {
"phyRate": null
},
"id": "1f5a055254fb9169d7536fb9",
"isConnected": true,
"platform": "mt7621",
"modelKey": "bridge"
},
{
"mac": "C65C557CCA95",
"host": "192.168.87.68",
"connectionHost": "192.168.102.63",
"type": "UFP-UAP-B",
"name": "Axiwj Bbd",
"upSince": 1641257260772,
"uptime": null,
"lastSeen": 1643052750862,
"connectedSince": 1643052754695,
"state": "CONNECTED",
"hardwareRevision": 19,
"firmwareVersion": "0.3.1",
"latestFirmwareVersion": null,
"firmwareBuild": null,
"isUpdating": false,
"isAdopting": false,
"isAdopted": true,
"isAdoptedByOther": false,
"isProvisioned": false,
"isRebooting": false,
"isSshEnabled": false,
"canAdopt": false,
"isAttemptingToConnect": false,
"wiredConnectionState": {
"phyRate": null
},
"id": "e6901e3665a4c0eab0d9c1a5",
"isConnected": true,
"platform": "mt7621",
"modelKey": "bridge"
}
]
}

View File

@@ -0,0 +1,370 @@
{
"isDeleting": false,
"mac": "72C7836A47DC",
"host": "192.168.6.90",
"connectionHost": "192.168.178.217",
"type": "UVC G4 Instant",
"name": "Test Camera",
"upSince": 1640020678036,
"uptime": 3203,
"lastSeen": 1640023881036,
"connectedSince": 1640020710448,
"state": "CONNECTED",
"hardwareRevision": "11",
"firmwareVersion": "4.47.13",
"latestFirmwareVersion": "4.47.13",
"firmwareBuild": "0a55423.211124.718",
"isUpdating": false,
"isAdopting": false,
"isAdopted": true,
"isAdoptedByOther": false,
"isProvisioned": true,
"isRebooting": false,
"isSshEnabled": false,
"canAdopt": false,
"isAttemptingToConnect": false,
"lastMotion": 1640021213927,
"micVolume": 1,
"isMicEnabled": true,
"isRecording": false,
"isWirelessUplinkEnabled": true,
"isMotionDetected": false,
"isSmartDetected": false,
"phyRate": 72,
"hdrMode": false,
"videoMode": "default",
"isProbingForWifi": false,
"apMac": null,
"apRssi": null,
"elementInfo": null,
"chimeDuration": 0,
"isDark": false,
"lastPrivacyZonePositionId": null,
"lastRing": null,
"isLiveHeatmapEnabled": false,
"anonymousDeviceId": "7722b5e7-ecfa-468c-a385-3eafea917b0c",
"eventStats": {
"motion": {
"today": 10,
"average": 39,
"lastDays": [48, 45, 33, 41, 44, 60, 6],
"recentHours": [0, 4, 1, 2, 0, 0, 0, 0, 0, 0, 2, 0, 0]
},
"smart": {
"today": 0,
"average": 0,
"lastDays": [0, 0, 0, 0, 0, 0, 0]
}
},
"videoReconfigurationInProgress": false,
"voltage": 20.0,
"wiredConnectionState": {
"phyRate": 1000
},
"channels": [
{
"id": 0,
"videoId": "video1",
"name": "High",
"enabled": true,
"isRtspEnabled": true,
"rtspAlias": "test_high_alias",
"width": 2688,
"height": 1512,
"fps": 30,
"bitrate": 10000000,
"minBitrate": 32000,
"maxBitrate": 10000000,
"minClientAdaptiveBitRate": 0,
"minMotionAdaptiveBitRate": 2000000,
"fpsValues": [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 30],
"idrInterval": 5
},
{
"id": 1,
"videoId": "video2",
"name": "Medium",
"enabled": true,
"isRtspEnabled": false,
"rtspAlias": null,
"width": 1280,
"height": 720,
"fps": 30,
"bitrate": 1500000,
"minBitrate": 32000,
"maxBitrate": 2000000,
"minClientAdaptiveBitRate": 150000,
"minMotionAdaptiveBitRate": 750000,
"fpsValues": [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 30],
"idrInterval": 5
},
{
"id": 2,
"videoId": "video3",
"name": "Low",
"enabled": true,
"isRtspEnabled": false,
"rtspAlias": null,
"width": 640,
"height": 360,
"fps": 30,
"bitrate": 200000,
"minBitrate": 32000,
"maxBitrate": 1000000,
"minClientAdaptiveBitRate": 0,
"minMotionAdaptiveBitRate": 200000,
"fpsValues": [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 30],
"idrInterval": 5
}
],
"ispSettings": {
"aeMode": "auto",
"irLedMode": "auto",
"irLedLevel": 255,
"wdr": 1,
"icrSensitivity": 0,
"brightness": 50,
"contrast": 50,
"hue": 50,
"saturation": 50,
"sharpness": 50,
"denoise": 50,
"isFlippedVertical": false,
"isFlippedHorizontal": false,
"isAutoRotateEnabled": true,
"isLdcEnabled": true,
"is3dnrEnabled": true,
"isExternalIrEnabled": false,
"isAggressiveAntiFlickerEnabled": false,
"isPauseMotionEnabled": false,
"dZoomCenterX": 50,
"dZoomCenterY": 50,
"dZoomScale": 0,
"dZoomStreamId": 4,
"focusMode": "ztrig",
"focusPosition": 0,
"touchFocusX": 1001,
"touchFocusY": 1001,
"zoomPosition": 1,
"mountPosition": "wall"
},
"talkbackSettings": {
"typeFmt": "aac",
"typeIn": "serverudp",
"bindAddr": "0.0.0.0",
"bindPort": 7004,
"filterAddr": "",
"filterPort": 0,
"channels": 1,
"samplingRate": 22050,
"bitsPerSample": 16,
"quality": 100
},
"osdSettings": {
"isNameEnabled": false,
"isDateEnabled": false,
"isLogoEnabled": false,
"isDebugEnabled": false
},
"ledSettings": {
"isEnabled": false,
"blinkRate": 0
},
"speakerSettings": {
"isEnabled": true,
"areSystemSoundsEnabled": false,
"volume": 100
},
"recordingSettings": {
"prePaddingSecs": 10,
"postPaddingSecs": 10,
"minMotionEventTrigger": 1000,
"endMotionEventDelay": 3000,
"suppressIlluminationSurge": false,
"mode": "always",
"geofencing": "off",
"motionAlgorithm": "enhanced",
"enablePirTimelapse": false,
"useNewMotionAlgorithm": true
},
"smartDetectSettings": {
"objectTypes": []
},
"recordingSchedules": [],
"motionZones": [
{
"id": 1,
"name": "Default",
"color": "#AB46BC",
"points": [
[0, 0],
[1, 0],
[1, 1],
[0, 1]
],
"sensitivity": 50
}
],
"privacyZones": [],
"smartDetectZones": [
{
"id": 1,
"name": "Default",
"color": "#AB46BC",
"points": [
[0, 0],
[1, 0],
[1, 1],
[0, 1]
],
"sensitivity": 50,
"objectTypes": []
}
],
"smartDetectLines": [],
"stats": {
"rxBytes": 100,
"txBytes": 100,
"wifi": {
"channel": 6,
"frequency": 2437,
"linkSpeedMbps": null,
"signalQuality": 100,
"signalStrength": -35
},
"battery": {
"percentage": null,
"isCharging": false,
"sleepState": "disconnected"
},
"video": {
"recordingStart": 1639219284079,
"recordingEnd": 1640021215245,
"recordingStartLQ": 1639219283987,
"recordingEndLQ": 1640021217213,
"timelapseStart": 1639219284030,
"timelapseEnd": 1640023738713,
"timelapseStartLQ": 1639219284030,
"timelapseEndLQ": 1640021765237
},
"storage": {
"used": 100,
"rate": 0.1
},
"wifiQuality": 100,
"wifiStrength": -35
},
"featureFlags": {
"canAdjustIrLedLevel": false,
"canMagicZoom": false,
"canOpticalZoom": true,
"canTouchFocus": false,
"hasAccelerometer": true,
"hasAec": true,
"hasBattery": false,
"hasBluetooth": true,
"hasChime": false,
"hasExternalIr": false,
"hasIcrSensitivity": true,
"hasLdc": false,
"hasLedIr": true,
"hasLedStatus": false,
"hasLineIn": false,
"hasMic": true,
"hasPrivacyMask": false,
"hasRtc": false,
"hasSdCard": false,
"hasSpeaker": false,
"hasWifi": true,
"hasHdr": false,
"hasAutoICROnly": true,
"videoModes": ["default"],
"videoModeMaxFps": [],
"hasMotionZones": true,
"hasLcdScreen": false,
"mountPositions": [],
"smartDetectTypes": [],
"motionAlgorithms": ["enhanced"],
"hasSquareEventThumbnail": true,
"hasPackageCamera": false,
"privacyMaskCapability": {
"maxMasks": 4,
"rectangleOnly": true
},
"focus": {
"steps": {
"max": null,
"min": null,
"step": null
},
"degrees": {
"max": null,
"min": null,
"step": null
}
},
"pan": {
"steps": {
"max": null,
"min": null,
"step": null
},
"degrees": {
"max": null,
"min": null,
"step": null
}
},
"tilt": {
"steps": {
"max": null,
"min": null,
"step": null
},
"degrees": {
"max": null,
"min": null,
"step": null
}
},
"zoom": {
"steps": {
"max": null,
"min": null,
"step": null
},
"degrees": {
"max": null,
"min": null,
"step": null
}
},
"hasSmartDetect": false
},
"pirSettings": {
"pirSensitivity": 100,
"pirMotionClipLength": 15,
"timelapseFrameInterval": 15,
"timelapseTransferInterval": 600
},
"lcdMessage": {},
"wifiConnectionState": {
"channel": 6,
"frequency": 2437,
"phyRate": 72,
"signalQuality": 100,
"signalStrength": -50,
"ssid": "Mortis Camera"
},
"lenses": [],
"id": "0de062b4f6922d489d3b312d",
"isConnected": true,
"platform": "sav530q",
"hasSpeaker": false,
"hasWifi": true,
"audioBitrate": 64000,
"canManage": false,
"isManaged": true,
"marketName": "G4 Instant",
"modelKey": "camera"
}

View File

@@ -0,0 +1,48 @@
{
"mac": "BEEEE2FBE413",
"host": "192.168.144.146",
"connectionHost": "192.168.234.27",
"type": "UP Chime",
"name": "Test Chime",
"upSince": 1651882870009,
"uptime": 567870,
"lastSeen": 1652450740009,
"connectedSince": 1652448904587,
"state": "CONNECTED",
"hardwareRevision": null,
"firmwareVersion": "1.3.4",
"latestFirmwareVersion": "1.3.4",
"firmwareBuild": "58bd350.220401.1859",
"isUpdating": false,
"isAdopting": false,
"isAdopted": true,
"isAdoptedByOther": false,
"isProvisioned": false,
"isRebooting": false,
"isSshEnabled": true,
"canAdopt": false,
"isAttemptingToConnect": false,
"volume": 100,
"isProbingForWifi": false,
"apMac": null,
"apRssi": null,
"elementInfo": null,
"lastRing": 1652116059940,
"isWirelessUplinkEnabled": true,
"wiredConnectionState": {
"phyRate": null
},
"wifiConnectionState": {
"channel": null,
"frequency": null,
"phyRate": null,
"signalQuality": 100,
"signalStrength": -44,
"ssid": null
},
"cameraIds": [],
"id": "cf1a330397c08f919d02bd7c",
"isConnected": true,
"marketName": "UP Chime",
"modelKey": "chime"
}

View File

@@ -0,0 +1,52 @@
{
"mac": "F10599AB6955",
"host": null,
"connectionHost": "192.168.102.63",
"type": "UFP-LOCK-R",
"name": "Test Lock",
"upSince": 1643050461849,
"uptime": null,
"lastSeen": 1643052750858,
"connectedSince": 1643052765849,
"state": "CONNECTED",
"hardwareRevision": 7,
"firmwareVersion": "1.2.0",
"latestFirmwareVersion": "1.2.0",
"firmwareBuild": null,
"isUpdating": false,
"isAdopting": false,
"isAdopted": true,
"isAdoptedByOther": false,
"isProvisioned": false,
"isRebooting": false,
"isSshEnabled": false,
"canAdopt": false,
"isAttemptingToConnect": false,
"credentials": "955756200c7f43936df9d5f7865f058e1528945aac0f0cb27cef960eb58f17db",
"lockStatus": "OPEN",
"enableHomekit": false,
"autoCloseTimeMs": 45000,
"wiredConnectionState": {
"phyRate": null
},
"ledSettings": {
"isEnabled": true
},
"bluetoothConnectionState": {
"signalQuality": 62,
"signalStrength": -65
},
"batteryStatus": {
"percentage": 100,
"isLow": false
},
"bridge": "61b3f5c90050a703e700042a",
"camera": "e2ff0ade6be0f2a2beb61869",
"bridgeCandidates": [],
"id": "1c812e80fd693ab51535be38",
"isConnected": true,
"hasHomekit": false,
"marketName": "UP DoorLock",
"modelKey": "doorlock",
"privateToken": "MsjIV0UUpMWuAQZvJnCOfC1K9UAfgqDKCIcWtANWIuW66OXLwSgMbNEG2MEkL2TViSkMbJvFxAQEyHU0EJeVCWzY6dGHGuKXFXZMqJWZivBGDC8JoXiRxNIBqHZtXQKXZIoXWKLmhBL7SDxLoFNYEYNNLUGKGFBBGX2oNLi8KRW3SDSUTTWJZNwAUs8GKeJJ"
}

View File

@@ -0,0 +1,53 @@
{
"mac": "D7F1C8D3FCDD",
"host": "192.168.10.86",
"connectionHost": "192.168.178.217",
"type": "UP FloodLight",
"name": "Test Light",
"upSince": 1638128991022,
"uptime": 1894890,
"lastSeen": 1640023881022,
"connectedSince": 1640020579711,
"state": "CONNECTED",
"hardwareRevision": null,
"firmwareVersion": "1.9.3",
"latestFirmwareVersion": "1.9.3",
"firmwareBuild": "g990c553.211105.251",
"isUpdating": false,
"isAdopting": false,
"isAdopted": true,
"isAdoptedByOther": false,
"isProvisioned": false,
"isRebooting": false,
"isSshEnabled": false,
"canAdopt": false,
"isAttemptingToConnect": false,
"isPirMotionDetected": false,
"lastMotion": 1640022006069,
"isDark": false,
"isLightOn": false,
"isLocating": false,
"wiredConnectionState": {
"phyRate": 100
},
"lightDeviceSettings": {
"isIndicatorEnabled": false,
"ledLevel": 6,
"luxSensitivity": "medium",
"pirDuration": 45000,
"pirSensitivity": 45
},
"lightOnSettings": {
"isLedForceOn": false
},
"lightModeSettings": {
"mode": "motion",
"enableAt": "fulltime"
},
"camera": null,
"id": "37dd610720816cfb5c547967",
"isConnected": true,
"isCameraPaired": true,
"marketName": "UP FloodLight",
"modelKey": "light"
}

View File

@@ -0,0 +1,56 @@
{
"name": "Default",
"isDefault": true,
"isGlobal": true,
"layout": 9,
"slots": [
{
"cameras": ["0488c1538efb5cc9f73f77ca"],
"cycleMode": "time",
"cycleInterval": 10
},
{
"cameras": ["0de062b4f6922d489d3b312d"],
"cycleMode": "time",
"cycleInterval": 10
},
{
"cameras": ["193be66559c03ec5629f54cd"],
"cycleMode": "time",
"cycleInterval": 10
},
{
"cameras": ["16b0c551e36d872806f2806b"],
"cycleMode": "time",
"cycleInterval": 10
},
{
"cameras": ["5becd64d90f1cae3a4146a0f"],
"cycleMode": "time",
"cycleInterval": 10
},
{
"cameras": ["4f5fab885aca3f7c226b22b9"],
"cycleMode": "time",
"cycleInterval": 10
},
{
"cameras": ["cc7a572a0a8677baae933873"],
"cycleMode": "time",
"cycleInterval": 10
},
{
"cameras": ["f4e9f4421209908c51284e67"],
"cycleMode": "time",
"cycleInterval": 10
},
{
"cameras": [],
"cycleMode": "time",
"cycleInterval": 10
}
],
"owner": "5a839670ad0a929bf8271c26",
"id": "ecb21f15e6d8fae65fea82f8",
"modelKey": "liveview"
}

View File

@@ -0,0 +1,363 @@
{
"mac": "A1E00C826924",
"host": "192.168.216.198",
"name": "UnifiProtect",
"canAutoUpdate": true,
"isStatsGatheringEnabled": true,
"timezone": "America/New_York",
"version": "2.2.6",
"ucoreVersion": "2.3.26",
"firmwareVersion": "2.3.10",
"uiVersion": null,
"hardwarePlatform": "al324",
"ports": {
"ump": 7449,
"http": 7080,
"https": 7443,
"rtsp": 7447,
"rtsps": 7441,
"rtmp": 1935,
"devicesWss": 7442,
"cameraHttps": 7444,
"cameraTcp": 7877,
"liveWs": 7445,
"liveWss": 7446,
"tcpStreams": 7448,
"playback": 7450,
"emsCLI": 7440,
"emsLiveFLV": 7550,
"cameraEvents": 7551,
"tcpBridge": 7888,
"ucore": 11081,
"discoveryClient": 0
},
"uptime": 1191516000,
"lastSeen": 1641269019283,
"isUpdating": false,
"lastUpdateAt": null,
"isStation": false,
"enableAutomaticBackups": true,
"enableStatsReporting": false,
"isSshEnabled": false,
"errorCode": null,
"releaseChannel": "release",
"ssoChannel": null,
"hosts": ["192.168.216.198"],
"enableBridgeAutoAdoption": true,
"hardwareId": "baf4878d-df21-4427-9fbe-c2ef15301412",
"hardwareRevision": "113-03137-22",
"hostType": 59936,
"hostShortname": "UNVRPRO",
"isHardware": true,
"isWirelessUplinkEnabled": false,
"timeFormat": "24h",
"temperatureUnit": "C",
"recordingRetentionDurationMs": null,
"enableCrashReporting": true,
"disableAudio": false,
"analyticsData": "anonymous",
"isInsightsEnabled": true,
"anonymousDeviceId": "65257f7d-874c-498a-8f1b-00b2dd0a7ae1",
"cameraUtilization": 30,
"isRecycling": false,
"avgMotions": [
21.29, 14, 5.43, 2.29, 6.43, 7.43, 16.86, 17, 24.71, 36.86, 46.43, 47.57,
51.57, 52.71, 63.86, 80.86, 86.71, 91.71, 96.57, 71.14, 57, 53.71, 39.57,
21.29
],
"disableAutoLink": false,
"skipFirmwareUpdate": false,
"wifiSettings": {
"useThirdPartyWifi": false,
"ssid": null,
"password": null
},
"locationSettings": {
"isAway": true,
"isGeofencingEnabled": false,
"latitude": 41.4519,
"longitude": -81.921,
"radius": 200
},
"featureFlags": {
"beta": false,
"dev": false,
"notificationsV2": true
},
"systemInfo": {
"cpu": {
"averageLoad": 5,
"temperature": 70
},
"memory": {
"available": 6481504,
"free": 87080,
"total": 8163024
},
"storage": {
"available": 21796939214848,
"isRecycling": false,
"size": 31855989432320,
"type": "raid",
"used": 8459815895040,
"devices": [
{
"model": "ST16000VE000-2L2103",
"size": 16000900661248,
"healthy": true
},
{
"model": "ST16000VE000-2L2103",
"size": 16000900661248,
"healthy": true
},
{
"model": "ST16000VE000-2L2103",
"size": 16000900661248,
"healthy": true
}
]
},
"ustorage": {
"disks": [
{
"slot": 1,
"type": "HDD",
"model": "ST16000VE000-2L2103",
"serial": "ABCD1234",
"firmware": "EV02",
"rpm": 7200,
"ata": "ACS-4",
"sata": "SATA 3.3",
"action": "expanding",
"healthy": "good",
"state": "expanding",
"reason": null,
"temperature": 52,
"poweronhrs": 4242,
"life_span": null,
"bad_sector": 0,
"threshold": 10,
"progress": 21.390607518939174,
"estimate": 234395.73300748435
},
{
"slot": 2,
"type": "HDD",
"model": "ST16000VE000-2L2103",
"serial": "ABCD1234",
"firmware": "EV02",
"rpm": 7200,
"ata": "ACS-4",
"sata": "SATA 3.3",
"action": "expanding",
"healthy": "good",
"state": "expanding",
"reason": null,
"temperature": 52,
"poweronhrs": 4242,
"life_span": null,
"bad_sector": 0,
"threshold": 10,
"progress": 21.390607518939174,
"estimate": 234395.73300748435
},
{
"slot": 3,
"type": "HDD",
"model": "ST16000VE000-2L2103",
"serial": "ABCD1234",
"firmware": "EV02",
"rpm": 7200,
"ata": "ACS-4",
"sata": "SATA 3.3",
"action": "expanding",
"healthy": "good",
"state": "expanding",
"reason": null,
"temperature": 51,
"poweronhrs": 4242,
"life_span": null,
"bad_sector": 0,
"threshold": 10,
"progress": 21.390607518939174,
"estimate": 234395.73300748435
},
{
"slot": 4,
"type": "HDD",
"model": "ST16000VE000-2L2103",
"serial": "ABCD1234",
"firmware": "EV02",
"rpm": 7200,
"ata": "ACS-4",
"sata": "SATA 3.3",
"action": "expanding",
"healthy": "good",
"state": "expanding",
"reason": null,
"temperature": 50,
"poweronhrs": 2443,
"life_span": null,
"bad_sector": 0,
"threshold": 10,
"progress": 21.390607518939174,
"estimate": 234395.73300748435
},
{
"slot": 5,
"type": "HDD",
"model": "ST16000VE000-2L2103",
"serial": "ABCD1234",
"firmware": "EV02",
"rpm": 7200,
"ata": "ACS-4",
"sata": "SATA 3.3",
"action": "expanding",
"healthy": "good",
"state": "expanding",
"reason": null,
"temperature": 50,
"poweronhrs": 783,
"life_span": null,
"bad_sector": 0,
"threshold": 10,
"progress": 21.390607518939174,
"estimate": 234395.73300748435
},
{
"slot": 6,
"state": "nodisk"
},
{
"slot": 7,
"type": "HDD",
"model": "ST16000VE002-3BR101",
"serial": "ABCD1234",
"firmware": "EV01",
"rpm": 7200,
"ata": "ACS-4",
"sata": "SATA 3.3",
"action": "expanding",
"healthy": "good",
"state": "expanding",
"reason": null,
"temperature": 45,
"poweronhrs": 18,
"life_span": null,
"bad_sector": 0,
"threshold": 10,
"progress": 21.390607518939174,
"estimate": 234395.73300748435
}
],
"space": [
{
"device": "md3",
"total_bytes": 63713403555840,
"used_bytes": 57006577086464,
"action": "expanding",
"progress": 21.390607518939174,
"estimate": 234395.73300748435
},
{
"device": "md0",
"total_bytes": 0,
"used_bytes": 0,
"action": "syncing",
"progress": 0,
"estimate": null
}
]
},
"tmpfs": {
"available": 934204,
"total": 1048576,
"used": 114372,
"path": "/var/opt/unifi-protect/tmp"
}
},
"doorbellSettings": {
"defaultMessageText": "Welcome",
"defaultMessageResetTimeoutMs": 60000,
"customMessages": ["Come In!", "Use Other Door"],
"allMessages": [
{
"type": "LEAVE_PACKAGE_AT_DOOR",
"text": "LEAVE PACKAGE AT DOOR"
},
{
"type": "DO_NOT_DISTURB",
"text": "DO NOT DISTURB"
},
{
"type": "CUSTOM_MESSAGE",
"text": "Test"
}
]
},
"smartDetectAgreement": {
"status": "agreed",
"lastUpdateAt": 1606964227734
},
"storageStats": {
"utilization": 26.61384533704469,
"capacity": 5706909122,
"remainingCapacity": 4188081155,
"recordingSpace": {
"total": 31787269955584,
"used": 8459814862848,
"available": 23327455092736
},
"storageDistribution": {
"recordingTypeDistributions": [
{
"recordingType": "rotating",
"size": 7736989099040,
"percentage": 91.47686438351941
},
{
"recordingType": "timelapse",
"size": 21474836480,
"percentage": 0.2539037704709915
},
{
"recordingType": "detections",
"size": 699400412128,
"percentage": 8.269231846009593
}
],
"resolutionDistributions": [
{
"resolution": "HD",
"size": 2896955441152,
"percentage": 9.113571077981481
},
{
"resolution": "4K",
"size": 5560908906496,
"percentage": 17.494138107066746
},
{
"resolution": "free",
"size": 23329405607936,
"percentage": 73.39229081495176
}
]
}
},
"id": "test_id",
"isAway": true,
"isSetup": true,
"network": "Ethernet",
"type": "UNVR-PRO",
"upSince": 1640077503063,
"isRecordingDisabled": false,
"isRecordingMotionOnly": false,
"maxCameraCapacity": {
"4K": 20,
"2K": 30,
"HD": 60
},
"modelKey": "nvr"
}

View File

@@ -0,0 +1,92 @@
{
"mac": "26DBAFF133A4",
"connectionHost": "192.168.216.198",
"type": "UFP-SENSE",
"name": "Test Sensor",
"upSince": 1641256963255,
"uptime": null,
"lastSeen": 1641259127934,
"connectedSince": 1641259139255,
"state": "CONNECTED",
"hardwareRevision": 6,
"firmwareVersion": "1.0.2",
"latestFirmwareVersion": "1.0.2",
"firmwareBuild": null,
"isUpdating": false,
"isAdopting": false,
"isAdopted": true,
"isAdoptedByOther": false,
"isProvisioned": false,
"isRebooting": false,
"isSshEnabled": false,
"canAdopt": false,
"isAttemptingToConnect": false,
"isMotionDetected": false,
"mountType": "door",
"leakDetectedAt": null,
"tamperingDetectedAt": null,
"isOpened": false,
"openStatusChangedAt": 1641269036582,
"alarmTriggeredAt": null,
"motionDetectedAt": 1641269044824,
"wiredConnectionState": {
"phyRate": null
},
"stats": {
"light": {
"value": 10.0,
"status": "neutral"
},
"humidity": {
"value": 10.0,
"status": "neutral"
},
"temperature": {
"value": 10.0,
"status": "neutral"
}
},
"bluetoothConnectionState": {
"signalQuality": 15,
"signalStrength": -50
},
"batteryStatus": {
"percentage": 10,
"isLow": false
},
"alarmSettings": {
"isEnabled": false
},
"lightSettings": {
"isEnabled": false,
"lowThreshold": null,
"highThreshold": null,
"margin": 10
},
"motionSettings": {
"isEnabled": false,
"sensitivity": 100
},
"temperatureSettings": {
"isEnabled": false,
"lowThreshold": null,
"highThreshold": null,
"margin": 0.1
},
"humiditySettings": {
"isEnabled": false,
"lowThreshold": null,
"highThreshold": null,
"margin": 1
},
"ledSettings": {
"isEnabled": false
},
"bridge": "61b3f5c90050a703e700042a",
"camera": "2f9beb2e6f79af3c32c22d49",
"bridgeCandidates": [],
"id": "f6ecbe829f81cc79ad6e0c9a",
"isConnected": true,
"marketName": "UP Sense",
"modelKey": "sensor"
}

View File

@@ -0,0 +1,35 @@
{
"mac": "4EDC1B6D2F76",
"host": "192.168.34.145",
"connectionHost": "192.168.178.217",
"type": "UP Viewport",
"name": "Yfptv Ttklkw",
"upSince": 1639845760126,
"uptime": 178121,
"lastSeen": 1640023881126,
"connectedSince": 1640020660049,
"state": "CONNECTED",
"hardwareRevision": null,
"firmwareVersion": "1.2.54",
"latestFirmwareVersion": "1.2.54",
"firmwareBuild": "dcfb16f3.210907.625",
"isUpdating": false,
"isAdopting": false,
"isAdopted": true,
"isAdoptedByOther": false,
"isProvisioned": false,
"isRebooting": false,
"isSshEnabled": false,
"canAdopt": false,
"isAttemptingToConnect": false,
"streamLimit": 16,
"softwareVersion": "1.2.54",
"wiredConnectionState": {
"phyRate": 1000
},
"liveview": "ecb21f15e6d8fae65fea82f8",
"id": "5ec2a22846047eeb6e976922",
"isConnected": true,
"marketName": "UP ViewPort",
"modelKey": "viewer"
}

View File

@@ -0,0 +1,723 @@
"""Test the UniFi Protect binary_sensor platform."""
from __future__ import annotations
from datetime import datetime, timedelta
from unittest.mock import Mock
import pytest
from uiprotect.data import (
Camera,
Event,
EventType,
Light,
ModelType,
MountType,
Sensor,
SmartDetectObjectType,
)
from uiprotect.data.nvr import EventMetadata
from homeassistant.components.binary_sensor import BinarySensorDeviceClass
from homeassistant.components.unifiprotect.binary_sensor import (
CAMERA_SENSORS,
EVENT_SENSORS,
LIGHT_SENSORS,
MOUNTABLE_SENSE_SENSORS,
SENSE_SENSORS,
)
from homeassistant.components.unifiprotect.const import (
ATTR_EVENT_SCORE,
DEFAULT_ATTRIBUTION,
)
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_DEVICE_CLASS,
EVENT_STATE_CHANGED,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
Platform,
)
from homeassistant.core import Event as HAEvent, EventStateChangedData, HomeAssistant
from homeassistant.helpers import entity_registry as er
from .utils import (
MockUFPFixture,
adopt_devices,
assert_entity_counts,
ids_from_device_description,
init_entry,
remove_entities,
)
from tests.common import async_capture_events
LIGHT_SENSOR_WRITE = LIGHT_SENSORS[:2]
SENSE_SENSORS_WRITE = SENSE_SENSORS[:3]
async def test_binary_sensor_camera_remove(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera, unadopted_camera: Camera
) -> None:
"""Test removing and re-adding a camera device."""
ufp.api.bootstrap.nvr.system_info.ustorage = None
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 9, 6)
await remove_entities(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 0, 0)
await adopt_devices(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 9, 6)
async def test_binary_sensor_light_remove(
hass: HomeAssistant, ufp: MockUFPFixture, light: Light
) -> None:
"""Test removing and re-adding a light device."""
ufp.api.bootstrap.nvr.system_info.ustorage = None
await init_entry(hass, ufp, [light])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 2, 2)
await remove_entities(hass, ufp, [light])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 0, 0)
await adopt_devices(hass, ufp, [light])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 2, 2)
async def test_binary_sensor_sensor_remove(
hass: HomeAssistant, ufp: MockUFPFixture, sensor_all: Sensor
) -> None:
"""Test removing and re-adding a light device."""
ufp.api.bootstrap.nvr.system_info.ustorage = None
await init_entry(hass, ufp, [sensor_all])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 5, 5)
await remove_entities(hass, ufp, [sensor_all])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 0, 0)
await adopt_devices(hass, ufp, [sensor_all])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 5, 5)
async def test_binary_sensor_setup_light(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
light: Light,
) -> None:
"""Test binary_sensor entity setup for light devices."""
await init_entry(hass, ufp, [light])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 8, 8)
for description in LIGHT_SENSOR_WRITE:
unique_id, entity_id = ids_from_device_description(
Platform.BINARY_SENSOR, light, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_binary_sensor_setup_camera_all(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
) -> None:
"""Test binary_sensor entity setup for camera devices (all features)."""
ufp.api.bootstrap.nvr.system_info.ustorage = None
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 9, 6)
description = EVENT_SENSORS[0]
unique_id, entity_id = ids_from_device_description(
Platform.BINARY_SENSOR, doorbell, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
# Is Dark
description = CAMERA_SENSORS[0]
unique_id, entity_id = ids_from_device_description(
Platform.BINARY_SENSOR, doorbell, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
# Motion
description = EVENT_SENSORS[1]
unique_id, entity_id = ids_from_device_description(
Platform.BINARY_SENSOR, doorbell, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_binary_sensor_setup_camera_none(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
camera: Camera,
) -> None:
"""Test binary_sensor entity setup for camera devices (no features)."""
ufp.api.bootstrap.nvr.system_info.ustorage = None
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 2, 2)
description = CAMERA_SENSORS[0]
unique_id, entity_id = ids_from_device_description(
Platform.BINARY_SENSOR, camera, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_binary_sensor_setup_sensor(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
sensor_all: Sensor,
) -> None:
"""Test binary_sensor entity setup for sensor devices."""
await init_entry(hass, ufp, [sensor_all])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 11, 11)
expected = [
STATE_UNAVAILABLE,
STATE_OFF,
STATE_OFF,
STATE_OFF,
]
for index, description in enumerate(SENSE_SENSORS_WRITE):
unique_id, entity_id = ids_from_device_description(
Platform.BINARY_SENSOR, sensor_all, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == expected[index]
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_binary_sensor_setup_sensor_leak(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
sensor: Sensor,
) -> None:
"""Test binary_sensor entity setup for sensor with most leak mounting type."""
sensor.mount_type = MountType.LEAK
await init_entry(hass, ufp, [sensor])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 11, 11)
expected = [
STATE_OFF,
STATE_OFF,
STATE_UNAVAILABLE,
STATE_OFF,
]
for index, description in enumerate(SENSE_SENSORS_WRITE):
unique_id, entity_id = ids_from_device_description(
Platform.BINARY_SENSOR, sensor, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == expected[index]
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_binary_sensor_update_motion(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
fixed_now: datetime,
) -> None:
"""Test binary_sensor motion entity."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 15, 12)
_, entity_id = ids_from_device_description(
Platform.BINARY_SENSOR, doorbell, EVENT_SENSORS[1]
)
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.MOTION,
start=fixed_now - timedelta(seconds=1),
end=None,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
camera_id=doorbell.id,
api=ufp.api,
)
new_camera = doorbell.model_copy()
new_camera.is_motion_detected = True
new_camera.last_motion_event_id = event.id
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_ON
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
assert state.attributes[ATTR_EVENT_SCORE] == 100
async def test_binary_sensor_update_light_motion(
hass: HomeAssistant, ufp: MockUFPFixture, light: Light, fixed_now: datetime
) -> None:
"""Test binary_sensor motion entity."""
await init_entry(hass, ufp, [light])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 8, 8)
_, entity_id = ids_from_device_description(
Platform.BINARY_SENSOR, light, LIGHT_SENSOR_WRITE[1]
)
event_metadata = EventMetadata(light_id=light.id)
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.MOTION_LIGHT,
start=fixed_now - timedelta(seconds=1),
end=None,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
metadata=event_metadata,
api=ufp.api,
)
new_light = light.model_copy()
new_light.is_pir_motion_detected = True
new_light.last_motion_event_id = event.id
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
ufp.api.bootstrap.lights = {new_light.id: new_light}
ufp.api.bootstrap.events = {event.id: event}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_ON
async def test_binary_sensor_update_mount_type_window(
hass: HomeAssistant, ufp: MockUFPFixture, sensor_all: Sensor
) -> None:
"""Test binary_sensor motion entity."""
await init_entry(hass, ufp, [sensor_all])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 11, 11)
_, entity_id = ids_from_device_description(
Platform.BINARY_SENSOR, sensor_all, MOUNTABLE_SENSE_SENSORS[0]
)
state = hass.states.get(entity_id)
assert state
assert state.attributes[ATTR_DEVICE_CLASS] == BinarySensorDeviceClass.DOOR.value
new_sensor = sensor_all.model_copy()
new_sensor.mount_type = MountType.WINDOW
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_sensor
ufp.api.bootstrap.sensors = {new_sensor.id: new_sensor}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.attributes[ATTR_DEVICE_CLASS] == BinarySensorDeviceClass.WINDOW.value
async def test_binary_sensor_update_mount_type_garage(
hass: HomeAssistant, ufp: MockUFPFixture, sensor_all: Sensor
) -> None:
"""Test binary_sensor motion entity."""
await init_entry(hass, ufp, [sensor_all], debug=True)
assert_entity_counts(hass, Platform.BINARY_SENSOR, 11, 11)
_, entity_id = ids_from_device_description(
Platform.BINARY_SENSOR, sensor_all, MOUNTABLE_SENSE_SENSORS[0]
)
state = hass.states.get(entity_id)
assert state
assert state.attributes[ATTR_DEVICE_CLASS] == BinarySensorDeviceClass.DOOR.value
new_sensor = sensor_all.model_copy()
new_sensor.mount_type = MountType.GARAGE
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_sensor
ufp.api.bootstrap.sensors = {new_sensor.id: new_sensor}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert (
state.attributes[ATTR_DEVICE_CLASS] == BinarySensorDeviceClass.GARAGE_DOOR.value
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_binary_sensor_package_detected(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
fixed_now: datetime,
) -> None:
"""Test binary_sensor package detection entity."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 15, 15)
doorbell.smart_detect_settings.object_types.append(SmartDetectObjectType.PACKAGE)
_, entity_id = ids_from_device_description(
Platform.BINARY_SENSOR, doorbell, EVENT_SENSORS[6]
)
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.SMART_DETECT,
start=fixed_now - timedelta(seconds=1),
end=None,
score=100,
smart_detect_types=[SmartDetectObjectType.PACKAGE],
smart_detect_event_ids=[],
camera_id=doorbell.id,
api=ufp.api,
)
new_camera = doorbell.model_copy()
new_camera.is_smart_detected = True
new_camera.last_smart_detect_event_ids[SmartDetectObjectType.PACKAGE] = event.id
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_ON
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
assert state.attributes[ATTR_EVENT_SCORE] == 100
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.SMART_DETECT,
start=fixed_now - timedelta(seconds=1),
end=fixed_now + timedelta(seconds=1),
score=50,
smart_detect_types=[SmartDetectObjectType.PACKAGE],
smart_detect_event_ids=[],
camera_id=doorbell.id,
api=ufp.api,
)
new_camera = doorbell.model_copy()
new_camera.is_smart_detected = True
new_camera.last_smart_detect_event_ids[SmartDetectObjectType.PACKAGE] = event.id
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
# Event is already seen and has end, should now be off
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
# Now send an event that has an end right away
event = Event(
model=ModelType.EVENT,
id="new_event_id",
type=EventType.SMART_DETECT,
start=fixed_now - timedelta(seconds=1),
end=fixed_now + timedelta(seconds=1),
score=80,
smart_detect_types=[SmartDetectObjectType.PACKAGE],
smart_detect_event_ids=[],
camera_id=doorbell.id,
api=ufp.api,
)
new_camera = doorbell.model_copy()
new_camera.is_smart_detected = True
new_camera.last_smart_detect_event_ids[SmartDetectObjectType.PACKAGE] = event.id
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
state_changes: list[HAEvent[EventStateChangedData]] = async_capture_events(
hass, EVENT_STATE_CHANGED
)
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
assert len(state_changes) == 2
on_event = state_changes[0]
state = on_event.data["new_state"]
assert state
assert state.state == STATE_ON
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
assert state.attributes[ATTR_EVENT_SCORE] == 80
off_event = state_changes[1]
state = off_event.data["new_state"]
assert state
assert state.state == STATE_OFF
assert ATTR_EVENT_SCORE not in state.attributes
# replay and ensure ignored
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(state_changes) == 2
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_binary_sensor_person_detected(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
fixed_now: datetime,
) -> None:
"""Test binary_sensor person detected detection entity."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 15, 15)
doorbell.smart_detect_settings.object_types.append(SmartDetectObjectType.PERSON)
_, entity_id = ids_from_device_description(
Platform.BINARY_SENSOR, doorbell, EVENT_SENSORS[3]
)
events = async_capture_events(hass, EVENT_STATE_CHANGED)
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.SMART_DETECT,
start=fixed_now - timedelta(seconds=1),
end=None,
score=50,
smart_detect_types=[],
smart_detect_event_ids=[],
camera_id=doorbell.id,
api=ufp.api,
)
new_camera = doorbell.model_copy()
new_camera.is_smart_detected = True
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.SMART_DETECT,
start=fixed_now - timedelta(seconds=1),
end=fixed_now + timedelta(seconds=1),
score=65,
smart_detect_types=[SmartDetectObjectType.PERSON],
smart_detect_event_ids=[],
camera_id=doorbell.id,
api=ufp.api,
)
new_camera = doorbell.model_copy()
new_camera.is_smart_detected = True
new_camera.last_smart_detect_event_ids[SmartDetectObjectType.PERSON] = event.id
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
entity_events = [event for event in events if event.data["entity_id"] == entity_id]
assert len(entity_events) == 3
assert entity_events[0].data["new_state"].state == STATE_OFF
assert entity_events[1].data["new_state"].state == STATE_ON
assert entity_events[2].data["new_state"].state == STATE_OFF
# Event is already seen and has end, should now be off
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
# Now send an event that has an end right away
event = Event(
model=ModelType.EVENT,
id="new_event_id",
type=EventType.SMART_DETECT,
start=fixed_now - timedelta(seconds=1),
end=fixed_now + timedelta(seconds=1),
score=80,
smart_detect_types=[SmartDetectObjectType.PERSON],
smart_detect_event_ids=[],
camera_id=doorbell.id,
api=ufp.api,
)
new_camera = doorbell.model_copy()
new_camera.is_smart_detected = True
new_camera.last_smart_detect_event_ids[SmartDetectObjectType.PERSON] = event.id
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
state_changes: list[HAEvent[EventStateChangedData]] = async_capture_events(
hass, EVENT_STATE_CHANGED
)
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
assert len(state_changes) == 2
on_event = state_changes[0]
state = on_event.data["new_state"]
assert state
assert state.state == STATE_ON
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
assert state.attributes[ATTR_EVENT_SCORE] == 80
off_event = state_changes[1]
state = off_event.data["new_state"]
assert state
assert state.state == STATE_OFF
assert ATTR_EVENT_SCORE not in state.attributes
# replay and ensure ignored
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(state_changes) == 2

View File

@@ -0,0 +1,167 @@
"""Test the UniFi Protect button platform."""
from __future__ import annotations
from unittest.mock import AsyncMock, Mock
from uiprotect.data.devices import Camera, Chime, Doorlock
from homeassistant.components.unifiprotect.const import DEFAULT_ATTRIBUTION
from homeassistant.const import ATTR_ATTRIBUTION, ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .utils import (
MockUFPFixture,
adopt_devices,
assert_entity_counts,
enable_entity,
init_entry,
remove_entities,
)
async def test_button_chime_remove(
hass: HomeAssistant, ufp: MockUFPFixture, chime: Chime
) -> None:
"""Test removing and re-adding a light device."""
await init_entry(hass, ufp, [chime])
assert_entity_counts(hass, Platform.BUTTON, 4, 2)
await remove_entities(hass, ufp, [chime])
assert_entity_counts(hass, Platform.BUTTON, 0, 0)
await adopt_devices(hass, ufp, [chime])
assert_entity_counts(hass, Platform.BUTTON, 4, 2)
async def test_reboot_button(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
chime: Chime,
) -> None:
"""Test button entity."""
await init_entry(hass, ufp, [chime])
assert_entity_counts(hass, Platform.BUTTON, 4, 2)
ufp.api.reboot_device = AsyncMock()
unique_id = f"{chime.mac}_reboot"
entity_id = "button.test_chime_reboot_device"
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.disabled
assert entity.unique_id == unique_id
await enable_entity(hass, ufp.entry.entry_id, entity_id)
state = hass.states.get(entity_id)
assert state
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
await hass.services.async_call(
"button", "press", {ATTR_ENTITY_ID: entity_id}, blocking=True
)
ufp.api.reboot_device.assert_called_once()
async def test_chime_button(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
chime: Chime,
) -> None:
"""Test button entity."""
await init_entry(hass, ufp, [chime])
assert_entity_counts(hass, Platform.BUTTON, 4, 2)
ufp.api.play_speaker = AsyncMock()
unique_id = f"{chime.mac}_play"
entity_id = "button.test_chime_play_chime"
entity = entity_registry.async_get(entity_id)
assert entity
assert not entity.disabled
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
await hass.services.async_call(
"button", "press", {ATTR_ENTITY_ID: entity_id}, blocking=True
)
ufp.api.play_speaker.assert_called_once()
async def test_adopt_button(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
doorlock: Doorlock,
doorbell: Camera,
) -> None:
"""Test button entity."""
doorlock._api = ufp.api
doorlock.is_adopted = False
doorlock.can_adopt = True
await init_entry(hass, ufp, [])
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.old_obj = None
mock_msg.new_obj = doorlock
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert_entity_counts(hass, Platform.BUTTON, 1, 1)
ufp.api.adopt_device = AsyncMock()
unique_id = f"{doorlock.mac}_adopt"
entity_id = "button.test_lock_adopt_device"
entity = entity_registry.async_get(entity_id)
assert entity
assert not entity.disabled
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
await hass.services.async_call(
"button", "press", {ATTR_ENTITY_ID: entity_id}, blocking=True
)
ufp.api.adopt_device.assert_called_once()
async def test_adopt_button_removed(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
doorlock: Doorlock,
doorbell: Camera,
) -> None:
"""Test button entity."""
entity_id = "button.test_lock_adopt_device"
doorlock._api = ufp.api
doorlock.is_adopted = False
doorlock.can_adopt = True
await init_entry(hass, ufp, [doorlock])
assert_entity_counts(hass, Platform.BUTTON, 1, 1)
entity = entity_registry.async_get(entity_id)
assert entity
await adopt_devices(hass, ufp, [doorlock], fully_adopt=True)
assert_entity_counts(hass, Platform.BUTTON, 2, 0)
entity = entity_registry.async_get(entity_id)
assert entity is None

View File

@@ -0,0 +1,636 @@
"""Test the UniFi Protect camera platform."""
from __future__ import annotations
from unittest.mock import AsyncMock, Mock
import pytest
from uiprotect.api import DEVICE_UPDATE_INTERVAL
from uiprotect.data import Camera as ProtectCamera, CameraChannel, StateType
from uiprotect.exceptions import NvrError
from uiprotect.websocket import WebsocketState
from webrtc_models import RTCIceCandidateInit
from homeassistant.components.camera import (
CameraEntityFeature,
CameraState,
CameraWebRTCProvider,
StreamType,
WebRTCSendMessage,
async_get_image,
async_get_stream_source,
async_register_webrtc_provider,
)
from homeassistant.components.unifiprotect.const import (
ATTR_BITRATE,
ATTR_CHANNEL_ID,
ATTR_FPS,
ATTR_HEIGHT,
ATTR_WIDTH,
DEFAULT_ATTRIBUTION,
DOMAIN,
)
from homeassistant.components.unifiprotect.utils import get_camera_base_name
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_ENTITY_ID,
ATTR_SUPPORTED_FEATURES,
STATE_UNAVAILABLE,
Platform,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.setup import async_setup_component
from .utils import (
Camera,
MockUFPFixture,
adopt_devices,
assert_entity_counts,
enable_entity,
init_entry,
remove_entities,
time_changed,
)
class MockWebRTCProvider(CameraWebRTCProvider):
"""WebRTC provider."""
@property
def domain(self) -> str:
"""Return the integration domain of the provider."""
return DOMAIN
@callback
def async_is_supported(self, stream_source: str) -> bool:
"""Return if this provider is supports the Camera as source."""
return True
async def async_handle_async_webrtc_offer(
self,
camera: Camera,
offer_sdp: str,
session_id: str,
send_message: WebRTCSendMessage,
) -> None:
"""Handle the WebRTC offer and return the answer via the provided callback."""
async def async_on_webrtc_candidate(
self, session_id: str, candidate: RTCIceCandidateInit
) -> None:
"""Handle the WebRTC candidate."""
@callback
def async_close_session(self, session_id: str) -> None:
"""Close the session."""
@pytest.fixture
async def web_rtc_provider(hass: HomeAssistant) -> None:
"""Fixture to enable WebRTC provider for camera entities."""
await async_setup_component(hass, "camera", {})
async_register_webrtc_provider(hass, MockWebRTCProvider())
def validate_default_camera_entity(
hass: HomeAssistant,
camera_obj: ProtectCamera,
channel_id: int,
) -> str:
"""Validate a camera entity."""
channel = camera_obj.channels[channel_id]
camera_name = get_camera_base_name(channel)
entity_name = f"{camera_obj.name} {camera_name}"
unique_id = f"{camera_obj.mac}_{channel.id}"
entity_id = f"camera.{entity_name.replace(' ', '_').lower()}"
entity_registry = er.async_get(hass)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.disabled is False
assert entity.unique_id == unique_id
device_registry = dr.async_get(hass)
device = device_registry.async_get(entity.device_id)
assert device
assert device.manufacturer == "Ubiquiti"
assert device.name == camera_obj.name
assert device.model == camera_obj.market_name or camera_obj.type
assert device.model_id == camera_obj.type
return entity_id
def validate_rtsps_camera_entity(
hass: HomeAssistant,
camera_obj: ProtectCamera,
channel_id: int,
) -> str:
"""Validate a disabled RTSPS camera entity."""
channel = camera_obj.channels[channel_id]
entity_name = f"{camera_obj.name} {channel.name} Resolution Channel"
unique_id = f"{camera_obj.mac}_{channel.id}"
entity_id = f"camera.{entity_name.replace(' ', '_').lower()}"
entity_registry = er.async_get(hass)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.disabled is True
assert entity.unique_id == unique_id
return entity_id
def validate_rtsp_camera_entity(
hass: HomeAssistant,
camera_obj: ProtectCamera,
channel_id: int,
) -> str:
"""Validate a disabled RTSP camera entity."""
channel = camera_obj.channels[channel_id]
entity_name = f"{camera_obj.name} {channel.name} Resolution Channel (Insecure)"
unique_id = f"{camera_obj.mac}_{channel.id}_insecure"
entity_id = f"camera.{entity_name.replace(' ', '_').replace('(', '').replace(')', '').lower()}"
entity_registry = er.async_get(hass)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.disabled is True
assert entity.unique_id == unique_id
return entity_id
def validate_common_camera_state(
hass: HomeAssistant,
channel: CameraChannel,
entity_id: str,
features: int = CameraEntityFeature.STREAM,
):
"""Validate state that is common to all camera entity, regradless of type."""
entity_state = hass.states.get(entity_id)
assert entity_state
assert entity_state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
assert entity_state.attributes[ATTR_SUPPORTED_FEATURES] == features
assert entity_state.attributes[ATTR_WIDTH] == channel.width
assert entity_state.attributes[ATTR_HEIGHT] == channel.height
assert entity_state.attributes[ATTR_FPS] == channel.fps
assert entity_state.attributes[ATTR_BITRATE] == channel.bitrate
assert entity_state.attributes[ATTR_CHANNEL_ID] == channel.id
async def validate_rtsps_camera_state(
hass: HomeAssistant,
camera_obj: ProtectCamera,
channel_id: int,
entity_id: str,
features: int = CameraEntityFeature.STREAM,
):
"""Validate a camera's state."""
channel = camera_obj.channels[channel_id]
assert await async_get_stream_source(hass, entity_id) == channel.rtsps_no_srtp_url
validate_common_camera_state(hass, channel, entity_id, features)
async def validate_rtsp_camera_state(
hass: HomeAssistant,
camera_obj: ProtectCamera,
channel_id: int,
entity_id: str,
features: int = CameraEntityFeature.STREAM,
):
"""Validate a camera's state."""
channel = camera_obj.channels[channel_id]
assert await async_get_stream_source(hass, entity_id) == channel.rtsp_url
validate_common_camera_state(hass, channel, entity_id, features)
async def validate_no_stream_camera_state(
hass: HomeAssistant,
camera_obj: ProtectCamera,
channel_id: int,
entity_id: str,
features: int = CameraEntityFeature.STREAM,
):
"""Validate a camera's state."""
channel = camera_obj.channels[channel_id]
assert await async_get_stream_source(hass, entity_id) is None
validate_common_camera_state(hass, channel, entity_id, features)
async def test_basic_setup(
hass: HomeAssistant,
ufp: MockUFPFixture,
camera_all: ProtectCamera,
doorbell: ProtectCamera,
) -> None:
"""Test working setup of unifiprotect entry."""
camera_high_only = camera_all.model_copy()
camera_high_only.channels = [c.model_copy() for c in camera_all.channels]
camera_high_only.name = "Test Camera 1"
camera_high_only.channels[0].is_rtsp_enabled = True
camera_high_only.channels[1].is_rtsp_enabled = False
camera_high_only.channels[2].is_rtsp_enabled = False
camera_medium_only = camera_all.model_copy()
camera_medium_only.channels = [c.model_copy() for c in camera_all.channels]
camera_medium_only.name = "Test Camera 2"
camera_medium_only.channels[0].is_rtsp_enabled = False
camera_medium_only.channels[1].is_rtsp_enabled = True
camera_medium_only.channels[2].is_rtsp_enabled = False
camera_all.name = "Test Camera 3"
camera_no_channels = camera_all.model_copy()
camera_no_channels.channels = [c.model_copy() for c in camera_all.channels]
camera_no_channels.name = "Test Camera 4"
camera_no_channels.channels[0].is_rtsp_enabled = False
camera_no_channels.channels[1].is_rtsp_enabled = False
camera_no_channels.channels[2].is_rtsp_enabled = False
doorbell.name = "Test Camera 5"
devices = [
camera_high_only,
camera_medium_only,
camera_all,
camera_no_channels,
doorbell,
]
await init_entry(hass, ufp, devices)
assert_entity_counts(hass, Platform.CAMERA, 14, 6)
# test camera 1
entity_id = validate_default_camera_entity(hass, camera_high_only, 0)
await validate_rtsps_camera_state(hass, camera_high_only, 0, entity_id)
entity_id = validate_rtsp_camera_entity(hass, camera_high_only, 0)
await enable_entity(hass, ufp.entry.entry_id, entity_id)
await validate_rtsp_camera_state(hass, camera_high_only, 0, entity_id)
# test camera 2
entity_id = validate_default_camera_entity(hass, camera_medium_only, 1)
await validate_rtsps_camera_state(hass, camera_medium_only, 1, entity_id)
entity_id = validate_rtsp_camera_entity(hass, camera_medium_only, 1)
await enable_entity(hass, ufp.entry.entry_id, entity_id)
await validate_rtsp_camera_state(hass, camera_medium_only, 1, entity_id)
# test camera 3
entity_id = validate_default_camera_entity(hass, camera_all, 0)
await validate_rtsps_camera_state(hass, camera_all, 0, entity_id)
entity_id = validate_rtsp_camera_entity(hass, camera_all, 0)
await enable_entity(hass, ufp.entry.entry_id, entity_id)
await validate_rtsp_camera_state(hass, camera_all, 0, entity_id)
entity_id = validate_rtsps_camera_entity(hass, camera_all, 1)
await enable_entity(hass, ufp.entry.entry_id, entity_id)
await validate_rtsps_camera_state(hass, camera_all, 1, entity_id)
entity_id = validate_rtsp_camera_entity(hass, camera_all, 1)
await enable_entity(hass, ufp.entry.entry_id, entity_id)
await validate_rtsp_camera_state(hass, camera_all, 1, entity_id)
entity_id = validate_rtsps_camera_entity(hass, camera_all, 2)
await enable_entity(hass, ufp.entry.entry_id, entity_id)
await validate_rtsps_camera_state(hass, camera_all, 2, entity_id)
entity_id = validate_rtsp_camera_entity(hass, camera_all, 2)
await enable_entity(hass, ufp.entry.entry_id, entity_id)
await validate_rtsp_camera_state(hass, camera_all, 2, entity_id)
# test camera 4
entity_id = validate_default_camera_entity(hass, camera_no_channels, 0)
await validate_no_stream_camera_state(
hass, camera_no_channels, 0, entity_id, features=0
)
# test camera 5
entity_id = validate_default_camera_entity(hass, doorbell, 0)
await validate_rtsps_camera_state(hass, doorbell, 0, entity_id)
entity_id = validate_rtsp_camera_entity(hass, doorbell, 0)
await enable_entity(hass, ufp.entry.entry_id, entity_id)
await validate_rtsp_camera_state(hass, doorbell, 0, entity_id)
entity_id = validate_default_camera_entity(hass, doorbell, 3)
await validate_no_stream_camera_state(hass, doorbell, 3, entity_id, features=0)
@pytest.mark.usefixtures("web_rtc_provider")
async def test_webrtc_support(
hass: HomeAssistant,
ufp: MockUFPFixture,
camera_all: ProtectCamera,
) -> None:
"""Test webrtc support is available."""
camera_high_only = camera_all.model_copy()
camera_high_only.channels = [c.model_copy() for c in camera_all.channels]
camera_high_only.name = "Test Camera 1"
camera_high_only.channels[0].is_rtsp_enabled = True
camera_high_only.channels[1].is_rtsp_enabled = False
camera_high_only.channels[2].is_rtsp_enabled = False
await init_entry(hass, ufp, [camera_high_only])
entity_id = validate_default_camera_entity(hass, camera_high_only, 0)
state = hass.states.get(entity_id)
assert state
assert StreamType.WEB_RTC in state.attributes["frontend_stream_type"]
async def test_adopt(
hass: HomeAssistant, ufp: MockUFPFixture, camera: ProtectCamera
) -> None:
"""Test setting up camera with no camera channels."""
camera1 = camera.model_copy()
camera1.channels = []
await init_entry(hass, ufp, [camera1])
assert_entity_counts(hass, Platform.CAMERA, 0, 0)
await remove_entities(hass, ufp, [camera1])
assert_entity_counts(hass, Platform.CAMERA, 0, 0)
camera1.channels = []
await adopt_devices(hass, ufp, [camera1])
assert_entity_counts(hass, Platform.CAMERA, 0, 0)
camera1.channels = camera.channels
for channel in camera1.channels:
channel._api = ufp.api
mock_msg = Mock()
mock_msg.changed_data = {"channels": camera.channels}
mock_msg.new_obj = camera1
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert_entity_counts(hass, Platform.CAMERA, 2, 1)
await remove_entities(hass, ufp, [camera1])
assert_entity_counts(hass, Platform.CAMERA, 0, 0)
await adopt_devices(hass, ufp, [camera1])
assert_entity_counts(hass, Platform.CAMERA, 2, 1)
async def test_camera_image(
hass: HomeAssistant, ufp: MockUFPFixture, camera: ProtectCamera
) -> None:
"""Test retrieving camera image."""
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.CAMERA, 2, 1)
ufp.api.get_camera_snapshot = AsyncMock()
await async_get_image(hass, "camera.test_camera_high_resolution_channel")
ufp.api.get_camera_snapshot.assert_called_once()
async def test_package_camera_image(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: ProtectCamera
) -> None:
"""Test retrieving package camera image."""
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.CAMERA, 3, 2)
ufp.api.get_package_camera_snapshot = AsyncMock()
await async_get_image(hass, "camera.test_camera_package_camera")
ufp.api.get_package_camera_snapshot.assert_called_once()
async def test_camera_generic_update(
hass: HomeAssistant, ufp: MockUFPFixture, camera: ProtectCamera
) -> None:
"""Tests generic entity update service."""
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.CAMERA, 2, 1)
entity_id = "camera.test_camera_high_resolution_channel"
assert await async_setup_component(hass, "homeassistant", {})
state = hass.states.get(entity_id)
assert state and state.state == "idle"
ufp.api.update = AsyncMock(return_value=None)
await hass.services.async_call(
"homeassistant",
"update_entity",
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
state = hass.states.get(entity_id)
assert state and state.state == "idle"
async def test_camera_interval_update(
hass: HomeAssistant, ufp: MockUFPFixture, camera: ProtectCamera
) -> None:
"""Interval updates updates camera entity."""
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.CAMERA, 2, 1)
entity_id = "camera.test_camera_high_resolution_channel"
state = hass.states.get(entity_id)
assert state and state.state == "idle"
new_camera = camera.model_copy()
new_camera.is_recording = True
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.update = AsyncMock(return_value=ufp.api.bootstrap)
await time_changed(hass, DEVICE_UPDATE_INTERVAL)
state = hass.states.get(entity_id)
assert state and state.state == "recording"
async def test_camera_bad_interval_update(
hass: HomeAssistant, ufp: MockUFPFixture, camera: ProtectCamera
) -> None:
"""Interval updates marks camera unavailable."""
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.CAMERA, 2, 1)
entity_id = "camera.test_camera_high_resolution_channel"
state = hass.states.get(entity_id)
assert state and state.state == "idle"
# update fails
ufp.api.update = AsyncMock(side_effect=NvrError)
await time_changed(hass, DEVICE_UPDATE_INTERVAL)
state = hass.states.get(entity_id)
assert state and state.state == "unavailable"
# next update succeeds
ufp.api.update = AsyncMock(return_value=ufp.api.bootstrap)
await time_changed(hass, DEVICE_UPDATE_INTERVAL)
state = hass.states.get(entity_id)
assert state and state.state == "idle"
async def test_camera_websocket_disconnected(
hass: HomeAssistant, ufp: MockUFPFixture, camera: ProtectCamera
) -> None:
"""Test the websocket gets disconnected and reconnected."""
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.CAMERA, 2, 1)
entity_id = "camera.test_camera_high_resolution_channel"
state = hass.states.get(entity_id)
assert state and state.state == CameraState.IDLE
# websocket disconnects
ufp.ws_state_subscription(WebsocketState.DISCONNECTED)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state and state.state == STATE_UNAVAILABLE
# websocket reconnects
ufp.ws_state_subscription(WebsocketState.CONNECTED)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state and state.state == CameraState.IDLE
async def test_camera_ws_update(
hass: HomeAssistant, ufp: MockUFPFixture, camera: ProtectCamera
) -> None:
"""WS update updates camera entity."""
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.CAMERA, 2, 1)
entity_id = "camera.test_camera_high_resolution_channel"
state = hass.states.get(entity_id)
assert state and state.state == "idle"
new_camera = camera.model_copy()
new_camera.is_recording = True
no_camera = camera.model_copy()
no_camera.is_adopted = False
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_camera
ufp.ws_msg(mock_msg)
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = no_camera
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state and state.state == "recording"
async def test_camera_ws_update_offline(
hass: HomeAssistant, ufp: MockUFPFixture, camera: ProtectCamera
) -> None:
"""WS updates marks camera unavailable."""
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.CAMERA, 2, 1)
entity_id = "camera.test_camera_high_resolution_channel"
state = hass.states.get(entity_id)
assert state and state.state == "idle"
# camera goes offline
new_camera = camera.model_copy()
new_camera.state = StateType.DISCONNECTED
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_camera
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state and state.state == "unavailable"
# camera comes back online
new_camera.state = StateType.CONNECTED
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_camera
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state and state.state == "idle"
async def test_camera_enable_motion(
hass: HomeAssistant, ufp: MockUFPFixture, camera: ProtectCamera
) -> None:
"""Tests generic entity update service."""
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.CAMERA, 2, 1)
entity_id = "camera.test_camera_high_resolution_channel"
camera.__pydantic_fields__["set_motion_detection"] = Mock(final=False, frozen=False)
camera.set_motion_detection = AsyncMock()
await hass.services.async_call(
"camera",
"enable_motion_detection",
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
camera.set_motion_detection.assert_called_once_with(True)
async def test_camera_disable_motion(
hass: HomeAssistant, ufp: MockUFPFixture, camera: ProtectCamera
) -> None:
"""Tests generic entity update service."""
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.CAMERA, 2, 1)
entity_id = "camera.test_camera_high_resolution_channel"
camera.__pydantic_fields__["set_motion_detection"] = Mock(final=False, frozen=False)
camera.set_motion_detection = AsyncMock()
await hass.services.async_call(
"camera",
"disable_motion_detection",
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
camera.set_motion_detection.assert_called_once_with(False)

View File

@@ -0,0 +1,913 @@
"""Test the UniFi Protect config flow."""
from __future__ import annotations
from dataclasses import asdict
import socket
from unittest.mock import patch
import pytest
from uiprotect import NotAuthorized, NvrError, ProtectApiClient
from uiprotect.data import NVR, Bootstrap, CloudAccount
from homeassistant import config_entries
from homeassistant.components import dhcp, ssdp
from homeassistant.components.unifiprotect.const import (
CONF_ALL_UPDATES,
CONF_DISABLE_RTSP,
CONF_OVERRIDE_CHOST,
DOMAIN,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_HOST
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers import device_registry as dr
from . import (
DEVICE_HOSTNAME,
DEVICE_IP_ADDRESS,
DEVICE_MAC_ADDRESS,
DIRECT_CONNECT_DOMAIN,
UNIFI_DISCOVERY,
UNIFI_DISCOVERY_PARTIAL,
_patch_discovery,
)
from .conftest import MAC_ADDR
from tests.common import MockConfigEntry
DHCP_DISCOVERY = dhcp.DhcpServiceInfo(
hostname=DEVICE_HOSTNAME,
ip=DEVICE_IP_ADDRESS,
macaddress=DEVICE_MAC_ADDRESS.lower().replace(":", ""),
)
SSDP_DISCOVERY = (
ssdp.SsdpServiceInfo(
ssdp_usn="mock_usn",
ssdp_st="mock_st",
ssdp_location=f"http://{DEVICE_IP_ADDRESS}:41417/rootDesc.xml",
upnp={
"friendlyName": "UniFi Dream Machine",
"modelDescription": "UniFi Dream Machine Pro",
"serialNumber": DEVICE_MAC_ADDRESS,
},
),
)
UNIFI_DISCOVERY_DICT = asdict(UNIFI_DISCOVERY)
UNIFI_DISCOVERY_DICT_PARTIAL = asdict(UNIFI_DISCOVERY_PARTIAL)
async def test_form(hass: HomeAssistant, bootstrap: Bootstrap, nvr: NVR) -> None:
"""Test we get the form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert not result["errors"]
bootstrap.nvr = nvr
with (
patch(
"homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
return_value=bootstrap,
),
patch(
"homeassistant.components.unifiprotect.async_setup_entry",
return_value=True,
) as mock_setup_entry,
patch(
"homeassistant.components.unifiprotect.async_setup",
return_value=True,
) as mock_setup,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
"host": "1.1.1.1",
"username": "test-username",
"password": "test-password",
},
)
await hass.async_block_till_done()
assert result2["type"] is FlowResultType.CREATE_ENTRY
assert result2["title"] == "UnifiProtect"
assert result2["data"] == {
"host": "1.1.1.1",
"username": "test-username",
"password": "test-password",
"id": "UnifiProtect",
"port": 443,
"verify_ssl": False,
}
assert len(mock_setup_entry.mock_calls) == 1
assert len(mock_setup.mock_calls) == 1
async def test_form_version_too_old(
hass: HomeAssistant, bootstrap: Bootstrap, old_nvr: NVR
) -> None:
"""Test we handle the version being too old."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
bootstrap.nvr = old_nvr
with patch(
"homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
return_value=bootstrap,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
"host": "1.1.1.1",
"username": "test-username",
"password": "test-password",
},
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"] == {"base": "protect_version"}
async def test_form_invalid_auth(hass: HomeAssistant) -> None:
"""Test we handle invalid auth."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
side_effect=NotAuthorized,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
"host": "1.1.1.1",
"username": "test-username",
"password": "test-password",
},
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"] == {"password": "invalid_auth"}
async def test_form_cloud_user(
hass: HomeAssistant, bootstrap: Bootstrap, cloud_account: CloudAccount
) -> None:
"""Test we handle cloud users."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
user = bootstrap.users[bootstrap.auth_user_id]
user.cloud_account = cloud_account
bootstrap.users[bootstrap.auth_user_id] = user
with patch(
"homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
return_value=bootstrap,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
"host": "1.1.1.1",
"username": "test-username",
"password": "test-password",
},
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"] == {"base": "cloud_user"}
async def test_form_cannot_connect(hass: HomeAssistant) -> None:
"""Test we handle cannot connect error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
side_effect=NvrError,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
"host": "1.1.1.1",
"username": "test-username",
"password": "test-password",
},
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"] == {"base": "cannot_connect"}
async def test_form_reauth_auth(
hass: HomeAssistant, bootstrap: Bootstrap, nvr: NVR
) -> None:
"""Test we handle reauth auth."""
mock_config = MockConfigEntry(
domain=DOMAIN,
data={
"host": "1.1.1.1",
"username": "test-username",
"password": "test-password",
"id": "UnifiProtect",
"port": 443,
"verify_ssl": False,
},
unique_id=dr.format_mac(MAC_ADDR),
)
mock_config.add_to_hass(hass)
result = await mock_config.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert not result["errors"]
flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN)
assert flows[0]["context"]["title_placeholders"] == {
"ip_address": "1.1.1.1",
"name": "Mock Title",
}
with patch(
"homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
side_effect=NotAuthorized,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
"username": "test-username",
"password": "test-password",
},
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"] == {"password": "invalid_auth"}
assert result2["step_id"] == "reauth_confirm"
bootstrap.nvr = nvr
with (
patch(
"homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
return_value=bootstrap,
),
patch(
"homeassistant.components.unifiprotect.async_setup",
return_value=True,
) as mock_setup,
):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
"username": "test-username",
"password": "new-password",
},
)
await hass.async_block_till_done()
assert result3["type"] is FlowResultType.ABORT
assert result3["reason"] == "reauth_successful"
assert len(mock_setup.mock_calls) == 1
async def test_form_options(hass: HomeAssistant, ufp_client: ProtectApiClient) -> None:
"""Test we handle options flows."""
mock_config = MockConfigEntry(
domain=DOMAIN,
data={
"host": "1.1.1.1",
"username": "test-username",
"password": "test-password",
"id": "UnifiProtect",
"port": 443,
"verify_ssl": False,
"max_media": 1000,
},
version=2,
unique_id=dr.format_mac(MAC_ADDR),
)
mock_config.add_to_hass(hass)
with (
_patch_discovery(),
patch(
"homeassistant.components.unifiprotect.utils.ProtectApiClient"
) as mock_api,
):
mock_api.return_value = ufp_client
await hass.config_entries.async_setup(mock_config.entry_id)
await hass.async_block_till_done()
assert mock_config.state is ConfigEntryState.LOADED
result = await hass.config_entries.options.async_init(mock_config.entry_id)
assert result["type"] is FlowResultType.FORM
assert not result["errors"]
assert result["step_id"] == "init"
result2 = await hass.config_entries.options.async_configure(
result["flow_id"],
{
CONF_DISABLE_RTSP: True,
CONF_ALL_UPDATES: True,
CONF_OVERRIDE_CHOST: True,
},
)
assert result2["type"] is FlowResultType.CREATE_ENTRY
assert result2["data"] == {
"all_updates": True,
"disable_rtsp": True,
"override_connection_host": True,
"max_media": 1000,
"allow_ea_channel": False,
}
await hass.async_block_till_done()
await hass.config_entries.async_unload(mock_config.entry_id)
@pytest.mark.parametrize(
("source", "data"),
[
(config_entries.SOURCE_DHCP, DHCP_DISCOVERY),
(config_entries.SOURCE_SSDP, SSDP_DISCOVERY),
],
)
async def test_discovered_by_ssdp_or_dhcp(
hass: HomeAssistant, source: str, data: dhcp.DhcpServiceInfo | ssdp.SsdpServiceInfo
) -> None:
"""Test we handoff to unifi-discovery when discovered via ssdp or dhcp."""
with _patch_discovery():
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": source},
data=data,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "discovery_started"
async def test_discovered_by_unifi_discovery_direct_connect(
hass: HomeAssistant, bootstrap: Bootstrap, nvr: NVR
) -> None:
"""Test a discovery from unifi-discovery."""
with _patch_discovery():
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
data=UNIFI_DISCOVERY_DICT,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "discovery_confirm"
flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN)
assert flows[0]["context"]["title_placeholders"] == {
"ip_address": DEVICE_IP_ADDRESS,
"name": DEVICE_HOSTNAME,
}
assert not result["errors"]
bootstrap.nvr = nvr
with (
patch(
"homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
return_value=bootstrap,
),
patch(
"homeassistant.components.unifiprotect.async_setup_entry",
return_value=True,
) as mock_setup_entry,
patch(
"homeassistant.components.unifiprotect.async_setup",
return_value=True,
) as mock_setup,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
"username": "test-username",
"password": "test-password",
},
)
await hass.async_block_till_done()
assert result2["type"] is FlowResultType.CREATE_ENTRY
assert result2["title"] == "UnifiProtect"
assert result2["data"] == {
"host": DIRECT_CONNECT_DOMAIN,
"username": "test-username",
"password": "test-password",
"id": "UnifiProtect",
"port": 443,
"verify_ssl": True,
}
assert len(mock_setup_entry.mock_calls) == 1
assert len(mock_setup.mock_calls) == 1
async def test_discovered_by_unifi_discovery_direct_connect_updated(
hass: HomeAssistant,
) -> None:
"""Test a discovery from unifi-discovery updates the direct connect host."""
mock_config = MockConfigEntry(
domain=DOMAIN,
data={
"host": "y.ui.direct",
"username": "test-username",
"password": "test-password",
"id": "UnifiProtect",
"port": 443,
"verify_ssl": True,
},
version=2,
unique_id=DEVICE_MAC_ADDRESS.replace(":", "").upper(),
)
mock_config.add_to_hass(hass)
with _patch_discovery():
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
data=UNIFI_DISCOVERY_DICT,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert mock_config.data[CONF_HOST] == DIRECT_CONNECT_DOMAIN
async def test_discovered_by_unifi_discovery_direct_connect_updated_but_not_using_direct_connect(
hass: HomeAssistant,
) -> None:
"""Test a discovery from unifi-discovery updates the host but not direct connect if its not in use."""
mock_config = MockConfigEntry(
domain=DOMAIN,
data={
"host": "1.2.2.2",
"username": "test-username",
"password": "test-password",
"id": "UnifiProtect",
"port": 443,
"verify_ssl": False,
},
version=2,
unique_id=DEVICE_MAC_ADDRESS.replace(":", "").upper(),
)
mock_config.add_to_hass(hass)
with (
_patch_discovery(),
patch(
"homeassistant.components.unifiprotect.config_flow.async_console_is_alive",
return_value=False,
),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
data=UNIFI_DISCOVERY_DICT,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert mock_config.data[CONF_HOST] == "127.0.0.1"
async def test_discovered_by_unifi_discovery_does_not_update_ip_when_console_is_still_online(
hass: HomeAssistant,
) -> None:
"""Test a discovery from unifi-discovery does not update the ip unless the console at the old ip is offline."""
mock_config = MockConfigEntry(
domain=DOMAIN,
data={
"host": "1.2.2.2",
"username": "test-username",
"password": "test-password",
"id": "UnifiProtect",
"port": 443,
"verify_ssl": False,
},
version=2,
unique_id=DEVICE_MAC_ADDRESS.replace(":", "").upper(),
)
mock_config.add_to_hass(hass)
with (
_patch_discovery(),
patch(
"homeassistant.components.unifiprotect.config_flow.async_console_is_alive",
return_value=True,
),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
data=UNIFI_DISCOVERY_DICT,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert mock_config.data[CONF_HOST] == "1.2.2.2"
async def test_discovered_host_not_updated_if_existing_is_a_hostname(
hass: HomeAssistant,
) -> None:
"""Test we only update the host if its an ip address from discovery."""
mock_config = MockConfigEntry(
domain=DOMAIN,
data={
"host": "a.hostname",
"username": "test-username",
"password": "test-password",
"id": "UnifiProtect",
"port": 443,
"verify_ssl": True,
},
unique_id=DEVICE_MAC_ADDRESS.upper().replace(":", ""),
)
mock_config.add_to_hass(hass)
with _patch_discovery():
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
data=UNIFI_DISCOVERY_DICT,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert mock_config.data[CONF_HOST] == "a.hostname"
async def test_discovered_by_unifi_discovery(
hass: HomeAssistant, bootstrap: Bootstrap, nvr: NVR
) -> None:
"""Test a discovery from unifi-discovery."""
with _patch_discovery():
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
data=UNIFI_DISCOVERY_DICT,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "discovery_confirm"
flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN)
assert flows[0]["context"]["title_placeholders"] == {
"ip_address": DEVICE_IP_ADDRESS,
"name": DEVICE_HOSTNAME,
}
assert not result["errors"]
bootstrap.nvr = nvr
with (
patch(
"homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
side_effect=[NotAuthorized, bootstrap],
),
patch(
"homeassistant.components.unifiprotect.async_setup_entry",
return_value=True,
) as mock_setup_entry,
patch(
"homeassistant.components.unifiprotect.async_setup",
return_value=True,
) as mock_setup,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
"username": "test-username",
"password": "test-password",
},
)
await hass.async_block_till_done()
assert result2["type"] is FlowResultType.CREATE_ENTRY
assert result2["title"] == "UnifiProtect"
assert result2["data"] == {
"host": DEVICE_IP_ADDRESS,
"username": "test-username",
"password": "test-password",
"id": "UnifiProtect",
"port": 443,
"verify_ssl": False,
}
assert len(mock_setup_entry.mock_calls) == 1
assert len(mock_setup.mock_calls) == 1
async def test_discovered_by_unifi_discovery_partial(
hass: HomeAssistant, bootstrap: Bootstrap, nvr: NVR
) -> None:
"""Test a discovery from unifi-discovery partial."""
with _patch_discovery():
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
data=UNIFI_DISCOVERY_DICT_PARTIAL,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "discovery_confirm"
flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN)
assert flows[0]["context"]["title_placeholders"] == {
"ip_address": DEVICE_IP_ADDRESS,
"name": "NVR DDEEFF",
}
assert not result["errors"]
bootstrap.nvr = nvr
with (
patch(
"homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
return_value=bootstrap,
),
patch(
"homeassistant.components.unifiprotect.async_setup_entry",
return_value=True,
) as mock_setup_entry,
patch(
"homeassistant.components.unifiprotect.async_setup",
return_value=True,
) as mock_setup,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
"username": "test-username",
"password": "test-password",
},
)
await hass.async_block_till_done()
assert result2["type"] is FlowResultType.CREATE_ENTRY
assert result2["title"] == "UnifiProtect"
assert result2["data"] == {
"host": DEVICE_IP_ADDRESS,
"username": "test-username",
"password": "test-password",
"id": "UnifiProtect",
"port": 443,
"verify_ssl": False,
}
assert len(mock_setup_entry.mock_calls) == 1
assert len(mock_setup.mock_calls) == 1
async def test_discovered_by_unifi_discovery_direct_connect_on_different_interface(
hass: HomeAssistant,
) -> None:
"""Test a discovery from unifi-discovery from an alternate interface."""
mock_config = MockConfigEntry(
domain=DOMAIN,
data={
"host": DIRECT_CONNECT_DOMAIN,
"username": "test-username",
"password": "test-password",
"id": "UnifiProtect",
"port": 443,
"verify_ssl": True,
},
unique_id="FFFFFFAAAAAA",
)
mock_config.add_to_hass(hass)
with _patch_discovery():
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
data=UNIFI_DISCOVERY_DICT,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_discovered_by_unifi_discovery_direct_connect_on_different_interface_ip_matches(
hass: HomeAssistant,
) -> None:
"""Test a discovery from unifi-discovery from an alternate interface when the ip matches."""
mock_config = MockConfigEntry(
domain=DOMAIN,
data={
"host": "127.0.0.1",
"username": "test-username",
"password": "test-password",
"id": "UnifiProtect",
"port": 443,
"verify_ssl": True,
},
unique_id="FFFFFFAAAAAA",
)
mock_config.add_to_hass(hass)
with _patch_discovery():
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
data=UNIFI_DISCOVERY_DICT,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_discovered_by_unifi_discovery_direct_connect_on_different_interface_resolver(
hass: HomeAssistant,
) -> None:
"""Test a discovery from unifi-discovery from an alternate interface when direct connect domain resolves to host ip."""
mock_config = MockConfigEntry(
domain=DOMAIN,
data={
"host": "y.ui.direct",
"username": "test-username",
"password": "test-password",
"id": "UnifiProtect",
"port": 443,
"verify_ssl": True,
},
unique_id="FFFFFFAAAAAA",
)
mock_config.add_to_hass(hass)
other_ip_dict = UNIFI_DISCOVERY_DICT.copy()
other_ip_dict["source_ip"] = "127.0.0.1"
other_ip_dict["direct_connect_domain"] = "nomatchsameip.ui.direct"
with (
_patch_discovery(),
patch.object(
hass.loop,
"getaddrinfo",
return_value=[(socket.AF_INET, None, None, None, ("127.0.0.1", 443))],
),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
data=other_ip_dict,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_discovered_by_unifi_discovery_direct_connect_on_different_interface_resolver_fails(
hass: HomeAssistant, bootstrap: Bootstrap, nvr: NVR
) -> None:
"""Test we can still configure if the resolver fails."""
mock_config = MockConfigEntry(
domain=DOMAIN,
data={
"host": "y.ui.direct",
"username": "test-username",
"password": "test-password",
"id": "UnifiProtect",
"port": 443,
"verify_ssl": True,
},
unique_id="FFFFFFAAAAAA",
)
mock_config.add_to_hass(hass)
other_ip_dict = UNIFI_DISCOVERY_DICT.copy()
other_ip_dict["source_ip"] = "127.0.0.2"
other_ip_dict["direct_connect_domain"] = "nomatchsameip.ui.direct"
with (
_patch_discovery(),
patch.object(hass.loop, "getaddrinfo", side_effect=OSError),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
data=other_ip_dict,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "discovery_confirm"
flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN)
assert flows[0]["context"]["title_placeholders"] == {
"ip_address": "127.0.0.2",
"name": "unvr",
}
assert not result["errors"]
bootstrap.nvr = nvr
with (
patch(
"homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
return_value=bootstrap,
),
patch(
"homeassistant.components.unifiprotect.async_setup_entry",
return_value=True,
) as mock_setup_entry,
patch(
"homeassistant.components.unifiprotect.async_setup",
return_value=True,
) as mock_setup,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
"username": "test-username",
"password": "test-password",
},
)
await hass.async_block_till_done()
assert result2["type"] is FlowResultType.CREATE_ENTRY
assert result2["title"] == "UnifiProtect"
assert result2["data"] == {
"host": "nomatchsameip.ui.direct",
"username": "test-username",
"password": "test-password",
"id": "UnifiProtect",
"port": 443,
"verify_ssl": True,
}
assert len(mock_setup_entry.mock_calls) == 1
assert len(mock_setup.mock_calls) == 1
async def test_discovered_by_unifi_discovery_direct_connect_on_different_interface_resolver_no_result(
hass: HomeAssistant,
) -> None:
"""Test a discovery from unifi-discovery from an alternate interface when direct connect domain resolve has no result."""
mock_config = MockConfigEntry(
domain=DOMAIN,
data={
"host": "y.ui.direct",
"username": "test-username",
"password": "test-password",
"id": "UnifiProtect",
"port": 443,
"verify_ssl": True,
},
unique_id="FFFFFFAAAAAA",
)
mock_config.add_to_hass(hass)
other_ip_dict = UNIFI_DISCOVERY_DICT.copy()
other_ip_dict["source_ip"] = "127.0.0.2"
other_ip_dict["direct_connect_domain"] = "y.ui.direct"
with _patch_discovery(), patch.object(hass.loop, "getaddrinfo", return_value=[]):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
data=other_ip_dict,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_discovery_can_be_ignored(hass: HomeAssistant) -> None:
"""Test a discovery can be ignored."""
mock_config = MockConfigEntry(
domain=DOMAIN,
data={},
unique_id=DEVICE_MAC_ADDRESS.upper().replace(":", ""),
source=config_entries.SOURCE_IGNORE,
)
mock_config.add_to_hass(hass)
with _patch_discovery():
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
data=UNIFI_DISCOVERY_DICT,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"

View File

@@ -0,0 +1,63 @@
"""Test UniFi Protect diagnostics."""
from uiprotect.data import NVR, Light
from homeassistant.components.unifiprotect.const import CONF_ALLOW_EA
from homeassistant.core import HomeAssistant
from .utils import MockUFPFixture, init_entry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_diagnostics(
hass: HomeAssistant,
ufp: MockUFPFixture,
light: Light,
hass_client: ClientSessionGenerator,
) -> None:
"""Test generating diagnostics for a config entry."""
await init_entry(hass, ufp, [light])
options = dict(ufp.entry.options)
options[CONF_ALLOW_EA] = True
hass.config_entries.async_update_entry(ufp.entry, options=options)
await hass.async_block_till_done()
diag = await get_diagnostics_for_config_entry(hass, hass_client, ufp.entry)
assert "options" in diag and isinstance(diag["options"], dict)
options = diag["options"]
assert options[CONF_ALLOW_EA] is True
assert "bootstrap" in diag and isinstance(diag["bootstrap"], dict)
bootstrap = diag["bootstrap"]
nvr: NVR = ufp.api.bootstrap.nvr
# validate some of the data
assert "nvr" in bootstrap and isinstance(bootstrap["nvr"], dict)
nvr_dict = bootstrap["nvr"]
# should have been anonymized
assert nvr_dict["id"] != nvr.id
assert nvr_dict["mac"] != nvr.mac
assert nvr_dict["host"] != str(nvr.host)
# should have been kept
assert nvr_dict["firmwareVersion"] == nvr.firmware_version
assert nvr_dict["version"] == str(nvr.version)
assert nvr_dict["type"] == nvr.type
assert (
"lights" in bootstrap
and isinstance(bootstrap["lights"], list)
and len(bootstrap["lights"]) == 1
)
light_dict = bootstrap["lights"][0]
# should have been anonymized
assert light_dict["id"] != light.id
assert light_dict["name"] != light.mac
assert light_dict["mac"] != light.mac
assert light_dict["host"] != str(light.host)
# should have been kept
assert light_dict["firmwareVersion"] == light.firmware_version
assert light_dict["type"] == light.type

View File

@@ -0,0 +1,690 @@
"""Test the UniFi Protect event platform."""
from __future__ import annotations
from datetime import datetime, timedelta
from unittest.mock import Mock
from uiprotect.data import Camera, Event, EventType, ModelType, SmartDetectObjectType
from homeassistant.components.unifiprotect.const import (
ATTR_EVENT_ID,
DEFAULT_ATTRIBUTION,
)
from homeassistant.components.unifiprotect.event import EVENT_DESCRIPTIONS
from homeassistant.const import ATTR_ATTRIBUTION, Platform
from homeassistant.core import Event as HAEvent, HomeAssistant, callback
from homeassistant.helpers.event import async_track_state_change_event
from .utils import (
MockUFPFixture,
adopt_devices,
assert_entity_counts,
ids_from_device_description,
init_entry,
remove_entities,
)
async def test_camera_remove(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera, unadopted_camera: Camera
) -> None:
"""Test removing and re-adding a camera device."""
ufp.api.bootstrap.nvr.system_info.ustorage = None
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.EVENT, 3, 3)
await remove_entities(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.EVENT, 0, 0)
await adopt_devices(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.EVENT, 3, 3)
async def test_doorbell_ring(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
fixed_now: datetime,
) -> None:
"""Test a doorbell ring event."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.EVENT, 3, 3)
events: list[HAEvent] = []
@callback
def _capture_event(event: HAEvent) -> None:
events.append(event)
_, entity_id = ids_from_device_description(
Platform.EVENT, doorbell, EVENT_DESCRIPTIONS[0]
)
unsub = async_track_state_change_event(hass, entity_id, _capture_event)
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.RING,
start=fixed_now - timedelta(seconds=1),
end=None,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
camera_id=doorbell.id,
api=ufp.api,
)
new_camera = doorbell.model_copy()
new_camera.last_ring_event_id = "test_event_id"
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(events) == 1
state = events[0].data["new_state"]
assert state
timestamp = state.state
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
assert state.attributes[ATTR_EVENT_ID] == "test_event_id"
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.RING,
start=fixed_now - timedelta(seconds=1),
end=fixed_now + timedelta(seconds=1),
score=50,
smart_detect_types=[],
smart_detect_event_ids=[],
camera_id=doorbell.id,
api=ufp.api,
)
new_camera = doorbell.model_copy()
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
# Event is already seen and has end, should now be off
state = hass.states.get(entity_id)
assert state
assert state.state == timestamp
# Now send an event that has an end right away
event = Event(
model=ModelType.EVENT,
id="new_event_id",
type=EventType.RING,
start=fixed_now - timedelta(seconds=1),
end=fixed_now + timedelta(seconds=1),
score=80,
smart_detect_types=[SmartDetectObjectType.PACKAGE],
smart_detect_event_ids=[],
camera_id=doorbell.id,
api=ufp.api,
)
new_camera = doorbell.model_copy()
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == timestamp
unsub()
async def test_doorbell_nfc_scanned(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
fixed_now: datetime,
) -> None:
"""Test a doorbell NFC scanned event."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.EVENT, 3, 3)
events: list[HAEvent] = []
@callback
def _capture_event(event: HAEvent) -> None:
events.append(event)
_, entity_id = ids_from_device_description(
Platform.EVENT, doorbell, EVENT_DESCRIPTIONS[1]
)
ulp_id = "ulp_id"
test_user_full_name = "Test User"
test_nfc_id = "test_nfc_id"
unsub = async_track_state_change_event(hass, entity_id, _capture_event)
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.NFC_CARD_SCANNED,
start=fixed_now - timedelta(seconds=1),
end=None,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
camera_id=doorbell.id,
api=ufp.api,
metadata={"nfc": {"nfc_id": test_nfc_id, "user_id": "test_user_id"}},
)
new_camera = doorbell.copy()
new_camera.last_nfc_card_scanned_event_id = "test_event_id"
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
mock_keyring = Mock()
mock_keyring.registry_id = test_nfc_id
mock_keyring.registry_type = "nfc"
mock_keyring.ulp_user = ulp_id
ufp.api.bootstrap.keyrings.add(mock_keyring)
mock_ulp_user = Mock()
mock_ulp_user.ulp_id = ulp_id
mock_ulp_user.full_name = test_user_full_name
mock_ulp_user.status = "ACTIVE"
ufp.api.bootstrap.ulp_users.add(mock_ulp_user)
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(events) == 1
state = events[0].data["new_state"]
assert state
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
assert state.attributes[ATTR_EVENT_ID] == "test_event_id"
assert state.attributes["nfc_id"] == "test_nfc_id"
assert state.attributes["full_name"] == test_user_full_name
unsub()
async def test_doorbell_nfc_scanned_ulpusr_deactivated(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
fixed_now: datetime,
) -> None:
"""Test a doorbell NFC scanned event."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.EVENT, 3, 3)
events: list[HAEvent] = []
@callback
def _capture_event(event: HAEvent) -> None:
events.append(event)
_, entity_id = ids_from_device_description(
Platform.EVENT, doorbell, EVENT_DESCRIPTIONS[1]
)
ulp_id = "ulp_id"
test_user_full_name = "Test User"
test_nfc_id = "test_nfc_id"
unsub = async_track_state_change_event(hass, entity_id, _capture_event)
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.NFC_CARD_SCANNED,
start=fixed_now - timedelta(seconds=1),
end=None,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
camera_id=doorbell.id,
api=ufp.api,
metadata={"nfc": {"nfc_id": test_nfc_id, "user_id": "test_user_id"}},
)
new_camera = doorbell.copy()
new_camera.last_nfc_card_scanned_event_id = "test_event_id"
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
mock_keyring = Mock()
mock_keyring.registry_id = test_nfc_id
mock_keyring.registry_type = "nfc"
mock_keyring.ulp_user = ulp_id
ufp.api.bootstrap.keyrings.add(mock_keyring)
mock_ulp_user = Mock()
mock_ulp_user.ulp_id = ulp_id
mock_ulp_user.full_name = test_user_full_name
mock_ulp_user.status = "DEACTIVATED"
ufp.api.bootstrap.ulp_users.add(mock_ulp_user)
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(events) == 1
state = events[0].data["new_state"]
assert state
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
assert state.attributes[ATTR_EVENT_ID] == "test_event_id"
assert state.attributes["nfc_id"] == "test_nfc_id"
assert state.attributes["full_name"] == "Test User"
assert state.attributes["user_status"] == "DEACTIVATED"
unsub()
async def test_doorbell_nfc_scanned_no_ulpusr(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
fixed_now: datetime,
) -> None:
"""Test a doorbell NFC scanned event."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.EVENT, 3, 3)
events: list[HAEvent] = []
@callback
def _capture_event(event: HAEvent) -> None:
events.append(event)
_, entity_id = ids_from_device_description(
Platform.EVENT, doorbell, EVENT_DESCRIPTIONS[1]
)
ulp_id = "ulp_id"
test_nfc_id = "test_nfc_id"
unsub = async_track_state_change_event(hass, entity_id, _capture_event)
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.NFC_CARD_SCANNED,
start=fixed_now - timedelta(seconds=1),
end=None,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
camera_id=doorbell.id,
api=ufp.api,
metadata={"nfc": {"nfc_id": test_nfc_id, "user_id": "test_user_id"}},
)
new_camera = doorbell.copy()
new_camera.last_nfc_card_scanned_event_id = "test_event_id"
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
mock_keyring = Mock()
mock_keyring.registry_id = test_nfc_id
mock_keyring.registry_type = "nfc"
mock_keyring.ulp_user = ulp_id
ufp.api.bootstrap.keyrings.add(mock_keyring)
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(events) == 1
state = events[0].data["new_state"]
assert state
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
assert state.attributes[ATTR_EVENT_ID] == "test_event_id"
assert state.attributes["nfc_id"] == "test_nfc_id"
assert state.attributes["full_name"] == ""
unsub()
async def test_doorbell_nfc_scanned_no_keyring(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
fixed_now: datetime,
) -> None:
"""Test a doorbell NFC scanned event."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.EVENT, 3, 3)
events: list[HAEvent] = []
@callback
def _capture_event(event: HAEvent) -> None:
events.append(event)
_, entity_id = ids_from_device_description(
Platform.EVENT, doorbell, EVENT_DESCRIPTIONS[1]
)
test_nfc_id = "test_nfc_id"
unsub = async_track_state_change_event(hass, entity_id, _capture_event)
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.NFC_CARD_SCANNED,
start=fixed_now - timedelta(seconds=1),
end=None,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
camera_id=doorbell.id,
api=ufp.api,
metadata={"nfc": {"nfc_id": test_nfc_id, "user_id": "test_user_id"}},
)
new_camera = doorbell.model_copy()
new_camera.last_nfc_card_scanned_event_id = "test_event_id"
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(events) == 1
state = events[0].data["new_state"]
assert state
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
assert state.attributes[ATTR_EVENT_ID] == "test_event_id"
assert state.attributes["nfc_id"] == "test_nfc_id"
assert state.attributes["full_name"] == ""
unsub()
async def test_doorbell_fingerprint_identified(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
fixed_now: datetime,
) -> None:
"""Test a doorbell fingerprint identified event."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.EVENT, 3, 3)
events: list[HAEvent] = []
@callback
def _capture_event(event: HAEvent) -> None:
events.append(event)
_, entity_id = ids_from_device_description(
Platform.EVENT, doorbell, EVENT_DESCRIPTIONS[2]
)
ulp_id = "ulp_id"
test_user_full_name = "Test User"
unsub = async_track_state_change_event(hass, entity_id, _capture_event)
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.FINGERPRINT_IDENTIFIED,
start=fixed_now - timedelta(seconds=1),
end=None,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
camera_id=doorbell.id,
api=ufp.api,
metadata={"fingerprint": {"ulp_id": ulp_id}},
)
new_camera = doorbell.copy()
new_camera.last_fingerprint_identified_event_id = "test_event_id"
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
mock_ulp_user = Mock()
mock_ulp_user.ulp_id = ulp_id
mock_ulp_user.full_name = test_user_full_name
mock_ulp_user.status = "ACTIVE"
ufp.api.bootstrap.ulp_users.add(mock_ulp_user)
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(events) == 1
state = events[0].data["new_state"]
assert state
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
assert state.attributes[ATTR_EVENT_ID] == "test_event_id"
assert state.attributes["ulp_id"] == ulp_id
assert state.attributes["full_name"] == test_user_full_name
unsub()
async def test_doorbell_fingerprint_identified_user_deactivated(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
fixed_now: datetime,
) -> None:
"""Test a doorbell fingerprint identified event."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.EVENT, 3, 3)
events: list[HAEvent] = []
@callback
def _capture_event(event: HAEvent) -> None:
events.append(event)
_, entity_id = ids_from_device_description(
Platform.EVENT, doorbell, EVENT_DESCRIPTIONS[2]
)
ulp_id = "ulp_id"
test_user_full_name = "Test User"
unsub = async_track_state_change_event(hass, entity_id, _capture_event)
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.FINGERPRINT_IDENTIFIED,
start=fixed_now - timedelta(seconds=1),
end=None,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
camera_id=doorbell.id,
api=ufp.api,
metadata={"fingerprint": {"ulp_id": ulp_id}},
)
new_camera = doorbell.copy()
new_camera.last_fingerprint_identified_event_id = "test_event_id"
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
mock_ulp_user = Mock()
mock_ulp_user.ulp_id = ulp_id
mock_ulp_user.full_name = test_user_full_name
mock_ulp_user.status = "DEACTIVATED"
ufp.api.bootstrap.ulp_users.add(mock_ulp_user)
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(events) == 1
state = events[0].data["new_state"]
assert state
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
assert state.attributes[ATTR_EVENT_ID] == "test_event_id"
assert state.attributes["ulp_id"] == ulp_id
assert state.attributes["full_name"] == "Test User"
assert state.attributes["user_status"] == "DEACTIVATED"
unsub()
async def test_doorbell_fingerprint_identified_no_user(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
fixed_now: datetime,
) -> None:
"""Test a doorbell fingerprint identified event."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.EVENT, 3, 3)
events: list[HAEvent] = []
@callback
def _capture_event(event: HAEvent) -> None:
events.append(event)
_, entity_id = ids_from_device_description(
Platform.EVENT, doorbell, EVENT_DESCRIPTIONS[2]
)
ulp_id = "ulp_id"
unsub = async_track_state_change_event(hass, entity_id, _capture_event)
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.FINGERPRINT_IDENTIFIED,
start=fixed_now - timedelta(seconds=1),
end=None,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
camera_id=doorbell.id,
api=ufp.api,
metadata={"fingerprint": {"ulp_id": ulp_id}},
)
new_camera = doorbell.model_copy()
new_camera.last_fingerprint_identified_event_id = "test_event_id"
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(events) == 1
state = events[0].data["new_state"]
assert state
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
assert state.attributes[ATTR_EVENT_ID] == "test_event_id"
assert state.attributes["ulp_id"] == ulp_id
assert state.attributes["full_name"] == ""
unsub()
async def test_doorbell_fingerprint_not_identified(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
fixed_now: datetime,
) -> None:
"""Test a doorbell fingerprint identified event."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.EVENT, 3, 3)
events: list[HAEvent] = []
@callback
def _capture_event(event: HAEvent) -> None:
events.append(event)
_, entity_id = ids_from_device_description(
Platform.EVENT, doorbell, EVENT_DESCRIPTIONS[2]
)
unsub = async_track_state_change_event(hass, entity_id, _capture_event)
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.FINGERPRINT_IDENTIFIED,
start=fixed_now - timedelta(seconds=1),
end=None,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
camera_id=doorbell.id,
api=ufp.api,
metadata={"fingerprint": {}},
)
new_camera = doorbell.model_copy()
new_camera.last_fingerprint_identified_event_id = "test_event_id"
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(events) == 1
state = events[0].data["new_state"]
assert state
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
assert state.attributes[ATTR_EVENT_ID] == "test_event_id"
assert state.attributes["ulp_id"] == ""
unsub()

View File

@@ -0,0 +1,347 @@
"""Test the UniFi Protect setup flow."""
from __future__ import annotations
from unittest.mock import AsyncMock, Mock, patch
import pytest
from uiprotect import NotAuthorized, NvrError, ProtectApiClient
from uiprotect.api import DEVICE_UPDATE_INTERVAL
from uiprotect.data import NVR, Bootstrap, CloudAccount, Light
from homeassistant.components.unifiprotect.const import (
AUTH_RETRIES,
CONF_DISABLE_RTSP,
DOMAIN,
)
from homeassistant.components.unifiprotect.data import (
async_ufp_instance_for_config_entry_ids,
)
from homeassistant.config_entries import ConfigEntry, ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.setup import async_setup_component
from . import _patch_discovery
from .utils import MockUFPFixture, init_entry, time_changed
from tests.common import MockConfigEntry
from tests.typing import WebSocketGenerator
async def test_setup(hass: HomeAssistant, ufp: MockUFPFixture) -> None:
"""Test working setup of unifiprotect entry."""
await hass.config_entries.async_setup(ufp.entry.entry_id)
await hass.async_block_till_done()
assert ufp.entry.state is ConfigEntryState.LOADED
assert ufp.api.update.called
assert ufp.entry.unique_id == ufp.api.bootstrap.nvr.mac
async def test_setup_multiple(
hass: HomeAssistant,
ufp: MockUFPFixture,
bootstrap: Bootstrap,
) -> None:
"""Test working setup of unifiprotect entry."""
await hass.config_entries.async_setup(ufp.entry.entry_id)
await hass.async_block_till_done()
assert ufp.entry.state is ConfigEntryState.LOADED
assert ufp.api.update.called
assert ufp.entry.unique_id == ufp.api.bootstrap.nvr.mac
nvr = bootstrap.nvr
nvr._api = ufp.api
nvr.mac = "A1E00C826983"
ufp.api.get_nvr = AsyncMock(return_value=nvr)
with patch(
"homeassistant.components.unifiprotect.utils.ProtectApiClient"
) as mock_api:
mock_config = MockConfigEntry(
domain=DOMAIN,
data={
"host": "1.1.1.1",
"username": "test-username",
"password": "test-password",
"id": "UnifiProtect",
"port": 443,
"verify_ssl": False,
},
version=2,
)
mock_config.add_to_hass(hass)
mock_api.return_value = ufp.api
await hass.config_entries.async_setup(mock_config.entry_id)
await hass.async_block_till_done()
assert mock_config.state is ConfigEntryState.LOADED
assert ufp.api.update.called
assert mock_config.unique_id == ufp.api.bootstrap.nvr.mac
async def test_reload(hass: HomeAssistant, ufp: MockUFPFixture) -> None:
"""Test updating entry reload entry."""
await hass.config_entries.async_setup(ufp.entry.entry_id)
await hass.async_block_till_done()
assert ufp.entry.state is ConfigEntryState.LOADED
options = dict(ufp.entry.options)
options[CONF_DISABLE_RTSP] = True
hass.config_entries.async_update_entry(ufp.entry, options=options)
await hass.async_block_till_done()
assert ufp.entry.state is ConfigEntryState.LOADED
assert ufp.api.async_disconnect_ws.called
async def test_unload(hass: HomeAssistant, ufp: MockUFPFixture, light: Light) -> None:
"""Test unloading of unifiprotect entry."""
await init_entry(hass, ufp, [light])
assert ufp.entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(ufp.entry.entry_id)
assert ufp.entry.state is ConfigEntryState.NOT_LOADED
assert ufp.api.async_disconnect_ws.called
async def test_setup_too_old(
hass: HomeAssistant, ufp: MockUFPFixture, old_nvr: NVR
) -> None:
"""Test setup of unifiprotect entry with too old of version of UniFi Protect."""
old_bootstrap = ufp.api.bootstrap.model_copy()
old_bootstrap.nvr = old_nvr
ufp.api.update.return_value = old_bootstrap
ufp.api.bootstrap = old_bootstrap
await hass.config_entries.async_setup(ufp.entry.entry_id)
await hass.async_block_till_done()
assert ufp.entry.state is ConfigEntryState.SETUP_ERROR
async def test_setup_cloud_account(
hass: HomeAssistant,
ufp: MockUFPFixture,
cloud_account: CloudAccount,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test setup of unifiprotect entry with cloud account."""
bootstrap = ufp.api.bootstrap
user = bootstrap.users[bootstrap.auth_user_id]
user.cloud_account = cloud_account
bootstrap.users[bootstrap.auth_user_id] = user
ufp.api.get_bootstrap.return_value = bootstrap
ws_client = await hass_ws_client(hass)
await hass.config_entries.async_setup(ufp.entry.entry_id)
await hass.async_block_till_done()
assert ufp.entry.state is ConfigEntryState.LOADED
await ws_client.send_json({"id": 1, "type": "repairs/list_issues"})
msg = await ws_client.receive_json()
assert msg["success"]
assert len(msg["result"]["issues"]) > 0
issue = None
for i in msg["result"]["issues"]:
if i["issue_id"] == "cloud_user":
issue = i
assert issue is not None
async def test_setup_failed_update(hass: HomeAssistant, ufp: MockUFPFixture) -> None:
"""Test setup of unifiprotect entry with failed update."""
ufp.api.update = AsyncMock(side_effect=NvrError)
await hass.config_entries.async_setup(ufp.entry.entry_id)
await hass.async_block_till_done()
assert ufp.entry.state is ConfigEntryState.SETUP_RETRY
assert ufp.api.update.called
async def test_setup_failed_update_reauth(
hass: HomeAssistant, ufp: MockUFPFixture
) -> None:
"""Test setup of unifiprotect entry with update that gives unauthroized error."""
await hass.config_entries.async_setup(ufp.entry.entry_id)
await hass.async_block_till_done()
assert ufp.entry.state is ConfigEntryState.LOADED
# reauth should not be triggered until there are 10 auth failures in a row
# to verify it is not transient
ufp.api.update = AsyncMock(side_effect=NotAuthorized)
for _ in range(AUTH_RETRIES):
await time_changed(hass, DEVICE_UPDATE_INTERVAL)
assert len(hass.config_entries.flow._progress) == 0
assert ufp.api.update.call_count == AUTH_RETRIES
assert ufp.entry.state is ConfigEntryState.LOADED
await time_changed(hass, DEVICE_UPDATE_INTERVAL)
assert ufp.api.update.call_count == AUTH_RETRIES + 1
assert len(hass.config_entries.flow._progress) == 1
async def test_setup_failed_error(hass: HomeAssistant, ufp: MockUFPFixture) -> None:
"""Test setup of unifiprotect entry with generic error."""
ufp.api.update = AsyncMock(side_effect=NvrError)
await hass.config_entries.async_setup(ufp.entry.entry_id)
await hass.async_block_till_done()
assert ufp.entry.state is ConfigEntryState.SETUP_RETRY
async def test_setup_failed_auth(hass: HomeAssistant, ufp: MockUFPFixture) -> None:
"""Test setup of unifiprotect entry with unauthorized error after multiple retries."""
ufp.api.update = AsyncMock(side_effect=NotAuthorized)
await hass.config_entries.async_setup(ufp.entry.entry_id)
assert ufp.entry.state is ConfigEntryState.SETUP_RETRY
for _ in range(AUTH_RETRIES - 1):
await hass.config_entries.async_reload(ufp.entry.entry_id)
assert ufp.entry.state is ConfigEntryState.SETUP_RETRY
await hass.config_entries.async_reload(ufp.entry.entry_id)
assert ufp.entry.state is ConfigEntryState.SETUP_ERROR
async def test_setup_starts_discovery(
hass: HomeAssistant, ufp_config_entry: ConfigEntry, ufp_client: ProtectApiClient
) -> None:
"""Test setting up will start discovery."""
with (
_patch_discovery(),
patch(
"homeassistant.components.unifiprotect.utils.ProtectApiClient"
) as mock_api,
):
ufp_config_entry.add_to_hass(hass)
mock_api.return_value = ufp_client
ufp = MockUFPFixture(ufp_config_entry, ufp_client)
await hass.config_entries.async_setup(ufp.entry.entry_id)
await hass.async_block_till_done()
assert ufp.entry.state is ConfigEntryState.LOADED
await hass.async_block_till_done()
assert len(hass.config_entries.flow.async_progress_by_handler(DOMAIN)) == 1
async def test_device_remove_devices(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
light: Light,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test we can only remove a device that no longer exists."""
await init_entry(hass, ufp, [light])
assert await async_setup_component(hass, "config", {})
entity_id = "light.test_light"
entry_id = ufp.entry.entry_id
entity = entity_registry.async_get(entity_id)
assert entity is not None
live_device_entry = device_registry.async_get(entity.device_id)
client = await hass_ws_client(hass)
response = await client.remove_device(live_device_entry.id, entry_id)
assert not response["success"]
dead_device_entry = device_registry.async_get_or_create(
config_entry_id=entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "e9:88:e7:b8:b4:40")},
)
response = await client.remove_device(dead_device_entry.id, entry_id)
assert response["success"]
async def test_device_remove_devices_nvr(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
ufp: MockUFPFixture,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test we can only remove a NVR device that no longer exists."""
assert await async_setup_component(hass, "config", {})
ufp.api.get_bootstrap = AsyncMock(return_value=ufp.api.bootstrap)
await hass.config_entries.async_setup(ufp.entry.entry_id)
await hass.async_block_till_done()
entry_id = ufp.entry.entry_id
live_device_entry = list(device_registry.devices.values())[0]
client = await hass_ws_client(hass)
response = await client.remove_device(live_device_entry.id, entry_id)
assert not response["success"]
@pytest.mark.parametrize(
("mock_entries", "expected_result"),
[
pytest.param(
[
MockConfigEntry(
domain=DOMAIN,
entry_id="1",
data={},
),
MockConfigEntry(
domain="other_domain",
entry_id="2",
data={},
),
],
"mock_api_instance_1",
id="one_matching_domain",
),
pytest.param(
[
MockConfigEntry(
domain="other_domain",
entry_id="1",
data={},
),
MockConfigEntry(
domain="other_domain",
entry_id="2",
data={},
),
],
None,
id="no_matching_domain",
),
],
)
async def test_async_ufp_instance_for_config_entry_ids(
hass: HomeAssistant,
mock_entries: list[MockConfigEntry],
expected_result: str | None,
) -> None:
"""Test async_ufp_instance_for_config_entry_ids with various entry configurations."""
for index, entry in enumerate(mock_entries):
entry.add_to_hass(hass)
entry.runtime_data = Mock(api=f"mock_api_instance_{index + 1}")
entry_ids = {entry.entry_id for entry in mock_entries}
result = async_ufp_instance_for_config_entry_ids(hass, entry_ids)
assert result == expected_result

View File

@@ -0,0 +1,136 @@
"""Test the UniFi Protect light platform."""
from __future__ import annotations
from unittest.mock import AsyncMock, Mock
from uiprotect.data import Light
from uiprotect.data.types import LEDLevel
from homeassistant.components.light import ATTR_BRIGHTNESS
from homeassistant.components.unifiprotect.const import DEFAULT_ATTRIBUTION
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_ENTITY_ID,
STATE_OFF,
STATE_ON,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .utils import (
MockUFPFixture,
adopt_devices,
assert_entity_counts,
init_entry,
remove_entities,
)
async def test_light_remove(
hass: HomeAssistant, ufp: MockUFPFixture, light: Light
) -> None:
"""Test removing and re-adding a light device."""
await init_entry(hass, ufp, [light])
assert_entity_counts(hass, Platform.LIGHT, 1, 1)
await remove_entities(hass, ufp, [light])
assert_entity_counts(hass, Platform.LIGHT, 0, 0)
await adopt_devices(hass, ufp, [light])
assert_entity_counts(hass, Platform.LIGHT, 1, 1)
async def test_light_setup(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
light: Light,
unadopted_light: Light,
) -> None:
"""Test light entity setup."""
await init_entry(hass, ufp, [light, unadopted_light])
assert_entity_counts(hass, Platform.LIGHT, 1, 1)
unique_id = light.mac
entity_id = "light.test_light"
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_light_update(
hass: HomeAssistant, ufp: MockUFPFixture, light: Light, unadopted_light: Light
) -> None:
"""Test light entity update."""
await init_entry(hass, ufp, [light, unadopted_light])
assert_entity_counts(hass, Platform.LIGHT, 1, 1)
new_light = light.model_copy()
new_light.is_light_on = True
new_light.light_device_settings.led_level = LEDLevel(3)
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_light
ufp.api.bootstrap.lights = {new_light.id: new_light}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get("light.test_light")
assert state
assert state.state == STATE_ON
assert state.attributes[ATTR_BRIGHTNESS] == 128
async def test_light_turn_on(
hass: HomeAssistant, ufp: MockUFPFixture, light: Light, unadopted_light: Light
) -> None:
"""Test light entity turn off."""
await init_entry(hass, ufp, [light, unadopted_light])
assert_entity_counts(hass, Platform.LIGHT, 1, 1)
entity_id = "light.test_light"
light.__pydantic_fields__["set_light"] = Mock(final=False, frozen=False)
light.set_light = AsyncMock()
await hass.services.async_call(
"light",
"turn_on",
{ATTR_ENTITY_ID: entity_id, ATTR_BRIGHTNESS: 128},
blocking=True,
)
light.set_light.assert_called_once_with(True, 3)
async def test_light_turn_off(
hass: HomeAssistant, ufp: MockUFPFixture, light: Light, unadopted_light: Light
) -> None:
"""Test light entity turn on."""
await init_entry(hass, ufp, [light, unadopted_light])
assert_entity_counts(hass, Platform.LIGHT, 1, 1)
entity_id = "light.test_light"
light.__pydantic_fields__["set_light"] = Mock(final=False, frozen=False)
light.set_light = AsyncMock()
await hass.services.async_call(
"light",
"turn_off",
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
light.set_light.assert_called_once_with(False)

View File

@@ -0,0 +1,258 @@
"""Test the UniFi Protect lock platform."""
from __future__ import annotations
from unittest.mock import AsyncMock, Mock
from uiprotect.data import Doorlock, LockStatusType
from homeassistant.components.lock import LockState
from homeassistant.components.unifiprotect.const import DEFAULT_ATTRIBUTION
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_ENTITY_ID,
STATE_UNAVAILABLE,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .utils import (
MockUFPFixture,
adopt_devices,
assert_entity_counts,
init_entry,
remove_entities,
)
async def test_lock_remove(
hass: HomeAssistant, ufp: MockUFPFixture, doorlock: Doorlock
) -> None:
"""Test removing and re-adding a lock device."""
await init_entry(hass, ufp, [doorlock])
assert_entity_counts(hass, Platform.LOCK, 1, 1)
await remove_entities(hass, ufp, [doorlock])
assert_entity_counts(hass, Platform.LOCK, 0, 0)
await adopt_devices(hass, ufp, [doorlock])
assert_entity_counts(hass, Platform.LOCK, 1, 1)
async def test_lock_setup(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
doorlock: Doorlock,
unadopted_doorlock: Doorlock,
) -> None:
"""Test lock entity setup."""
await init_entry(hass, ufp, [doorlock, unadopted_doorlock])
assert_entity_counts(hass, Platform.LOCK, 1, 1)
unique_id = f"{doorlock.mac}_lock"
entity_id = "lock.test_lock_lock"
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == LockState.UNLOCKED
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_lock_locked(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorlock: Doorlock,
unadopted_doorlock: Doorlock,
) -> None:
"""Test lock entity locked."""
await init_entry(hass, ufp, [doorlock, unadopted_doorlock])
assert_entity_counts(hass, Platform.LOCK, 1, 1)
new_lock = doorlock.model_copy()
new_lock.lock_status = LockStatusType.CLOSED
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_lock
ufp.api.bootstrap.doorlocks = {new_lock.id: new_lock}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get("lock.test_lock_lock")
assert state
assert state.state == LockState.LOCKED
async def test_lock_unlocking(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorlock: Doorlock,
unadopted_doorlock: Doorlock,
) -> None:
"""Test lock entity unlocking."""
await init_entry(hass, ufp, [doorlock, unadopted_doorlock])
assert_entity_counts(hass, Platform.LOCK, 1, 1)
new_lock = doorlock.model_copy()
new_lock.lock_status = LockStatusType.OPENING
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_lock
ufp.api.bootstrap.doorlocks = {new_lock.id: new_lock}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get("lock.test_lock_lock")
assert state
assert state.state == LockState.UNLOCKING
async def test_lock_locking(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorlock: Doorlock,
unadopted_doorlock: Doorlock,
) -> None:
"""Test lock entity locking."""
await init_entry(hass, ufp, [doorlock, unadopted_doorlock])
assert_entity_counts(hass, Platform.LOCK, 1, 1)
new_lock = doorlock.model_copy()
new_lock.lock_status = LockStatusType.CLOSING
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_lock
ufp.api.bootstrap.doorlocks = {new_lock.id: new_lock}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get("lock.test_lock_lock")
assert state
assert state.state == LockState.LOCKING
async def test_lock_jammed(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorlock: Doorlock,
unadopted_doorlock: Doorlock,
) -> None:
"""Test lock entity jammed."""
await init_entry(hass, ufp, [doorlock, unadopted_doorlock])
assert_entity_counts(hass, Platform.LOCK, 1, 1)
new_lock = doorlock.model_copy()
new_lock.lock_status = LockStatusType.JAMMED_WHILE_CLOSING
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_lock
ufp.api.bootstrap.doorlocks = {new_lock.id: new_lock}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get("lock.test_lock_lock")
assert state
assert state.state == LockState.JAMMED
async def test_lock_unavailable(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorlock: Doorlock,
unadopted_doorlock: Doorlock,
) -> None:
"""Test lock entity unavailable."""
await init_entry(hass, ufp, [doorlock, unadopted_doorlock])
assert_entity_counts(hass, Platform.LOCK, 1, 1)
new_lock = doorlock.model_copy()
new_lock.lock_status = LockStatusType.NOT_CALIBRATED
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_lock
ufp.api.bootstrap.doorlocks = {new_lock.id: new_lock}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get("lock.test_lock_lock")
assert state
assert state.state == STATE_UNAVAILABLE
async def test_lock_do_lock(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorlock: Doorlock,
unadopted_doorlock: Doorlock,
) -> None:
"""Test lock entity lock service."""
await init_entry(hass, ufp, [doorlock, unadopted_doorlock])
assert_entity_counts(hass, Platform.LOCK, 1, 1)
doorlock.__pydantic_fields__["close_lock"] = Mock(final=False, frozen=False)
doorlock.close_lock = AsyncMock()
await hass.services.async_call(
"lock",
"lock",
{ATTR_ENTITY_ID: "lock.test_lock_lock"},
blocking=True,
)
doorlock.close_lock.assert_called_once()
async def test_lock_do_unlock(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorlock: Doorlock,
unadopted_doorlock: Doorlock,
) -> None:
"""Test lock entity unlock service."""
await init_entry(hass, ufp, [doorlock, unadopted_doorlock])
assert_entity_counts(hass, Platform.LOCK, 1, 1)
new_lock = doorlock.model_copy()
new_lock.lock_status = LockStatusType.CLOSED
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_lock
ufp.api.bootstrap.doorlocks = {new_lock.id: new_lock}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
doorlock.__pydantic_fields__["open_lock"] = Mock(final=False, frozen=False)
new_lock.open_lock = AsyncMock()
await hass.services.async_call(
"lock",
"unlock",
{ATTR_ENTITY_ID: "lock.test_lock_lock"},
blocking=True,
)
new_lock.open_lock.assert_called_once()

View File

@@ -0,0 +1,303 @@
"""Test the UniFi Protect media_player platform."""
from __future__ import annotations
from unittest.mock import AsyncMock, Mock, patch
import pytest
from uiprotect.data import Camera
from uiprotect.exceptions import StreamError
from homeassistant.components.media_player import (
ATTR_MEDIA_CONTENT_TYPE,
ATTR_MEDIA_VOLUME_LEVEL,
)
from homeassistant.components.unifiprotect.const import DEFAULT_ATTRIBUTION
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_ENTITY_ID,
ATTR_SUPPORTED_FEATURES,
STATE_IDLE,
STATE_PLAYING,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from .utils import (
MockUFPFixture,
adopt_devices,
assert_entity_counts,
init_entry,
remove_entities,
)
async def test_media_player_camera_remove(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera
) -> None:
"""Test removing and re-adding a light device."""
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.MEDIA_PLAYER, 1, 1)
await remove_entities(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.MEDIA_PLAYER, 0, 0)
await adopt_devices(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.MEDIA_PLAYER, 1, 1)
async def test_media_player_setup(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
) -> None:
"""Test media_player entity setup."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.MEDIA_PLAYER, 1, 1)
unique_id = f"{doorbell.mac}_speaker"
entity_id = "media_player.test_camera_speaker"
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
expected_volume = float(doorbell.speaker_settings.volume / 100)
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_IDLE
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 136708
assert state.attributes[ATTR_MEDIA_CONTENT_TYPE] == "music"
assert state.attributes[ATTR_MEDIA_VOLUME_LEVEL] == expected_volume
async def test_media_player_update(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
) -> None:
"""Test media_player entity update."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.MEDIA_PLAYER, 1, 1)
new_camera = doorbell.model_copy()
new_camera.talkback_stream = Mock()
new_camera.talkback_stream.is_running = True
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_camera
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get("media_player.test_camera_speaker")
assert state
assert state.state == STATE_PLAYING
async def test_media_player_set_volume(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
) -> None:
"""Test media_player entity test set_volume_level."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.MEDIA_PLAYER, 1, 1)
doorbell.__pydantic_fields__["set_speaker_volume"] = Mock(final=False, frozen=False)
doorbell.set_speaker_volume = AsyncMock()
await hass.services.async_call(
"media_player",
"volume_set",
{ATTR_ENTITY_ID: "media_player.test_camera_speaker", "volume_level": 0.5},
blocking=True,
)
doorbell.set_speaker_volume.assert_called_once_with(50)
async def test_media_player_stop(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
) -> None:
"""Test media_player entity test media_stop."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.MEDIA_PLAYER, 1, 1)
new_camera = doorbell.model_copy()
new_camera.talkback_stream = AsyncMock()
new_camera.talkback_stream.is_running = True
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_camera
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
await hass.services.async_call(
"media_player",
"media_stop",
{ATTR_ENTITY_ID: "media_player.test_camera_speaker"},
blocking=True,
)
new_camera.talkback_stream.stop.assert_called_once()
async def test_media_player_play(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
) -> None:
"""Test media_player entity test play_media."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.MEDIA_PLAYER, 1, 1)
doorbell.__pydantic_fields__["stop_audio"] = Mock(final=False, frozen=False)
doorbell.__pydantic_fields__["play_audio"] = Mock(final=False, frozen=False)
doorbell.__pydantic_fields__["wait_until_audio_completes"] = Mock(
final=False, frozen=False
)
doorbell.stop_audio = AsyncMock()
doorbell.play_audio = AsyncMock()
doorbell.wait_until_audio_completes = AsyncMock()
await hass.services.async_call(
"media_player",
"play_media",
{
ATTR_ENTITY_ID: "media_player.test_camera_speaker",
"media_content_id": "http://example.com/test.mp3",
"media_content_type": "music",
},
blocking=True,
)
doorbell.play_audio.assert_called_once_with(
"http://example.com/test.mp3", blocking=False
)
doorbell.wait_until_audio_completes.assert_called_once()
async def test_media_player_play_media_source(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
) -> None:
"""Test media_player entity test play_media."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.MEDIA_PLAYER, 1, 1)
doorbell.__pydantic_fields__["stop_audio"] = Mock(final=False, frozen=False)
doorbell.__pydantic_fields__["play_audio"] = Mock(final=False, frozen=False)
doorbell.__pydantic_fields__["wait_until_audio_completes"] = Mock(
final=False, frozen=False
)
doorbell.stop_audio = AsyncMock()
doorbell.play_audio = AsyncMock()
doorbell.wait_until_audio_completes = AsyncMock()
with patch(
"homeassistant.components.media_source.async_resolve_media",
return_value=Mock(url="http://example.com/test.mp3"),
):
await hass.services.async_call(
"media_player",
"play_media",
{
ATTR_ENTITY_ID: "media_player.test_camera_speaker",
"media_content_id": "media-source://some_source/some_id",
"media_content_type": "audio/mpeg",
},
blocking=True,
)
doorbell.play_audio.assert_called_once_with(
"http://example.com/test.mp3", blocking=False
)
doorbell.wait_until_audio_completes.assert_called_once()
async def test_media_player_play_invalid(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
) -> None:
"""Test media_player entity test play_media, not music."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.MEDIA_PLAYER, 1, 1)
doorbell.__pydantic_fields__["play_audio"] = Mock(final=False, frozen=False)
doorbell.play_audio = AsyncMock()
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
"media_player",
"play_media",
{
ATTR_ENTITY_ID: "media_player.test_camera_speaker",
"media_content_id": "/test.png",
"media_content_type": "image",
},
blocking=True,
)
assert not doorbell.play_audio.called
async def test_media_player_play_error(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
) -> None:
"""Test media_player entity test play_media, not music."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.MEDIA_PLAYER, 1, 1)
doorbell.__pydantic_fields__["play_audio"] = Mock(final=False, frozen=False)
doorbell.__pydantic_fields__["wait_until_audio_completes"] = Mock(
final=False, frozen=False
)
doorbell.play_audio = AsyncMock(side_effect=StreamError)
doorbell.wait_until_audio_completes = AsyncMock()
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
"media_player",
"play_media",
{
ATTR_ENTITY_ID: "media_player.test_camera_speaker",
"media_content_id": "/test.mp3",
"media_content_type": "music",
},
blocking=True,
)
assert doorbell.play_audio.called
assert not doorbell.wait_until_audio_completes.called

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,227 @@
"""Test the UniFi Protect setup flow."""
from __future__ import annotations
from unittest.mock import patch
from uiprotect.data import Camera
from homeassistant.components.automation import DOMAIN as AUTOMATION_DOMAIN
from homeassistant.components.script import DOMAIN as SCRIPT_DOMAIN
from homeassistant.components.unifiprotect.const import DOMAIN
from homeassistant.const import SERVICE_RELOAD, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from .utils import MockUFPFixture, init_entry
from tests.components.repairs import async_process_repairs_platforms
from tests.typing import WebSocketGenerator
async def test_deprecated_entity(
hass: HomeAssistant,
ufp: MockUFPFixture,
hass_ws_client: WebSocketGenerator,
doorbell: Camera,
) -> None:
"""Test Deprecate entity repair does not exist by default (new installs)."""
await init_entry(hass, ufp, [doorbell])
await async_process_repairs_platforms(hass)
ws_client = await hass_ws_client(hass)
await ws_client.send_json({"id": 1, "type": "repairs/list_issues"})
msg = await ws_client.receive_json()
assert msg["success"]
issue = None
for i in msg["result"]["issues"]:
if i["issue_id"] == "deprecate_hdr_switch":
issue = i
assert issue is None
async def test_deprecated_entity_no_automations(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
hass_ws_client: WebSocketGenerator,
doorbell: Camera,
) -> None:
"""Test Deprecate entity repair exists for existing installs."""
entity_registry.async_get_or_create(
Platform.SWITCH,
DOMAIN,
f"{doorbell.mac}_hdr_mode",
config_entry=ufp.entry,
)
await init_entry(hass, ufp, [doorbell])
await async_process_repairs_platforms(hass)
ws_client = await hass_ws_client(hass)
await ws_client.send_json({"id": 1, "type": "repairs/list_issues"})
msg = await ws_client.receive_json()
assert msg["success"]
issue = None
for i in msg["result"]["issues"]:
if i["issue_id"] == "deprecate_hdr_switch":
issue = i
assert issue is None
async def _load_automation(hass: HomeAssistant, entity_id: str):
assert await async_setup_component(
hass,
AUTOMATION_DOMAIN,
{
AUTOMATION_DOMAIN: [
{
"alias": "test1",
"trigger": [
{"platform": "state", "entity_id": entity_id},
{
"platform": "event",
"event_type": "state_changed",
"event_data": {"entity_id": entity_id},
},
],
"condition": {
"condition": "state",
"entity_id": entity_id,
"state": "on",
},
"action": [
{
"service": "test.script",
"data": {"entity_id": entity_id},
},
],
},
]
},
)
async def test_deprecate_entity_automation(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
hass_ws_client: WebSocketGenerator,
doorbell: Camera,
) -> None:
"""Test Deprecate entity repair exists for existing installs."""
entry = entity_registry.async_get_or_create(
Platform.SWITCH,
DOMAIN,
f"{doorbell.mac}_hdr_mode",
config_entry=ufp.entry,
)
await _load_automation(hass, entry.entity_id)
await init_entry(hass, ufp, [doorbell])
await async_process_repairs_platforms(hass)
ws_client = await hass_ws_client(hass)
await ws_client.send_json({"id": 1, "type": "repairs/list_issues"})
msg = await ws_client.receive_json()
assert msg["success"]
issue = None
for i in msg["result"]["issues"]:
if i["issue_id"] == "deprecate_hdr_switch":
issue = i
assert issue is not None
with patch(
"homeassistant.config.load_yaml_config_file",
autospec=True,
return_value={AUTOMATION_DOMAIN: []},
):
await hass.services.async_call(AUTOMATION_DOMAIN, SERVICE_RELOAD, blocking=True)
await hass.config_entries.async_reload(ufp.entry.entry_id)
await hass.async_block_till_done()
await ws_client.send_json({"id": 2, "type": "repairs/list_issues"})
msg = await ws_client.receive_json()
assert msg["success"]
issue = None
for i in msg["result"]["issues"]:
if i["issue_id"] == "deprecate_hdr_switch":
issue = i
assert issue is None
async def _load_script(hass: HomeAssistant, entity_id: str):
assert await async_setup_component(
hass,
SCRIPT_DOMAIN,
{
SCRIPT_DOMAIN: {
"test": {
"sequence": {
"service": "test.script",
"data": {"entity_id": entity_id},
}
}
},
},
)
async def test_deprecate_entity_script(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
hass_ws_client: WebSocketGenerator,
doorbell: Camera,
) -> None:
"""Test Deprecate entity repair exists for existing installs."""
entry = entity_registry.async_get_or_create(
Platform.SWITCH,
DOMAIN,
f"{doorbell.mac}_hdr_mode",
config_entry=ufp.entry,
)
await _load_script(hass, entry.entity_id)
await init_entry(hass, ufp, [doorbell])
await async_process_repairs_platforms(hass)
ws_client = await hass_ws_client(hass)
await ws_client.send_json({"id": 1, "type": "repairs/list_issues"})
msg = await ws_client.receive_json()
assert msg["success"]
issue = None
for i in msg["result"]["issues"]:
if i["issue_id"] == "deprecate_hdr_switch":
issue = i
assert issue is not None
with patch(
"homeassistant.config.load_yaml_config_file",
autospec=True,
return_value={SCRIPT_DOMAIN: {}},
):
await hass.services.async_call(SCRIPT_DOMAIN, SERVICE_RELOAD, blocking=True)
await hass.config_entries.async_reload(ufp.entry.entry_id)
await hass.async_block_till_done()
await ws_client.send_json({"id": 2, "type": "repairs/list_issues"})
msg = await ws_client.receive_json()
assert msg["success"]
issue = None
for i in msg["result"]["issues"]:
if i["issue_id"] == "deprecate_hdr_switch":
issue = i
assert issue is None

View File

@@ -0,0 +1,246 @@
"""Test the UniFi Protect number platform."""
from __future__ import annotations
from datetime import timedelta
from unittest.mock import AsyncMock, Mock
import pytest
from uiprotect.data import Camera, Doorlock, IRLEDMode, Light
from homeassistant.components.unifiprotect.const import DEFAULT_ATTRIBUTION
from homeassistant.components.unifiprotect.number import (
CAMERA_NUMBERS,
DOORLOCK_NUMBERS,
LIGHT_NUMBERS,
ProtectNumberEntityDescription,
)
from homeassistant.const import ATTR_ATTRIBUTION, ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .utils import (
MockUFPFixture,
adopt_devices,
assert_entity_counts,
ids_from_device_description,
init_entry,
remove_entities,
)
async def test_number_sensor_camera_remove(
hass: HomeAssistant, ufp: MockUFPFixture, camera: Camera, unadopted_camera: Camera
) -> None:
"""Test removing and re-adding a camera device."""
await init_entry(hass, ufp, [camera, unadopted_camera])
assert_entity_counts(hass, Platform.NUMBER, 4, 4)
await remove_entities(hass, ufp, [camera, unadopted_camera])
assert_entity_counts(hass, Platform.NUMBER, 0, 0)
await adopt_devices(hass, ufp, [camera, unadopted_camera])
assert_entity_counts(hass, Platform.NUMBER, 4, 4)
async def test_number_sensor_light_remove(
hass: HomeAssistant, ufp: MockUFPFixture, light: Light
) -> None:
"""Test removing and re-adding a light device."""
await init_entry(hass, ufp, [light])
assert_entity_counts(hass, Platform.NUMBER, 2, 2)
await remove_entities(hass, ufp, [light])
assert_entity_counts(hass, Platform.NUMBER, 0, 0)
await adopt_devices(hass, ufp, [light])
assert_entity_counts(hass, Platform.NUMBER, 2, 2)
async def test_number_lock_remove(
hass: HomeAssistant, ufp: MockUFPFixture, doorlock: Doorlock
) -> None:
"""Test removing and re-adding a light device."""
await init_entry(hass, ufp, [doorlock])
assert_entity_counts(hass, Platform.NUMBER, 1, 1)
await remove_entities(hass, ufp, [doorlock])
assert_entity_counts(hass, Platform.NUMBER, 0, 0)
await adopt_devices(hass, ufp, [doorlock])
assert_entity_counts(hass, Platform.NUMBER, 1, 1)
async def test_number_setup_light(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
light: Light,
) -> None:
"""Test number entity setup for light devices."""
await init_entry(hass, ufp, [light])
assert_entity_counts(hass, Platform.NUMBER, 2, 2)
for description in LIGHT_NUMBERS:
unique_id, entity_id = ids_from_device_description(
Platform.NUMBER, light, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == "45"
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_number_setup_camera_all(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
camera: Camera,
) -> None:
"""Test number entity setup for camera devices (all features)."""
camera.feature_flags.has_chime = True
camera.chime_duration = timedelta(seconds=1)
camera.feature_flags.has_led_ir = True
camera.isp_settings.icr_custom_value = 1
camera.isp_settings.ir_led_mode = IRLEDMode.CUSTOM
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.NUMBER, 5, 5)
for description in CAMERA_NUMBERS:
unique_id, entity_id = ids_from_device_description(
Platform.NUMBER, camera, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == "1"
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_number_setup_camera_none(
hass: HomeAssistant, ufp: MockUFPFixture, camera: Camera
) -> None:
"""Test number entity setup for camera devices (no features)."""
camera.feature_flags.can_optical_zoom = False
camera.feature_flags.has_mic = False
# has_wdr is an the inverse of has HDR
camera.feature_flags.has_hdr = True
camera.feature_flags.has_led_ir = False
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.NUMBER, 0, 0)
async def test_number_setup_camera_missing_attr(
hass: HomeAssistant, ufp: MockUFPFixture, camera: Camera
) -> None:
"""Test number entity setup for camera devices (no features, bad attrs)."""
camera.feature_flags = None
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.NUMBER, 0, 0)
async def test_number_light_sensitivity(
hass: HomeAssistant, ufp: MockUFPFixture, light: Light
) -> None:
"""Test sensitivity number entity for lights."""
await init_entry(hass, ufp, [light])
assert_entity_counts(hass, Platform.NUMBER, 2, 2)
description = LIGHT_NUMBERS[0]
assert description.ufp_set_method is not None
light.__pydantic_fields__["set_sensitivity"] = Mock(final=False, frozen=False)
light.set_sensitivity = AsyncMock()
_, entity_id = ids_from_device_description(Platform.NUMBER, light, description)
await hass.services.async_call(
"number", "set_value", {ATTR_ENTITY_ID: entity_id, "value": 15.0}, blocking=True
)
light.set_sensitivity.assert_called_once_with(15.0)
async def test_number_light_duration(
hass: HomeAssistant, ufp: MockUFPFixture, light: Light
) -> None:
"""Test auto-shutoff duration number entity for lights."""
await init_entry(hass, ufp, [light])
assert_entity_counts(hass, Platform.NUMBER, 2, 2)
description = LIGHT_NUMBERS[1]
light.__pydantic_fields__["set_duration"] = Mock(final=False, frozen=False)
light.set_duration = AsyncMock()
_, entity_id = ids_from_device_description(Platform.NUMBER, light, description)
await hass.services.async_call(
"number", "set_value", {ATTR_ENTITY_ID: entity_id, "value": 15.0}, blocking=True
)
light.set_duration.assert_called_once_with(timedelta(seconds=15.0))
@pytest.mark.parametrize("description", CAMERA_NUMBERS)
async def test_number_camera_simple(
hass: HomeAssistant,
ufp: MockUFPFixture,
camera: Camera,
description: ProtectNumberEntityDescription,
) -> None:
"""Tests all simple numbers for cameras."""
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.NUMBER, 4, 4)
assert description.ufp_set_method is not None
camera.__pydantic_fields__[description.ufp_set_method] = Mock(
final=False, frozen=False
)
setattr(camera, description.ufp_set_method, AsyncMock())
_, entity_id = ids_from_device_description(Platform.NUMBER, camera, description)
await hass.services.async_call(
"number", "set_value", {ATTR_ENTITY_ID: entity_id, "value": 1.0}, blocking=True
)
async def test_number_lock_auto_close(
hass: HomeAssistant, ufp: MockUFPFixture, doorlock: Doorlock
) -> None:
"""Test auto-lock timeout for locks."""
await init_entry(hass, ufp, [doorlock])
assert_entity_counts(hass, Platform.NUMBER, 1, 1)
description = DOORLOCK_NUMBERS[0]
doorlock.__pydantic_fields__["set_auto_close_time"] = Mock(
final=False, frozen=False
)
doorlock.set_auto_close_time = AsyncMock()
_, entity_id = ids_from_device_description(Platform.NUMBER, doorlock, description)
await hass.services.async_call(
"number", "set_value", {ATTR_ENTITY_ID: entity_id, "value": 15.0}, blocking=True
)
doorlock.set_auto_close_time.assert_called_once_with(timedelta(seconds=15.0))

View File

@@ -0,0 +1,82 @@
"""The tests for unifiprotect recorder."""
from __future__ import annotations
from datetime import datetime, timedelta
from unittest.mock import Mock
from uiprotect.data import Camera, Event, EventType, ModelType
from homeassistant.components.recorder import Recorder
from homeassistant.components.recorder.history import get_significant_states
from homeassistant.components.unifiprotect.binary_sensor import EVENT_SENSORS
from homeassistant.components.unifiprotect.const import (
ATTR_EVENT_ID,
ATTR_EVENT_SCORE,
DEFAULT_ATTRIBUTION,
)
from homeassistant.const import ATTR_ATTRIBUTION, ATTR_FRIENDLY_NAME, STATE_ON, Platform
from homeassistant.core import HomeAssistant
from .utils import MockUFPFixture, ids_from_device_description, init_entry
from tests.components.recorder.common import async_wait_recording_done
async def test_exclude_attributes(
recorder_mock: Recorder,
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
fixed_now: datetime,
) -> None:
"""Test binary_sensor has event_id and event_score excluded from recording."""
now = fixed_now
await init_entry(hass, ufp, [doorbell, unadopted_camera])
_, entity_id = ids_from_device_description(
Platform.BINARY_SENSOR, doorbell, EVENT_SENSORS[1]
)
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.MOTION,
start=fixed_now - timedelta(seconds=1),
end=None,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
camera_id=doorbell.id,
)
new_camera = doorbell.model_copy()
new_camera.is_motion_detected = True
new_camera.last_motion_event_id = event.id
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_camera
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_ON
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
assert state.attributes[ATTR_EVENT_SCORE] == 100
await async_wait_recording_done(hass)
states = await hass.async_add_executor_job(
get_significant_states, hass, now, None, hass.states.async_entity_ids()
)
assert len(states) >= 1
for entity_states in states.values():
for state in entity_states:
assert ATTR_EVENT_SCORE not in state.attributes
assert ATTR_EVENT_ID not in state.attributes
assert ATTR_FRIENDLY_NAME in state.attributes

View File

@@ -0,0 +1,392 @@
"""Test repairs for unifiprotect."""
from __future__ import annotations
from copy import copy, deepcopy
from unittest.mock import AsyncMock, Mock
from uiprotect.data import Camera, CloudAccount, ModelType, Version
from homeassistant.components.unifiprotect.const import DOMAIN
from homeassistant.config_entries import SOURCE_REAUTH
from homeassistant.core import HomeAssistant
from .utils import MockUFPFixture, init_entry
from tests.components.repairs import (
async_process_repairs_platforms,
process_repair_fix_flow,
start_repair_fix_flow,
)
from tests.typing import ClientSessionGenerator, WebSocketGenerator
async def test_ea_warning_ignore(
hass: HomeAssistant,
ufp: MockUFPFixture,
hass_client: ClientSessionGenerator,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test EA warning is created if using prerelease version of Protect."""
ufp.api.bootstrap.nvr.release_channel = "beta"
ufp.api.bootstrap.nvr.version = Version("1.21.0-beta.2")
version = ufp.api.bootstrap.nvr.version
assert version.is_prerelease
await init_entry(hass, ufp, [])
await async_process_repairs_platforms(hass)
ws_client = await hass_ws_client(hass)
client = await hass_client()
await ws_client.send_json({"id": 1, "type": "repairs/list_issues"})
msg = await ws_client.receive_json()
assert msg["success"]
assert len(msg["result"]["issues"]) > 0
issue = None
for i in msg["result"]["issues"]:
if i["issue_id"] == "ea_channel_warning":
issue = i
assert issue is not None
data = await start_repair_fix_flow(client, DOMAIN, "ea_channel_warning")
flow_id = data["flow_id"]
assert data["description_placeholders"] == {
"learn_more": "https://www.home-assistant.io/integrations/unifiprotect#software-support",
"version": str(version),
}
assert data["step_id"] == "start"
data = await process_repair_fix_flow(client, flow_id)
flow_id = data["flow_id"]
assert data["description_placeholders"] == {
"learn_more": "https://www.home-assistant.io/integrations/unifiprotect#software-support",
"version": str(version),
}
assert data["step_id"] == "confirm"
data = await process_repair_fix_flow(client, flow_id)
assert data["type"] == "create_entry"
async def test_ea_warning_fix(
hass: HomeAssistant,
ufp: MockUFPFixture,
hass_client: ClientSessionGenerator,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test EA warning is created if using prerelease version of Protect."""
ufp.api.bootstrap.nvr.release_channel = "beta"
ufp.api.bootstrap.nvr.version = Version("1.21.0-beta.2")
version = ufp.api.bootstrap.nvr.version
assert version.is_prerelease
await init_entry(hass, ufp, [])
await async_process_repairs_platforms(hass)
ws_client = await hass_ws_client(hass)
client = await hass_client()
await ws_client.send_json({"id": 1, "type": "repairs/list_issues"})
msg = await ws_client.receive_json()
assert msg["success"]
assert len(msg["result"]["issues"]) > 0
issue = None
for i in msg["result"]["issues"]:
if i["issue_id"] == "ea_channel_warning":
issue = i
assert issue is not None
data = await start_repair_fix_flow(client, DOMAIN, "ea_channel_warning")
flow_id = data["flow_id"]
assert data["description_placeholders"] == {
"learn_more": "https://www.home-assistant.io/integrations/unifiprotect#software-support",
"version": str(version),
}
assert data["step_id"] == "start"
new_nvr = copy(ufp.api.bootstrap.nvr)
new_nvr.release_channel = "release"
new_nvr.version = Version("2.2.6")
mock_msg = Mock()
mock_msg.changed_data = {"version": "2.2.6", "releaseChannel": "release"}
mock_msg.new_obj = new_nvr
ufp.api.bootstrap.nvr = new_nvr
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
data = await process_repair_fix_flow(client, flow_id)
assert data["type"] == "create_entry"
async def test_cloud_user_fix(
hass: HomeAssistant,
ufp: MockUFPFixture,
cloud_account: CloudAccount,
hass_client: ClientSessionGenerator,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test EA warning is created if using prerelease version of Protect."""
ufp.api.bootstrap.nvr.version = Version("2.2.6")
user = ufp.api.bootstrap.users[ufp.api.bootstrap.auth_user_id]
user.cloud_account = cloud_account
ufp.api.bootstrap.users[ufp.api.bootstrap.auth_user_id] = user
await init_entry(hass, ufp, [])
await async_process_repairs_platforms(hass)
ws_client = await hass_ws_client(hass)
client = await hass_client()
await ws_client.send_json({"id": 1, "type": "repairs/list_issues"})
msg = await ws_client.receive_json()
assert msg["success"]
assert len(msg["result"]["issues"]) > 0
issue = None
for i in msg["result"]["issues"]:
if i["issue_id"] == "cloud_user":
issue = i
assert issue is not None
data = await start_repair_fix_flow(client, DOMAIN, "cloud_user")
flow_id = data["flow_id"]
assert data["step_id"] == "confirm"
data = await process_repair_fix_flow(client, flow_id)
assert data["type"] == "create_entry"
await hass.async_block_till_done()
assert any(ufp.entry.async_get_active_flows(hass, {SOURCE_REAUTH}))
async def test_rtsp_read_only_ignore(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
hass_client: ClientSessionGenerator,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test RTSP disabled warning if camera is read-only and it is ignored."""
for channel in doorbell.channels:
channel.is_rtsp_enabled = False
for user in ufp.api.bootstrap.users.values():
user.all_permissions = []
ufp.api.get_camera = AsyncMock(return_value=doorbell)
await init_entry(hass, ufp, [doorbell])
await async_process_repairs_platforms(hass)
ws_client = await hass_ws_client(hass)
client = await hass_client()
issue_id = f"rtsp_disabled_{doorbell.id}"
await ws_client.send_json({"id": 1, "type": "repairs/list_issues"})
msg = await ws_client.receive_json()
assert msg["success"]
assert len(msg["result"]["issues"]) > 0
issue = None
for i in msg["result"]["issues"]:
if i["issue_id"] == issue_id:
issue = i
assert issue is not None
data = await start_repair_fix_flow(client, DOMAIN, issue_id)
flow_id = data["flow_id"]
assert data["step_id"] == "start"
data = await process_repair_fix_flow(client, flow_id)
flow_id = data["flow_id"]
assert data["step_id"] == "confirm"
data = await process_repair_fix_flow(client, flow_id)
assert data["type"] == "create_entry"
async def test_rtsp_read_only_fix(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
hass_client: ClientSessionGenerator,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test RTSP disabled warning if camera is read-only and it is fixed."""
for channel in doorbell.channels:
channel.is_rtsp_enabled = False
for user in ufp.api.bootstrap.users.values():
user.all_permissions = []
await init_entry(hass, ufp, [doorbell])
await async_process_repairs_platforms(hass)
ws_client = await hass_ws_client(hass)
client = await hass_client()
new_doorbell = deepcopy(doorbell)
new_doorbell.channels[1].is_rtsp_enabled = True
ufp.api.get_camera = AsyncMock(return_value=new_doorbell)
issue_id = f"rtsp_disabled_{doorbell.id}"
await ws_client.send_json({"id": 1, "type": "repairs/list_issues"})
msg = await ws_client.receive_json()
assert msg["success"]
assert len(msg["result"]["issues"]) > 0
issue = None
for i in msg["result"]["issues"]:
if i["issue_id"] == issue_id:
issue = i
assert issue is not None
data = await start_repair_fix_flow(client, DOMAIN, issue_id)
flow_id = data["flow_id"]
assert data["step_id"] == "start"
data = await process_repair_fix_flow(client, flow_id)
assert data["type"] == "create_entry"
async def test_rtsp_writable_fix(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
hass_client: ClientSessionGenerator,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test RTSP disabled warning if camera is writable and it is ignored."""
for channel in doorbell.channels:
channel.is_rtsp_enabled = False
await init_entry(hass, ufp, [doorbell])
await async_process_repairs_platforms(hass)
ws_client = await hass_ws_client(hass)
client = await hass_client()
new_doorbell = deepcopy(doorbell)
new_doorbell.channels[0].is_rtsp_enabled = True
ufp.api.get_camera = AsyncMock(side_effect=[doorbell, new_doorbell])
ufp.api.update_device = AsyncMock()
issue_id = f"rtsp_disabled_{doorbell.id}"
await ws_client.send_json({"id": 1, "type": "repairs/list_issues"})
msg = await ws_client.receive_json()
assert msg["success"]
assert len(msg["result"]["issues"]) > 0
issue = None
for i in msg["result"]["issues"]:
if i["issue_id"] == issue_id:
issue = i
assert issue is not None
data = await start_repair_fix_flow(client, DOMAIN, issue_id)
flow_id = data["flow_id"]
assert data["step_id"] == "start"
data = await process_repair_fix_flow(client, flow_id)
assert data["type"] == "create_entry"
channels = doorbell.unifi_dict()["channels"]
channels[0]["isRtspEnabled"] = True
ufp.api.update_device.assert_called_with(
ModelType.CAMERA, doorbell.id, {"channels": channels}
)
async def test_rtsp_writable_fix_when_not_setup(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
hass_client: ClientSessionGenerator,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test RTSP disabled warning if the integration is no longer set up."""
for channel in doorbell.channels:
channel.is_rtsp_enabled = False
await init_entry(hass, ufp, [doorbell])
await async_process_repairs_platforms(hass)
ws_client = await hass_ws_client(hass)
client = await hass_client()
new_doorbell = deepcopy(doorbell)
new_doorbell.channels[0].is_rtsp_enabled = True
ufp.api.get_camera = AsyncMock(side_effect=[doorbell, new_doorbell])
ufp.api.update_device = AsyncMock()
issue_id = f"rtsp_disabled_{doorbell.id}"
await ws_client.send_json({"id": 1, "type": "repairs/list_issues"})
msg = await ws_client.receive_json()
assert msg["success"]
assert len(msg["result"]["issues"]) > 0
issue = None
for i in msg["result"]["issues"]:
if i["issue_id"] == issue_id:
issue = i
assert issue is not None
# Unload the integration to ensure the fix flow still works
# if the integration is no longer set up
await hass.config_entries.async_unload(ufp.entry.entry_id)
await hass.async_block_till_done()
data = await start_repair_fix_flow(client, DOMAIN, issue_id)
flow_id = data["flow_id"]
assert data["step_id"] == "start"
data = await process_repair_fix_flow(client, flow_id)
assert data["type"] == "create_entry"
channels = doorbell.unifi_dict()["channels"]
channels[0]["isRtspEnabled"] = True
ufp.api.update_device.assert_called_with(
ModelType.CAMERA, doorbell.id, {"channels": channels}
)
async def test_rtsp_no_fix_if_third_party(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test no RTSP disabled warning if camera is third-party."""
for channel in doorbell.channels:
channel.is_rtsp_enabled = False
for user in ufp.api.bootstrap.users.values():
user.all_permissions = []
ufp.api.get_camera = AsyncMock(return_value=doorbell)
doorbell.is_third_party_camera = True
await init_entry(hass, ufp, [doorbell])
await async_process_repairs_platforms(hass)
ws_client = await hass_ws_client(hass)
await ws_client.send_json({"id": 1, "type": "repairs/list_issues"})
msg = await ws_client.receive_json()
assert msg["success"]
assert not msg["result"]["issues"]

View File

@@ -0,0 +1,556 @@
"""Test the UniFi Protect select platform."""
from __future__ import annotations
from copy import copy
from unittest.mock import AsyncMock, Mock
from uiprotect.data import (
Camera,
DoorbellMessageType,
IRLEDMode,
LCDMessage,
Light,
LightModeEnableType,
LightModeType,
Liveview,
RecordingMode,
Viewer,
)
from uiprotect.data.nvr import DoorbellMessage
from homeassistant.components.select import ATTR_OPTIONS
from homeassistant.components.unifiprotect.const import DEFAULT_ATTRIBUTION
from homeassistant.components.unifiprotect.select import (
CAMERA_SELECTS,
LIGHT_MODE_OFF,
LIGHT_SELECTS,
VIEWER_SELECTS,
)
from homeassistant.const import ATTR_ATTRIBUTION, ATTR_ENTITY_ID, ATTR_OPTION, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .utils import (
MockUFPFixture,
adopt_devices,
assert_entity_counts,
ids_from_device_description,
init_entry,
remove_entities,
)
async def test_select_camera_remove(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera, unadopted_camera: Camera
) -> None:
"""Test removing and re-adding a camera device."""
ufp.api.bootstrap.nvr.system_info.ustorage = None
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.SELECT, 5, 5)
await remove_entities(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.SELECT, 0, 0)
await adopt_devices(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.SELECT, 5, 5)
async def test_select_light_remove(
hass: HomeAssistant, ufp: MockUFPFixture, light: Light
) -> None:
"""Test removing and re-adding a light device."""
ufp.api.bootstrap.nvr.system_info.ustorage = None
await init_entry(hass, ufp, [light])
assert_entity_counts(hass, Platform.SELECT, 2, 2)
await remove_entities(hass, ufp, [light])
assert_entity_counts(hass, Platform.SELECT, 0, 0)
await adopt_devices(hass, ufp, [light])
assert_entity_counts(hass, Platform.SELECT, 2, 2)
async def test_select_viewer_remove(
hass: HomeAssistant, ufp: MockUFPFixture, viewer: Viewer
) -> None:
"""Test removing and re-adding a light device."""
ufp.api.bootstrap.nvr.system_info.ustorage = None
await init_entry(hass, ufp, [viewer])
assert_entity_counts(hass, Platform.SELECT, 1, 1)
await remove_entities(hass, ufp, [viewer])
assert_entity_counts(hass, Platform.SELECT, 0, 0)
await adopt_devices(hass, ufp, [viewer])
assert_entity_counts(hass, Platform.SELECT, 1, 1)
async def test_select_setup_light(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
light: Light,
) -> None:
"""Test select entity setup for light devices."""
light.light_mode_settings.enable_at = LightModeEnableType.DARK
await init_entry(hass, ufp, [light])
assert_entity_counts(hass, Platform.SELECT, 2, 2)
expected_values = ("On Motion - When Dark", "Not Paired")
for index, description in enumerate(LIGHT_SELECTS):
unique_id, entity_id = ids_from_device_description(
Platform.SELECT, light, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == expected_values[index]
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_select_setup_viewer(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
viewer: Viewer,
liveview: Liveview,
) -> None:
"""Test select entity setup for light devices."""
ufp.api.bootstrap.liveviews = {liveview.id: liveview}
await init_entry(hass, ufp, [viewer])
assert_entity_counts(hass, Platform.SELECT, 1, 1)
description = VIEWER_SELECTS[0]
unique_id, entity_id = ids_from_device_description(
Platform.SELECT, viewer, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == viewer.liveview.name
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_select_setup_camera_all(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
doorbell: Camera,
) -> None:
"""Test select entity setup for camera devices (all features)."""
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.SELECT, 5, 5)
expected_values = (
"Always",
"Auto",
"Default Message (Welcome)",
"None",
"Always Off",
)
for index, description in enumerate(CAMERA_SELECTS):
unique_id, entity_id = ids_from_device_description(
Platform.SELECT, doorbell, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == expected_values[index]
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_select_setup_camera_none(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
camera: Camera,
) -> None:
"""Test select entity setup for camera devices (no features)."""
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.SELECT, 2, 2)
expected_values = ("Always", "Auto", "Default Message (Welcome)")
for index, description in enumerate(CAMERA_SELECTS):
if index == 2:
return
unique_id, entity_id = ids_from_device_description(
Platform.SELECT, camera, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == expected_values[index]
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_select_update_liveview(
hass: HomeAssistant, ufp: MockUFPFixture, viewer: Viewer, liveview: Liveview
) -> None:
"""Test select entity update (new Liveview)."""
ufp.api.bootstrap.liveviews = {liveview.id: liveview}
await init_entry(hass, ufp, [viewer])
assert_entity_counts(hass, Platform.SELECT, 1, 1)
_, entity_id = ids_from_device_description(
Platform.SELECT, viewer, VIEWER_SELECTS[0]
)
state = hass.states.get(entity_id)
assert state
expected_options = state.attributes[ATTR_OPTIONS]
new_liveview = copy(liveview)
new_liveview.id = "test_id"
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_liveview
ufp.api.bootstrap.liveviews = {
**ufp.api.bootstrap.liveviews,
new_liveview.id: new_liveview,
}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.attributes[ATTR_OPTIONS] == expected_options
async def test_select_update_doorbell_settings(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera
) -> None:
"""Test select entity update (new Doorbell Message)."""
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.SELECT, 5, 5)
expected_length = len(ufp.api.bootstrap.nvr.doorbell_settings.all_messages) + 1
_, entity_id = ids_from_device_description(
Platform.SELECT, doorbell, CAMERA_SELECTS[2]
)
state = hass.states.get(entity_id)
assert state
assert len(state.attributes[ATTR_OPTIONS]) == expected_length
expected_length += 1
new_nvr = copy(ufp.api.bootstrap.nvr)
new_nvr.__pydantic_fields__["update_all_messages"] = Mock(final=False, frozen=False)
new_nvr.update_all_messages = Mock()
new_nvr.doorbell_settings.all_messages = [
*new_nvr.doorbell_settings.all_messages,
DoorbellMessage(
type=DoorbellMessageType.CUSTOM_MESSAGE,
text="Test2",
),
]
mock_msg = Mock()
mock_msg.changed_data = {"doorbell_settings": {}}
mock_msg.new_obj = new_nvr
ufp.api.bootstrap.nvr = new_nvr
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
new_nvr.update_all_messages.assert_called_once()
state = hass.states.get(entity_id)
assert state
assert len(state.attributes[ATTR_OPTIONS]) == expected_length
async def test_select_update_doorbell_message(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera
) -> None:
"""Test select entity update (change doorbell message)."""
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.SELECT, 5, 5)
_, entity_id = ids_from_device_description(
Platform.SELECT, doorbell, CAMERA_SELECTS[2]
)
state = hass.states.get(entity_id)
assert state
assert state.state == "Default Message (Welcome)"
new_camera = doorbell.model_copy()
new_camera.lcd_message = LCDMessage(
type=DoorbellMessageType.CUSTOM_MESSAGE, text="Test"
)
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_camera
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "Test"
async def test_select_set_option_light_motion(
hass: HomeAssistant, ufp: MockUFPFixture, light: Light
) -> None:
"""Test Light Mode select."""
await init_entry(hass, ufp, [light])
assert_entity_counts(hass, Platform.SELECT, 2, 2)
_, entity_id = ids_from_device_description(Platform.SELECT, light, LIGHT_SELECTS[0])
light.__pydantic_fields__["set_light_settings"] = Mock(final=False, frozen=False)
light.set_light_settings = AsyncMock()
await hass.services.async_call(
"select",
"select_option",
{ATTR_ENTITY_ID: entity_id, ATTR_OPTION: LIGHT_MODE_OFF},
blocking=True,
)
light.set_light_settings.assert_called_once_with(
LightModeType.MANUAL, enable_at=None
)
async def test_select_set_option_light_camera(
hass: HomeAssistant, ufp: MockUFPFixture, light: Light, camera: Camera
) -> None:
"""Test Paired Camera select."""
await init_entry(hass, ufp, [light, camera])
assert_entity_counts(hass, Platform.SELECT, 4, 4)
_, entity_id = ids_from_device_description(Platform.SELECT, light, LIGHT_SELECTS[1])
light.__pydantic_fields__["set_paired_camera"] = Mock(final=False, frozen=False)
light.set_paired_camera = AsyncMock()
camera = list(light.api.bootstrap.cameras.values())[0]
await hass.services.async_call(
"select",
"select_option",
{ATTR_ENTITY_ID: entity_id, ATTR_OPTION: camera.name},
blocking=True,
)
light.set_paired_camera.assert_called_once_with(camera)
await hass.services.async_call(
"select",
"select_option",
{ATTR_ENTITY_ID: entity_id, ATTR_OPTION: "Not Paired"},
blocking=True,
)
light.set_paired_camera.assert_called_with(None)
async def test_select_set_option_camera_recording(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera
) -> None:
"""Test Recording Mode select."""
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.SELECT, 5, 5)
_, entity_id = ids_from_device_description(
Platform.SELECT, doorbell, CAMERA_SELECTS[0]
)
doorbell.__pydantic_fields__["set_recording_mode"] = Mock(final=False, frozen=False)
doorbell.set_recording_mode = AsyncMock()
await hass.services.async_call(
"select",
"select_option",
{ATTR_ENTITY_ID: entity_id, ATTR_OPTION: "Never"},
blocking=True,
)
doorbell.set_recording_mode.assert_called_once_with(RecordingMode.NEVER)
async def test_select_set_option_camera_ir(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera
) -> None:
"""Test Infrared Mode select."""
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.SELECT, 5, 5)
_, entity_id = ids_from_device_description(
Platform.SELECT, doorbell, CAMERA_SELECTS[1]
)
doorbell.__pydantic_fields__["set_ir_led_model"] = Mock(final=False, frozen=False)
doorbell.set_ir_led_model = AsyncMock()
await hass.services.async_call(
"select",
"select_option",
{ATTR_ENTITY_ID: entity_id, ATTR_OPTION: "Always Enable"},
blocking=True,
)
doorbell.set_ir_led_model.assert_called_once_with(IRLEDMode.ON)
async def test_select_set_option_camera_doorbell_custom(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera
) -> None:
"""Test Doorbell Text select (user defined message)."""
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.SELECT, 5, 5)
_, entity_id = ids_from_device_description(
Platform.SELECT, doorbell, CAMERA_SELECTS[2]
)
doorbell.__pydantic_fields__["set_lcd_text"] = Mock(final=False, frozen=False)
doorbell.set_lcd_text = AsyncMock()
await hass.services.async_call(
"select",
"select_option",
{ATTR_ENTITY_ID: entity_id, ATTR_OPTION: "Test"},
blocking=True,
)
doorbell.set_lcd_text.assert_called_once_with(
DoorbellMessageType.CUSTOM_MESSAGE, text="Test"
)
async def test_select_set_option_camera_doorbell_unifi(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera
) -> None:
"""Test Doorbell Text select (unifi message)."""
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.SELECT, 5, 5)
_, entity_id = ids_from_device_description(
Platform.SELECT, doorbell, CAMERA_SELECTS[2]
)
doorbell.__pydantic_fields__["set_lcd_text"] = Mock(final=False, frozen=False)
doorbell.set_lcd_text = AsyncMock()
await hass.services.async_call(
"select",
"select_option",
{
ATTR_ENTITY_ID: entity_id,
ATTR_OPTION: "LEAVE PACKAGE AT DOOR",
},
blocking=True,
)
doorbell.set_lcd_text.assert_called_once_with(
DoorbellMessageType.LEAVE_PACKAGE_AT_DOOR
)
await hass.services.async_call(
"select",
"select_option",
{
ATTR_ENTITY_ID: entity_id,
ATTR_OPTION: "Default Message (Welcome)",
},
blocking=True,
)
doorbell.set_lcd_text.assert_called_with(None)
async def test_select_set_option_camera_doorbell_default(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera
) -> None:
"""Test Doorbell Text select (default message)."""
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.SELECT, 5, 5)
_, entity_id = ids_from_device_description(
Platform.SELECT, doorbell, CAMERA_SELECTS[2]
)
doorbell.__pydantic_fields__["set_lcd_text"] = Mock(final=False, frozen=False)
doorbell.set_lcd_text = AsyncMock()
await hass.services.async_call(
"select",
"select_option",
{
ATTR_ENTITY_ID: entity_id,
ATTR_OPTION: "Default Message (Welcome)",
},
blocking=True,
)
doorbell.set_lcd_text.assert_called_once_with(None)
async def test_select_set_option_viewer(
hass: HomeAssistant, ufp: MockUFPFixture, viewer: Viewer, liveview: Liveview
) -> None:
"""Test Liveview select."""
ufp.api.bootstrap.liveviews = {liveview.id: liveview}
await init_entry(hass, ufp, [viewer])
assert_entity_counts(hass, Platform.SELECT, 1, 1)
_, entity_id = ids_from_device_description(
Platform.SELECT, viewer, VIEWER_SELECTS[0]
)
viewer.__pydantic_fields__["set_liveview"] = Mock(final=False, frozen=False)
viewer.set_liveview = AsyncMock()
liveview = list(viewer.api.bootstrap.liveviews.values())[0]
await hass.services.async_call(
"select",
"select_option",
{ATTR_ENTITY_ID: entity_id, ATTR_OPTION: liveview.name},
blocking=True,
)
viewer.set_liveview.assert_called_once_with(liveview)

View File

@@ -0,0 +1,951 @@
"""Test the UniFi Protect sensor platform."""
from __future__ import annotations
from datetime import datetime, timedelta
from unittest.mock import Mock
import pytest
from uiprotect.data import (
NVR,
Camera,
Event,
EventType,
ModelType,
Sensor,
SmartDetectObjectType,
)
from uiprotect.data.nvr import EventMetadata, LicensePlateMetadata
from homeassistant.components.unifiprotect.const import (
ATTR_EVENT_SCORE,
DEFAULT_ATTRIBUTION,
)
from homeassistant.components.unifiprotect.sensor import (
ALL_DEVICES_SENSORS,
CAMERA_DISABLED_SENSORS,
CAMERA_SENSORS,
LICENSE_PLATE_EVENT_SENSORS,
MOTION_TRIP_SENSORS,
NVR_DISABLED_SENSORS,
NVR_SENSORS,
SENSE_SENSORS,
)
from homeassistant.const import (
ATTR_ATTRIBUTION,
EVENT_STATE_CHANGED,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
Platform,
)
from homeassistant.core import Event as HAEvent, EventStateChangedData, HomeAssistant
from homeassistant.helpers import entity_registry as er
from .utils import (
MockUFPFixture,
adopt_devices,
assert_entity_counts,
enable_entity,
ids_from_device_description,
init_entry,
remove_entities,
reset_objects,
time_changed,
)
from tests.common import async_capture_events
CAMERA_SENSORS_WRITE = CAMERA_SENSORS[:5]
SENSE_SENSORS_WRITE = SENSE_SENSORS[:8]
async def test_sensor_camera_remove(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera, unadopted_camera: Camera
) -> None:
"""Test removing and re-adding a camera device."""
ufp.api.bootstrap.nvr.system_info.ustorage = None
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.SENSOR, 24, 12)
await remove_entities(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.SENSOR, 12, 9)
await adopt_devices(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.SENSOR, 24, 12)
async def test_sensor_sensor_remove(
hass: HomeAssistant, ufp: MockUFPFixture, sensor_all: Sensor
) -> None:
"""Test removing and re-adding a light device."""
ufp.api.bootstrap.nvr.system_info.ustorage = None
await init_entry(hass, ufp, [sensor_all])
assert_entity_counts(hass, Platform.SENSOR, 22, 14)
await remove_entities(hass, ufp, [sensor_all])
assert_entity_counts(hass, Platform.SENSOR, 12, 9)
await adopt_devices(hass, ufp, [sensor_all])
assert_entity_counts(hass, Platform.SENSOR, 22, 14)
async def test_sensor_setup_sensor(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
sensor_all: Sensor,
) -> None:
"""Test sensor entity setup for sensor devices."""
await init_entry(hass, ufp, [sensor_all])
assert_entity_counts(hass, Platform.SENSOR, 22, 14)
expected_values = (
"10",
"10.0",
"10.0",
"10.0",
"none",
)
for index, description in enumerate(SENSE_SENSORS_WRITE):
if not description.entity_registry_enabled_default:
continue
unique_id, entity_id = ids_from_device_description(
Platform.SENSOR, sensor_all, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == expected_values[index]
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
# BLE signal
unique_id, entity_id = ids_from_device_description(
Platform.SENSOR, sensor_all, ALL_DEVICES_SENSORS[1]
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.disabled is True
assert entity.unique_id == unique_id
await enable_entity(hass, ufp.entry.entry_id, entity_id)
state = hass.states.get(entity_id)
assert state
assert state.state == "-50"
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_sensor_setup_sensor_none(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
sensor: Sensor,
) -> None:
"""Test sensor entity setup for sensor devices with no sensors enabled."""
await init_entry(hass, ufp, [sensor])
assert_entity_counts(hass, Platform.SENSOR, 22, 14)
expected_values = (
"10",
STATE_UNAVAILABLE,
STATE_UNAVAILABLE,
STATE_UNAVAILABLE,
STATE_UNAVAILABLE,
)
for index, description in enumerate(SENSE_SENSORS_WRITE):
if not description.entity_registry_enabled_default:
continue
unique_id, entity_id = ids_from_device_description(
Platform.SENSOR, sensor, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == expected_values[index]
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_sensor_setup_nvr(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
fixed_now: datetime,
) -> None:
"""Test sensor entity setup for NVR device."""
reset_objects(ufp.api.bootstrap)
nvr: NVR = ufp.api.bootstrap.nvr
nvr.up_since = fixed_now
nvr.system_info.cpu.average_load = 50.0
nvr.system_info.cpu.temperature = 50.0
nvr.storage_stats.utilization = 50.0
nvr.system_info.memory.available = 50.0
nvr.system_info.memory.total = 100.0
nvr.storage_stats.storage_distribution.timelapse_recordings.percentage = 50.0
nvr.storage_stats.storage_distribution.continuous_recordings.percentage = 50.0
nvr.storage_stats.storage_distribution.detections_recordings.percentage = 50.0
nvr.storage_stats.storage_distribution.hd_usage.percentage = 50.0
nvr.storage_stats.storage_distribution.uhd_usage.percentage = 50.0
nvr.storage_stats.storage_distribution.free.percentage = 50.0
nvr.storage_stats.capacity = 50.0
await hass.config_entries.async_setup(ufp.entry.entry_id)
await hass.async_block_till_done()
assert_entity_counts(hass, Platform.SENSOR, 12, 9)
expected_values = (
fixed_now.replace(second=0, microsecond=0).isoformat(),
"50.0",
"50.0",
"50.0",
"50.0",
"50.0",
"50.0",
"50.0",
"50",
)
for index, description in enumerate(NVR_SENSORS):
unique_id, entity_id = ids_from_device_description(
Platform.SENSOR, nvr, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.disabled is not description.entity_registry_enabled_default
assert entity.unique_id == unique_id
if not description.entity_registry_enabled_default:
await enable_entity(hass, ufp.entry.entry_id, entity_id)
state = hass.states.get(entity_id)
assert state
assert state.state == expected_values[index]
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
expected_values = ("50.0", "50.0", "50.0")
for index, description in enumerate(NVR_DISABLED_SENSORS):
unique_id, entity_id = ids_from_device_description(
Platform.SENSOR, nvr, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.disabled is not description.entity_registry_enabled_default
assert entity.unique_id == unique_id
await enable_entity(hass, ufp.entry.entry_id, entity_id)
state = hass.states.get(entity_id)
assert state
assert state.state == expected_values[index]
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_sensor_nvr_missing_values(
hass: HomeAssistant, entity_registry: er.EntityRegistry, ufp: MockUFPFixture
) -> None:
"""Test NVR sensor sensors if no data available."""
reset_objects(ufp.api.bootstrap)
nvr: NVR = ufp.api.bootstrap.nvr
nvr.system_info.memory.available = None
nvr.system_info.memory.total = None
nvr.up_since = None
nvr.storage_stats.capacity = None
await hass.config_entries.async_setup(ufp.entry.entry_id)
await hass.async_block_till_done()
assert_entity_counts(hass, Platform.SENSOR, 12, 9)
# Uptime
description = NVR_SENSORS[0]
unique_id, entity_id = ids_from_device_description(
Platform.SENSOR, nvr, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
await enable_entity(hass, ufp.entry.entry_id, entity_id)
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_UNKNOWN
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
# Memory
description = NVR_SENSORS[8]
unique_id, entity_id = ids_from_device_description(
Platform.SENSOR, nvr, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == "0"
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
# Memory
description = NVR_DISABLED_SENSORS[2]
unique_id, entity_id = ids_from_device_description(
Platform.SENSOR, nvr, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.disabled is True
assert entity.unique_id == unique_id
await enable_entity(hass, ufp.entry.entry_id, entity_id)
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_UNKNOWN
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_sensor_setup_camera(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
doorbell: Camera,
fixed_now: datetime,
) -> None:
"""Test sensor entity setup for camera devices."""
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.SENSOR, 24, 12)
expected_values = (
fixed_now.replace(microsecond=0).isoformat(),
"0.0001",
"0.0001",
"20.0",
)
for index, description in enumerate(CAMERA_SENSORS_WRITE):
if not description.entity_registry_enabled_default:
continue
unique_id, entity_id = ids_from_device_description(
Platform.SENSOR, doorbell, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.disabled is not description.entity_registry_enabled_default
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == expected_values[index]
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
expected_values = ("0.0001", "0.0001")
for index, description in enumerate(CAMERA_DISABLED_SENSORS):
unique_id, entity_id = ids_from_device_description(
Platform.SENSOR, doorbell, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.disabled is not description.entity_registry_enabled_default
assert entity.unique_id == unique_id
await enable_entity(hass, ufp.entry.entry_id, entity_id)
state = hass.states.get(entity_id)
assert state
assert state.state == expected_values[index]
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
# Wired signal
unique_id, entity_id = ids_from_device_description(
Platform.SENSOR, doorbell, ALL_DEVICES_SENSORS[2]
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.disabled is True
assert entity.unique_id == unique_id
await enable_entity(hass, ufp.entry.entry_id, entity_id)
state = hass.states.get(entity_id)
assert state
assert state.state == "1000"
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
# WiFi signal
unique_id, entity_id = ids_from_device_description(
Platform.SENSOR, doorbell, ALL_DEVICES_SENSORS[3]
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.disabled is True
assert entity.unique_id == unique_id
await enable_entity(hass, ufp.entry.entry_id, entity_id)
state = hass.states.get(entity_id)
assert state
assert state.state == "-50"
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensor_setup_camera_with_last_trip_time(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
doorbell: Camera,
fixed_now: datetime,
) -> None:
"""Test sensor entity setup for camera devices with last trip time."""
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.SENSOR, 24, 24)
# Last Trip Time
unique_id, entity_id = ids_from_device_description(
Platform.SENSOR, doorbell, MOTION_TRIP_SENSORS[0]
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert (
state.state
== (fixed_now - timedelta(hours=1)).replace(microsecond=0).isoformat()
)
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_sensor_update_alarm(
hass: HomeAssistant, ufp: MockUFPFixture, sensor_all: Sensor, fixed_now: datetime
) -> None:
"""Test sensor motion entity."""
await init_entry(hass, ufp, [sensor_all])
assert_entity_counts(hass, Platform.SENSOR, 22, 14)
_, entity_id = ids_from_device_description(
Platform.SENSOR, sensor_all, SENSE_SENSORS_WRITE[4]
)
event_metadata = EventMetadata(sensor_id=sensor_all.id, alarm_type="smoke")
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.SENSOR_ALARM,
start=fixed_now - timedelta(seconds=1),
end=None,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
metadata=event_metadata,
api=ufp.api,
)
new_sensor = sensor_all.model_copy()
new_sensor.set_alarm_timeout()
new_sensor.last_alarm_event_id = event.id
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = event
ufp.api.bootstrap.sensors = {new_sensor.id: new_sensor}
ufp.api.bootstrap.events = {event.id: event}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "smoke"
await time_changed(hass, 10)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensor_update_alarm_with_last_trip_time(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
sensor_all: Sensor,
fixed_now: datetime,
) -> None:
"""Test sensor motion entity with last trip time."""
await init_entry(hass, ufp, [sensor_all])
assert_entity_counts(hass, Platform.SENSOR, 22, 22)
# Last Trip Time
unique_id, entity_id = ids_from_device_description(
Platform.SENSOR, sensor_all, SENSE_SENSORS_WRITE[-3]
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert (
state.state
== (fixed_now - timedelta(hours=1)).replace(microsecond=0).isoformat()
)
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_camera_update_license_plate(
hass: HomeAssistant, ufp: MockUFPFixture, camera: Camera, fixed_now: datetime
) -> None:
"""Test license plate sensor."""
camera.feature_flags.smart_detect_types.append(SmartDetectObjectType.LICENSE_PLATE)
camera.feature_flags.has_smart_detect = True
camera.smart_detect_settings.object_types.append(
SmartDetectObjectType.LICENSE_PLATE
)
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.SENSOR, 23, 13)
_, entity_id = ids_from_device_description(
Platform.SENSOR, camera, LICENSE_PLATE_EVENT_SENSORS[0]
)
event_metadata = EventMetadata(
license_plate=LicensePlateMetadata(name="ABCD1234", confidence_level=95)
)
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.SMART_DETECT,
start=fixed_now - timedelta(seconds=1),
end=None,
score=100,
smart_detect_types=[SmartDetectObjectType.LICENSE_PLATE],
smart_detect_event_ids=[],
metadata=event_metadata,
api=ufp.api,
)
new_camera = camera.model_copy()
new_camera.is_smart_detected = True
new_camera.last_smart_detect_event_ids[SmartDetectObjectType.LICENSE_PLATE] = (
event.id
)
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_camera
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
state_changes: list[HAEvent[EventStateChangedData]] = async_capture_events(
hass, EVENT_STATE_CHANGED
)
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "ABCD1234"
assert len(state_changes) == 1
# ensure reply is ignored
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(state_changes) == 1
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.SMART_DETECT,
start=fixed_now - timedelta(seconds=1),
end=fixed_now + timedelta(seconds=1),
score=100,
smart_detect_types=[SmartDetectObjectType.LICENSE_PLATE],
smart_detect_event_ids=[],
metadata=event_metadata,
api=ufp.api,
)
ufp.api.bootstrap.events = {event.id: event}
new_camera.last_smart_detect_event_ids[SmartDetectObjectType.LICENSE_PLATE] = (
event.id
)
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(state_changes) == 2
state = hass.states.get(entity_id)
assert state
assert state.state == "none"
# Now send a new event with end already set
event = Event(
model=ModelType.EVENT,
id="new_event",
type=EventType.SMART_DETECT,
start=fixed_now - timedelta(seconds=1),
end=fixed_now + timedelta(seconds=1),
score=100,
smart_detect_types=[SmartDetectObjectType.LICENSE_PLATE],
smart_detect_event_ids=[],
metadata=event_metadata,
api=ufp.api,
)
ufp.api.bootstrap.events = {event.id: event}
new_camera.last_smart_detect_event_ids[SmartDetectObjectType.LICENSE_PLATE] = (
event.id
)
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(state_changes) == 4
assert state_changes[2].data["new_state"].state == "ABCD1234"
state = hass.states.get(entity_id)
assert state
assert state.state == "none"
async def test_camera_update_license_plate_changes_number_during_detect(
hass: HomeAssistant, ufp: MockUFPFixture, camera: Camera, fixed_now: datetime
) -> None:
"""Test license plate sensor that changes number during detect."""
camera.feature_flags.smart_detect_types.append(SmartDetectObjectType.LICENSE_PLATE)
camera.feature_flags.has_smart_detect = True
camera.smart_detect_settings.object_types.append(
SmartDetectObjectType.LICENSE_PLATE
)
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.SENSOR, 23, 13)
_, entity_id = ids_from_device_description(
Platform.SENSOR, camera, LICENSE_PLATE_EVENT_SENSORS[0]
)
event_metadata = EventMetadata(
license_plate=LicensePlateMetadata(name="ABCD1234", confidence_level=95)
)
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.SMART_DETECT,
start=fixed_now - timedelta(seconds=1),
end=None,
score=100,
smart_detect_types=[SmartDetectObjectType.LICENSE_PLATE],
smart_detect_event_ids=[],
metadata=event_metadata,
api=ufp.api,
)
new_camera = camera.model_copy()
new_camera.is_smart_detected = True
new_camera.last_smart_detect_event_ids[SmartDetectObjectType.LICENSE_PLATE] = (
event.id
)
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_camera
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
state_changes: list[HAEvent[EventStateChangedData]] = async_capture_events(
hass, EVENT_STATE_CHANGED
)
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "ABCD1234"
assert len(state_changes) == 1
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(state_changes) == 1
# Now mutate the original event so it ends
# Also change the metadata to a different license plate
# since the model may not get the plate correct on
# the first update.
event.score = 99
event.end = fixed_now + timedelta(seconds=1)
event_metadata.license_plate.name = "DCBA4321"
ufp.api.bootstrap.events = {event.id: event}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(state_changes) == 3
state = hass.states.get(entity_id)
assert state
assert state.state == "none"
assert state_changes[0].data["new_state"].state == "ABCD1234"
assert state_changes[1].data["new_state"].state == "DCBA4321"
assert state_changes[2].data["new_state"].state == "none"
state = hass.states.get(entity_id)
assert state
assert state.state == "none"
async def test_camera_update_license_plate_multiple_updates(
hass: HomeAssistant, ufp: MockUFPFixture, camera: Camera, fixed_now: datetime
) -> None:
"""Test license plate sensor that updates multiple times."""
camera.feature_flags.smart_detect_types.append(SmartDetectObjectType.LICENSE_PLATE)
camera.feature_flags.has_smart_detect = True
camera.smart_detect_settings.object_types.append(
SmartDetectObjectType.LICENSE_PLATE
)
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.SENSOR, 23, 13)
_, entity_id = ids_from_device_description(
Platform.SENSOR, camera, LICENSE_PLATE_EVENT_SENSORS[0]
)
event_metadata = EventMetadata(
license_plate=LicensePlateMetadata(name="ABCD1234", confidence_level=95)
)
event = Event(
model=ModelType.EVENT,
id="test_event_id",
type=EventType.SMART_DETECT,
start=fixed_now - timedelta(seconds=1),
end=None,
score=100,
smart_detect_types=[SmartDetectObjectType.LICENSE_PLATE],
smart_detect_event_ids=[],
metadata=event_metadata,
api=ufp.api,
)
new_camera = camera.model_copy()
new_camera.is_smart_detected = True
new_camera.last_smart_detect_event_ids[SmartDetectObjectType.LICENSE_PLATE] = (
event.id
)
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_camera
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
state_changes: list[HAEvent[EventStateChangedData]] = async_capture_events(
hass, EVENT_STATE_CHANGED
)
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "ABCD1234"
assert state.attributes[ATTR_EVENT_SCORE] == 100
assert len(state_changes) == 1
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(state_changes) == 1
# Now mutate the original event so the score changes
event.score = 99
event_metadata.license_plate.name = "DCBA4321"
ufp.api.bootstrap.events = {event.id: event}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(state_changes) == 2
state = hass.states.get(entity_id)
assert state
assert state.state == "DCBA4321"
assert state.attributes[ATTR_EVENT_SCORE] == 99
# Now mutate the original event so the score changes again
event.score = 40
ufp.api.bootstrap.events = {event.id: event}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(state_changes) == 3
state = hass.states.get(entity_id)
assert state
assert state.state == "DCBA4321"
assert state.attributes[ATTR_EVENT_SCORE] == 40
# Now send the event again
ufp.api.bootstrap.events = {event.id: event}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(state_changes) == 3
state = hass.states.get(entity_id)
assert state
assert state.state == "DCBA4321"
assert state.attributes[ATTR_EVENT_SCORE] == 40
# Now mutate the original event to add an end time
event.end = fixed_now + timedelta(seconds=1)
ufp.api.bootstrap.events = {event.id: event}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(state_changes) == 4
state = hass.states.get(entity_id)
assert state
assert state.state == "none"
# Now send the event again
event.end = fixed_now + timedelta(seconds=1)
ufp.api.bootstrap.events = {event.id: event}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(state_changes) == 4
state = hass.states.get(entity_id)
assert state
assert state.state == "none"
async def test_camera_update_license_no_dupes(
hass: HomeAssistant, ufp: MockUFPFixture, camera: Camera, fixed_now: datetime
) -> None:
"""Test license plate sensor does not generate duplicate reads."""
camera.feature_flags.smart_detect_types.append(SmartDetectObjectType.LICENSE_PLATE)
camera.feature_flags.has_smart_detect = True
camera.smart_detect_settings.object_types.append(
SmartDetectObjectType.LICENSE_PLATE
)
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.SENSOR, 23, 13)
_, entity_id = ids_from_device_description(
Platform.SENSOR, camera, LICENSE_PLATE_EVENT_SENSORS[0]
)
event_metadata = EventMetadata(
license_plate=LicensePlateMetadata(name="FPR2238", confidence_level=91)
)
event = Event(
model=ModelType.EVENT,
id="6675e36400de8c03e40bd5e3",
type=EventType.SMART_DETECT,
start=fixed_now - timedelta(seconds=1),
end=None,
score=83,
smart_detect_types=[SmartDetectObjectType.LICENSE_PLATE],
smart_detect_event_ids=[],
metadata=event_metadata,
api=ufp.api,
)
new_camera = camera.model_copy()
new_camera.is_smart_detected = True
new_camera.last_smart_detect_event_ids[SmartDetectObjectType.LICENSE_PLATE] = (
event.id
)
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_camera
ufp.api.bootstrap.cameras = {new_camera.id: new_camera}
ufp.api.bootstrap.events = {event.id: event}
state_changes: list[HAEvent[EventStateChangedData]] = async_capture_events(
hass, EVENT_STATE_CHANGED
)
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "FPR2238"
assert state.attributes[ATTR_EVENT_SCORE] == 83
assert len(state_changes) == 1
# Now send it again
ufp.api.bootstrap.events = {event.id: event}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(state_changes) == 1
# Again send it again
ufp.api.bootstrap.events = {event.id: event}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(state_changes) == 1
# Now add the end time and change the confidence level
event.end = fixed_now + timedelta(seconds=1)
event.metadata.license_plate.confidence_level = 96
ufp.api.bootstrap.events = {event.id: event}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(state_changes) == 2
state = hass.states.get(entity_id)
assert state
assert state.state == "none"
# Now send it 3 more times
for _ in range(3):
ufp.api.bootstrap.events = {event.id: event}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(state_changes) == 2
# Now clear the event
ufp.api.bootstrap.events = {}
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()
assert len(state_changes) == 2
async def test_sensor_precision(
hass: HomeAssistant, ufp: MockUFPFixture, sensor_all: Sensor, fixed_now: datetime
) -> None:
"""Test sensor precision value is respected."""
await init_entry(hass, ufp, [sensor_all])
assert_entity_counts(hass, Platform.SENSOR, 22, 14)
nvr: NVR = ufp.api.bootstrap.nvr
_, entity_id = ids_from_device_description(Platform.SENSOR, nvr, NVR_SENSORS[6])
assert hass.states.get(entity_id).state == "17.49"

View File

@@ -0,0 +1,344 @@
"""Test the UniFi Protect global services."""
from __future__ import annotations
from unittest.mock import AsyncMock, Mock
import pytest
from uiprotect.data import Camera, Chime, Color, Light, ModelType
from uiprotect.data.devices import CameraZone
from uiprotect.exceptions import BadRequest
from homeassistant.components.unifiprotect.const import (
ATTR_MESSAGE,
DOMAIN,
KEYRINGS_KEY_TYPE,
KEYRINGS_KEY_TYPE_ID_FINGERPRINT,
KEYRINGS_KEY_TYPE_ID_NFC,
KEYRINGS_ULP_ID,
KEYRINGS_USER_FULL_NAME,
KEYRINGS_USER_STATUS,
)
from homeassistant.components.unifiprotect.services import (
SERVICE_ADD_DOORBELL_TEXT,
SERVICE_GET_USER_KEYRING_INFO,
SERVICE_REMOVE_DOORBELL_TEXT,
SERVICE_REMOVE_PRIVACY_ZONE,
SERVICE_SET_CHIME_PAIRED,
)
from homeassistant.config_entries import ConfigEntryDisabler
from homeassistant.const import ATTR_DEVICE_ID, ATTR_ENTITY_ID, ATTR_NAME
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import device_registry as dr, entity_registry as er
from .utils import MockUFPFixture, init_entry
@pytest.fixture(name="device")
async def device_fixture(
hass: HomeAssistant, device_registry: dr.DeviceRegistry, ufp: MockUFPFixture
):
"""Fixture with entry setup to call services with."""
await init_entry(hass, ufp, [])
return list(device_registry.devices.values())[0]
@pytest.fixture(name="subdevice")
async def subdevice_fixture(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
ufp: MockUFPFixture,
light: Light,
):
"""Fixture with entry setup to call services with."""
await init_entry(hass, ufp, [light])
return [d for d in device_registry.devices.values() if d.name != "UnifiProtect"][0]
async def test_global_service_bad_device(
hass: HomeAssistant, ufp: MockUFPFixture
) -> None:
"""Test global service, invalid device ID."""
nvr = ufp.api.bootstrap.nvr
nvr.__pydantic_fields__["add_custom_doorbell_message"] = Mock(
final=False, frozen=False
)
nvr.add_custom_doorbell_message = AsyncMock()
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
DOMAIN,
SERVICE_ADD_DOORBELL_TEXT,
{ATTR_DEVICE_ID: "bad_device_id", ATTR_MESSAGE: "Test Message"},
blocking=True,
)
assert not nvr.add_custom_doorbell_message.called
async def test_global_service_exception(
hass: HomeAssistant, device: dr.DeviceEntry, ufp: MockUFPFixture
) -> None:
"""Test global service, unexpected error."""
nvr = ufp.api.bootstrap.nvr
nvr.__pydantic_fields__["add_custom_doorbell_message"] = Mock(
final=False, frozen=False
)
nvr.add_custom_doorbell_message = AsyncMock(side_effect=BadRequest)
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
DOMAIN,
SERVICE_ADD_DOORBELL_TEXT,
{ATTR_DEVICE_ID: device.id, ATTR_MESSAGE: "Test Message"},
blocking=True,
)
assert nvr.add_custom_doorbell_message.called
async def test_add_doorbell_text(
hass: HomeAssistant, device: dr.DeviceEntry, ufp: MockUFPFixture
) -> None:
"""Test add_doorbell_text service."""
nvr = ufp.api.bootstrap.nvr
nvr.__pydantic_fields__["add_custom_doorbell_message"] = Mock(
final=False, frozen=False
)
nvr.add_custom_doorbell_message = AsyncMock()
await hass.services.async_call(
DOMAIN,
SERVICE_ADD_DOORBELL_TEXT,
{ATTR_DEVICE_ID: device.id, ATTR_MESSAGE: "Test Message"},
blocking=True,
)
nvr.add_custom_doorbell_message.assert_called_once_with("Test Message")
async def test_remove_doorbell_text(
hass: HomeAssistant, subdevice: dr.DeviceEntry, ufp: MockUFPFixture
) -> None:
"""Test remove_doorbell_text service."""
nvr = ufp.api.bootstrap.nvr
nvr.__pydantic_fields__["remove_custom_doorbell_message"] = Mock(
final=False, frozen=False
)
nvr.remove_custom_doorbell_message = AsyncMock()
await hass.services.async_call(
DOMAIN,
SERVICE_REMOVE_DOORBELL_TEXT,
{ATTR_DEVICE_ID: subdevice.id, ATTR_MESSAGE: "Test Message"},
blocking=True,
)
nvr.remove_custom_doorbell_message.assert_called_once_with("Test Message")
async def test_add_doorbell_text_disabled_config_entry(
hass: HomeAssistant, device: dr.DeviceEntry, ufp: MockUFPFixture
) -> None:
"""Test add_doorbell_text service."""
nvr = ufp.api.bootstrap.nvr
nvr.__pydantic_fields__["add_custom_doorbell_message"] = Mock(
final=False, frozen=False
)
nvr.add_custom_doorbell_message = AsyncMock()
await hass.config_entries.async_set_disabled_by(
ufp.entry.entry_id, ConfigEntryDisabler.USER
)
await hass.async_block_till_done()
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
DOMAIN,
SERVICE_ADD_DOORBELL_TEXT,
{ATTR_DEVICE_ID: device.id, ATTR_MESSAGE: "Test Message"},
blocking=True,
)
assert not nvr.add_custom_doorbell_message.called
async def test_set_chime_paired_doorbells(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
chime: Chime,
doorbell: Camera,
) -> None:
"""Test set_chime_paired_doorbells."""
ufp.api.update_device = AsyncMock()
camera1 = doorbell.model_copy()
camera1.name = "Test Camera 1"
camera2 = doorbell.model_copy()
camera2.name = "Test Camera 2"
await init_entry(hass, ufp, [camera1, camera2, chime])
chime_entry = entity_registry.async_get("button.test_chime_play_chime")
camera_entry = entity_registry.async_get("binary_sensor.test_camera_2_doorbell")
assert chime_entry is not None
assert camera_entry is not None
await hass.services.async_call(
DOMAIN,
SERVICE_SET_CHIME_PAIRED,
{
ATTR_DEVICE_ID: chime_entry.device_id,
"doorbells": {
ATTR_ENTITY_ID: ["binary_sensor.test_camera_1_doorbell"],
ATTR_DEVICE_ID: [camera_entry.device_id],
},
},
blocking=True,
)
ufp.api.update_device.assert_called_once_with(
ModelType.CHIME, chime.id, {"cameraIds": sorted([camera1.id, camera2.id])}
)
async def test_remove_privacy_zone_no_zone(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
doorbell: Camera,
) -> None:
"""Test remove_privacy_zone service."""
ufp.api.update_device = AsyncMock()
doorbell.privacy_zones = []
await init_entry(hass, ufp, [doorbell])
camera_entry = entity_registry.async_get("binary_sensor.test_camera_doorbell")
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
DOMAIN,
SERVICE_REMOVE_PRIVACY_ZONE,
{ATTR_DEVICE_ID: camera_entry.device_id, ATTR_NAME: "Testing"},
blocking=True,
)
ufp.api.update_device.assert_not_called()
async def test_remove_privacy_zone(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
doorbell: Camera,
) -> None:
"""Test remove_privacy_zone service."""
ufp.api.update_device = AsyncMock()
doorbell.privacy_zones = [
CameraZone(id=0, name="Testing", color=Color("red"), points=[(0, 0), (1, 1)])
]
await init_entry(hass, ufp, [doorbell])
camera_entry = entity_registry.async_get("binary_sensor.test_camera_doorbell")
await hass.services.async_call(
DOMAIN,
SERVICE_REMOVE_PRIVACY_ZONE,
{ATTR_DEVICE_ID: camera_entry.device_id, ATTR_NAME: "Testing"},
blocking=True,
)
ufp.api.update_device.assert_called()
assert not doorbell.privacy_zones
@pytest.mark.asyncio
async def get_user_keyring_info(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
doorbell: Camera,
) -> None:
"""Test get_user_keyring_info service."""
ulp_user = Mock(full_name="Test User", status="active", ulp_id="user_ulp_id")
keyring = Mock(
registry_type="nfc",
registry_id="123456",
ulp_user="user_ulp_id",
)
keyring_2 = Mock(
registry_type="fingerprint",
registry_id="2",
ulp_user="user_ulp_id",
)
ufp.api.bootstrap.ulp_users.as_list = Mock(return_value=[ulp_user])
ufp.api.bootstrap.keyrings.as_list = Mock(return_value=[keyring, keyring_2])
await init_entry(hass, ufp, [doorbell])
camera_entry = entity_registry.async_get("binary_sensor.test_camera_doorbell")
response = await hass.services.async_call(
DOMAIN,
SERVICE_GET_USER_KEYRING_INFO,
{ATTR_DEVICE_ID: camera_entry.device_id},
blocking=True,
return_response=True,
)
assert response == {
"users": [
{
KEYRINGS_USER_FULL_NAME: "Test User",
"keys": [
{
KEYRINGS_KEY_TYPE: "nfc",
KEYRINGS_KEY_TYPE_ID_NFC: "123456",
},
{
KEYRINGS_KEY_TYPE_ID_FINGERPRINT: "2",
KEYRINGS_KEY_TYPE: "fingerprint",
},
],
KEYRINGS_USER_STATUS: "active",
KEYRINGS_ULP_ID: "user_ulp_id",
},
],
}
async def test_get_user_keyring_info_no_users(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
doorbell: Camera,
) -> None:
"""Test get_user_keyring_info service with no users."""
ufp.api.bootstrap.ulp_users.as_list = Mock(return_value=[])
ufp.api.bootstrap.keyrings.as_list = Mock(return_value=[])
await init_entry(hass, ufp, [doorbell])
camera_entry = entity_registry.async_get("binary_sensor.test_camera_doorbell")
with pytest.raises(
HomeAssistantError, match="No users found, please check Protect permissions."
):
await hass.services.async_call(
DOMAIN,
SERVICE_GET_USER_KEYRING_INFO,
{ATTR_DEVICE_ID: camera_entry.device_id},
blocking=True,
return_response=True,
)

View File

@@ -0,0 +1,459 @@
"""Test the UniFi Protect switch platform."""
from __future__ import annotations
from unittest.mock import AsyncMock, Mock
import pytest
from uiprotect.data import Camera, Light, Permission, RecordingMode, VideoMode
from homeassistant.components.unifiprotect.const import DEFAULT_ATTRIBUTION
from homeassistant.components.unifiprotect.switch import (
ATTR_PREV_MIC,
ATTR_PREV_RECORD,
CAMERA_SWITCHES,
LIGHT_SWITCHES,
PRIVACY_MODE_SWITCH,
ProtectSwitchEntityDescription,
)
from homeassistant.const import ATTR_ATTRIBUTION, ATTR_ENTITY_ID, STATE_OFF, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .utils import (
MockUFPFixture,
adopt_devices,
assert_entity_counts,
enable_entity,
ids_from_device_description,
init_entry,
remove_entities,
)
CAMERA_SWITCHES_BASIC = [
d
for d in CAMERA_SWITCHES
if (
not d.name.startswith("Detections:")
and d.name
not in {"SSH enabled", "Color night vision", "Tracking: person", "HDR mode"}
)
or d.name
in {
"Detections: motion",
"Detections: person",
"Detections: vehicle",
"Detections: animal",
}
]
CAMERA_SWITCHES_NO_EXTRA = [
d
for d in CAMERA_SWITCHES_BASIC
if d.name not in ("High FPS", "Privacy mode", "HDR mode")
]
async def test_switch_camera_remove(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera, unadopted_camera: Camera
) -> None:
"""Test removing and re-adding a camera device."""
ufp.api.bootstrap.nvr.system_info.ustorage = None
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.SWITCH, 17, 15)
await remove_entities(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.SWITCH, 2, 2)
await adopt_devices(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.SWITCH, 17, 15)
async def test_switch_light_remove(
hass: HomeAssistant, ufp: MockUFPFixture, light: Light
) -> None:
"""Test removing and re-adding a light device."""
ufp.api.bootstrap.nvr.system_info.ustorage = None
await init_entry(hass, ufp, [light])
assert_entity_counts(hass, Platform.SWITCH, 4, 3)
await remove_entities(hass, ufp, [light])
assert_entity_counts(hass, Platform.SWITCH, 2, 2)
await adopt_devices(hass, ufp, [light])
assert_entity_counts(hass, Platform.SWITCH, 4, 3)
async def test_switch_nvr(hass: HomeAssistant, ufp: MockUFPFixture) -> None:
"""Test switch entity setup for light devices."""
await init_entry(hass, ufp, [])
assert_entity_counts(hass, Platform.SWITCH, 2, 2)
nvr = ufp.api.bootstrap.nvr
nvr.__pydantic_fields__["set_insights"] = Mock(final=False, frozen=False)
nvr.set_insights = AsyncMock()
entity_id = "switch.unifiprotect_insights_enabled"
await hass.services.async_call(
"switch", "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True
)
nvr.set_insights.assert_called_once_with(True)
await hass.services.async_call(
"switch", "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True
)
nvr.set_insights.assert_called_with(False)
async def test_switch_setup_no_perm(
hass: HomeAssistant,
ufp: MockUFPFixture,
light: Light,
doorbell: Camera,
) -> None:
"""Test switch entity setup for light devices."""
ufp.api.bootstrap.auth_user.all_permissions = [
Permission.unifi_dict_to_dict({"rawPermission": "light:read:*"})
]
await init_entry(hass, ufp, [light, doorbell])
assert_entity_counts(hass, Platform.SWITCH, 0, 0)
async def test_switch_setup_light(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
light: Light,
) -> None:
"""Test switch entity setup for light devices."""
await init_entry(hass, ufp, [light])
assert_entity_counts(hass, Platform.SWITCH, 4, 3)
description = LIGHT_SWITCHES[1]
unique_id, entity_id = ids_from_device_description(
Platform.SWITCH, light, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
description = LIGHT_SWITCHES[0]
unique_id = f"{light.mac}_{description.key}"
entity_id = f"switch.test_light_{description.name.lower().replace(' ', '_')}"
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.disabled is True
assert entity.unique_id == unique_id
await enable_entity(hass, ufp.entry.entry_id, entity_id)
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_switch_setup_camera_all(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
doorbell: Camera,
) -> None:
"""Test switch entity setup for camera devices (all enabled feature flags)."""
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.SWITCH, 17, 15)
for description in CAMERA_SWITCHES_BASIC:
unique_id, entity_id = ids_from_device_description(
Platform.SWITCH, doorbell, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
description = CAMERA_SWITCHES[0]
description_entity_name = (
description.name.lower().replace(":", "").replace(" ", "_")
)
unique_id = f"{doorbell.mac}_{description.key}"
entity_id = f"switch.test_camera_{description_entity_name}"
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.disabled is True
assert entity.unique_id == unique_id
await enable_entity(hass, ufp.entry.entry_id, entity_id)
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_switch_setup_camera_none(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
camera: Camera,
) -> None:
"""Test switch entity setup for camera devices (no enabled feature flags)."""
await init_entry(hass, ufp, [camera])
assert_entity_counts(hass, Platform.SWITCH, 8, 7)
for description in CAMERA_SWITCHES_BASIC:
if description.ufp_required_field is not None:
continue
unique_id, entity_id = ids_from_device_description(
Platform.SWITCH, camera, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
description = CAMERA_SWITCHES[0]
description_entity_name = (
description.name.lower().replace(":", "").replace(" ", "_")
)
unique_id = f"{camera.mac}_{description.key}"
entity_id = f"switch.test_camera_{description_entity_name}"
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.disabled is True
assert entity.unique_id == unique_id
await enable_entity(hass, ufp.entry.entry_id, entity_id)
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_switch_light_status(
hass: HomeAssistant, ufp: MockUFPFixture, light: Light
) -> None:
"""Tests status light switch for lights."""
await init_entry(hass, ufp, [light])
assert_entity_counts(hass, Platform.SWITCH, 4, 3)
description = LIGHT_SWITCHES[1]
light.__pydantic_fields__["set_status_light"] = Mock(final=False, frozen=False)
light.set_status_light = AsyncMock()
_, entity_id = ids_from_device_description(Platform.SWITCH, light, description)
await hass.services.async_call(
"switch", "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True
)
light.set_status_light.assert_called_once_with(True)
await hass.services.async_call(
"switch", "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True
)
light.set_status_light.assert_called_with(False)
async def test_switch_camera_ssh(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera
) -> None:
"""Tests SSH switch for cameras."""
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.SWITCH, 17, 15)
description = CAMERA_SWITCHES[0]
doorbell.__pydantic_fields__["set_ssh"] = Mock(final=False, frozen=False)
doorbell.set_ssh = AsyncMock()
_, entity_id = ids_from_device_description(Platform.SWITCH, doorbell, description)
await enable_entity(hass, ufp.entry.entry_id, entity_id)
await hass.services.async_call(
"switch", "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True
)
doorbell.set_ssh.assert_called_once_with(True)
await hass.services.async_call(
"switch", "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True
)
doorbell.set_ssh.assert_called_with(False)
@pytest.mark.parametrize("description", CAMERA_SWITCHES_NO_EXTRA)
async def test_switch_camera_simple(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
description: ProtectSwitchEntityDescription,
) -> None:
"""Tests all simple switches for cameras."""
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.SWITCH, 17, 15)
assert description.ufp_set_method is not None
doorbell.__pydantic_fields__[description.ufp_set_method] = Mock(
final=False, frozen=False
)
setattr(doorbell, description.ufp_set_method, AsyncMock())
set_method = getattr(doorbell, description.ufp_set_method)
_, entity_id = ids_from_device_description(Platform.SWITCH, doorbell, description)
await hass.services.async_call(
"switch", "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True
)
set_method.assert_called_once_with(True)
await hass.services.async_call(
"switch", "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True
)
set_method.assert_called_with(False)
async def test_switch_camera_highfps(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera
) -> None:
"""Tests High FPS switch for cameras."""
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.SWITCH, 17, 15)
description = CAMERA_SWITCHES[3]
doorbell.__pydantic_fields__["set_video_mode"] = Mock(final=False, frozen=False)
doorbell.set_video_mode = AsyncMock()
_, entity_id = ids_from_device_description(Platform.SWITCH, doorbell, description)
await hass.services.async_call(
"switch", "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True
)
doorbell.set_video_mode.assert_called_once_with(VideoMode.HIGH_FPS)
await hass.services.async_call(
"switch", "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True
)
doorbell.set_video_mode.assert_called_with(VideoMode.DEFAULT)
async def test_switch_camera_privacy(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera
) -> None:
"""Tests Privacy Mode switch for cameras with privacy mode defaulted on."""
previous_mic = doorbell.mic_volume = 53
previous_record = doorbell.recording_settings.mode = RecordingMode.DETECTIONS
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.SWITCH, 17, 15)
description = PRIVACY_MODE_SWITCH
doorbell.__pydantic_fields__["set_privacy"] = Mock(final=False, frozen=False)
doorbell.set_privacy = AsyncMock()
_, entity_id = ids_from_device_description(Platform.SWITCH, doorbell, description)
state = hass.states.get(entity_id)
assert state and state.state == "off"
assert ATTR_PREV_MIC not in state.attributes
assert ATTR_PREV_RECORD not in state.attributes
await hass.services.async_call(
"switch", "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True
)
doorbell.set_privacy.assert_called_with(True, 0, RecordingMode.NEVER)
new_doorbell = doorbell.model_copy()
new_doorbell.add_privacy_zone()
new_doorbell.mic_volume = 0
new_doorbell.recording_settings.mode = RecordingMode.NEVER
ufp.api.bootstrap.cameras = {new_doorbell.id: new_doorbell}
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = new_doorbell
ufp.ws_msg(mock_msg)
state = hass.states.get(entity_id)
assert state and state.state == "on"
assert state.attributes[ATTR_PREV_MIC] == previous_mic
assert state.attributes[ATTR_PREV_RECORD] == previous_record.value
doorbell.set_privacy.reset_mock()
await hass.services.async_call(
"switch", "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True
)
doorbell.set_privacy.assert_called_with(False, previous_mic, previous_record)
async def test_switch_camera_privacy_already_on(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera
) -> None:
"""Tests Privacy Mode switch for cameras with privacy mode defaulted on."""
doorbell.add_privacy_zone()
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.SWITCH, 17, 15)
description = PRIVACY_MODE_SWITCH
doorbell.__pydantic_fields__["set_privacy"] = Mock(final=False, frozen=False)
doorbell.set_privacy = AsyncMock()
_, entity_id = ids_from_device_description(Platform.SWITCH, doorbell, description)
await hass.services.async_call(
"switch", "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True
)
doorbell.set_privacy.assert_called_once_with(False, 100, RecordingMode.ALWAYS)

View File

@@ -0,0 +1,93 @@
"""Test the UniFi Protect text platform."""
from __future__ import annotations
from unittest.mock import AsyncMock, Mock
from uiprotect.data import Camera, DoorbellMessageType, LCDMessage
from homeassistant.components.unifiprotect.const import DEFAULT_ATTRIBUTION
from homeassistant.components.unifiprotect.text import CAMERA
from homeassistant.const import ATTR_ATTRIBUTION, ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .utils import (
MockUFPFixture,
adopt_devices,
assert_entity_counts,
ids_from_device_description,
init_entry,
remove_entities,
)
async def test_text_camera_remove(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera, unadopted_camera: Camera
) -> None:
"""Test removing and re-adding a camera device."""
ufp.api.bootstrap.nvr.system_info.ustorage = None
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.TEXT, 1, 1)
await remove_entities(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.TEXT, 0, 0)
await adopt_devices(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.TEXT, 1, 1)
async def test_text_camera_setup(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
ufp: MockUFPFixture,
doorbell: Camera,
) -> None:
"""Test text entity setup for camera devices."""
doorbell.lcd_message = LCDMessage(
type=DoorbellMessageType.CUSTOM_MESSAGE, text="Test"
)
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.TEXT, 1, 1)
description = CAMERA[0]
unique_id, entity_id = ids_from_device_description(
Platform.TEXT, doorbell, description
)
entity = entity_registry.async_get(entity_id)
assert entity
assert entity.unique_id == unique_id
state = hass.states.get(entity_id)
assert state
assert state.state == "Test"
assert state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION
async def test_text_camera_set(
hass: HomeAssistant, ufp: MockUFPFixture, doorbell: Camera
) -> None:
"""Test text entity setting value camera devices."""
await init_entry(hass, ufp, [doorbell])
assert_entity_counts(hass, Platform.TEXT, 1, 1)
description = CAMERA[0]
unique_id, entity_id = ids_from_device_description(
Platform.TEXT, doorbell, description
)
doorbell.__pydantic_fields__["set_lcd_text"] = Mock(final=False, frozen=False)
doorbell.set_lcd_text = AsyncMock()
await hass.services.async_call(
"text",
"set_value",
{ATTR_ENTITY_ID: entity_id, "value": "Test test"},
blocking=True,
)
doorbell.set_lcd_text.assert_called_once_with(
DoorbellMessageType.CUSTOM_MESSAGE, text="Test test"
)

View File

@@ -0,0 +1,739 @@
"""Test UniFi Protect views."""
from datetime import datetime, timedelta
from typing import Any, cast
from unittest.mock import AsyncMock, Mock
from aiohttp import ClientResponse
import pytest
from uiprotect.data import Camera, Event, EventType, ModelType
from uiprotect.exceptions import ClientError
from homeassistant.components.unifiprotect.views import (
async_generate_event_video_url,
async_generate_proxy_event_video_url,
async_generate_thumbnail_url,
)
from homeassistant.core import HomeAssistant
from .utils import MockUFPFixture, init_entry
from tests.typing import ClientSessionGenerator
async def test_thumbnail_bad_nvr_id(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
) -> None:
"""Test invalid NVR ID in URL."""
ufp.api.get_event_thumbnail = AsyncMock()
await init_entry(hass, ufp, [camera])
url = async_generate_thumbnail_url("test_id", "bad_id")
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 404
ufp.api.get_event_thumbnail.assert_not_called()
@pytest.mark.parametrize(("width", "height"), [("test", None), (None, "test")])
async def test_thumbnail_bad_params(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
width: Any,
height: Any,
) -> None:
"""Test invalid bad query parameters."""
ufp.api.get_event_thumbnail = AsyncMock()
await init_entry(hass, ufp, [camera])
url = async_generate_thumbnail_url(
"test_id", ufp.api.bootstrap.nvr.id, width=width, height=height
)
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 400
ufp.api.get_event_thumbnail.assert_not_called()
async def test_thumbnail_bad_event(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
) -> None:
"""Test invalid with error raised."""
ufp.api.get_event_thumbnail = AsyncMock(side_effect=ClientError())
await init_entry(hass, ufp, [camera])
url = async_generate_thumbnail_url("test_id", ufp.api.bootstrap.nvr.id)
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 404
ufp.api.get_event_thumbnail.assert_called_with("test_id", width=None, height=None)
async def test_thumbnail_no_data(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
) -> None:
"""Test invalid no thumbnail returned."""
ufp.api.get_event_thumbnail = AsyncMock(return_value=None)
await init_entry(hass, ufp, [camera])
url = async_generate_thumbnail_url("test_id", ufp.api.bootstrap.nvr.id)
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 404
ufp.api.get_event_thumbnail.assert_called_with("test_id", width=None, height=None)
async def test_thumbnail(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
) -> None:
"""Test NVR ID in URL."""
ufp.api.get_event_thumbnail = AsyncMock(return_value=b"testtest")
await init_entry(hass, ufp, [camera])
url = async_generate_thumbnail_url("test_id", ufp.api.bootstrap.nvr.id)
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 200
assert response.content_type == "image/jpeg"
assert await response.content.read() == b"testtest"
ufp.api.get_event_thumbnail.assert_called_with("test_id", width=None, height=None)
async def test_thumbnail_entry_id(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
) -> None:
"""Test config entry ID in URL."""
ufp.api.get_event_thumbnail = AsyncMock(return_value=b"testtest")
await init_entry(hass, ufp, [camera])
url = async_generate_thumbnail_url("test_id", ufp.entry.entry_id)
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 200
assert response.content_type == "image/jpeg"
assert await response.content.read() == b"testtest"
ufp.api.get_event_thumbnail.assert_called_with("test_id", width=None, height=None)
async def test_thumbnail_invalid_entry_entry_id(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
) -> None:
"""Test invalid config entry ID in URL."""
ufp.api.get_event_thumbnail = AsyncMock(return_value=b"testtest")
await init_entry(hass, ufp, [camera])
url = async_generate_thumbnail_url("test_id", "invalid")
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 404
async def test_video_bad_event(
hass: HomeAssistant,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test generating event with bad camera ID."""
await init_entry(hass, ufp, [camera])
event = Event(
model=ModelType.EVENT,
api=ufp.api,
camera_id="test_id",
start=fixed_now - timedelta(seconds=30),
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
with pytest.raises(ValueError):
async_generate_event_video_url(event)
async def test_video_bad_event_ongoing(
hass: HomeAssistant,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test generating event with bad camera ID."""
await init_entry(hass, ufp, [camera])
event = Event(
model=ModelType.EVENT,
api=ufp.api,
camera_id=camera.id,
start=fixed_now - timedelta(seconds=30),
end=None,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
with pytest.raises(ValueError):
async_generate_event_video_url(event)
async def test_video_bad_perms(
hass: HomeAssistant,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test generating event with bad user permissions."""
ufp.api.bootstrap.auth_user.all_permissions = []
await init_entry(hass, ufp, [camera])
event = Event(
model=ModelType.EVENT,
api=ufp.api,
camera_id=camera.id,
start=fixed_now - timedelta(seconds=30),
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
with pytest.raises(PermissionError):
async_generate_event_video_url(event)
async def test_video_bad_nvr_id(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test video URL with bad NVR id."""
ufp.api.request = AsyncMock()
await init_entry(hass, ufp, [camera])
event = Event(
model=ModelType.EVENT,
api=ufp.api,
camera_id=camera.id,
start=fixed_now - timedelta(seconds=30),
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
url = async_generate_event_video_url(event)
url = url.replace(ufp.api.bootstrap.nvr.id, "bad_id")
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 404
ufp.api.request.assert_not_called()
async def test_video_bad_camera_id(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test video URL with bad camera id."""
ufp.api.request = AsyncMock()
await init_entry(hass, ufp, [camera])
event = Event(
model=ModelType.EVENT,
api=ufp.api,
camera_id=camera.id,
start=fixed_now - timedelta(seconds=30),
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
url = async_generate_event_video_url(event)
url = url.replace(camera.id, "bad_id")
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 404
ufp.api.request.assert_not_called()
async def test_video_bad_camera_perms(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test video URL with bad camera perms."""
ufp.api.request = AsyncMock()
await init_entry(hass, ufp, [camera])
event = Event(
model=ModelType.EVENT,
api=ufp.api,
camera_id=camera.id,
start=fixed_now - timedelta(seconds=30),
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
url = async_generate_event_video_url(event)
ufp.api.bootstrap.auth_user.all_permissions = []
ufp.api.bootstrap.auth_user._perm_cache = {}
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 403
ufp.api.request.assert_not_called()
@pytest.mark.parametrize(("start", "end"), [("test", None), (None, "test")])
async def test_video_bad_params(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
start: Any,
end: Any,
) -> None:
"""Test video URL with bad start/end params."""
ufp.api.request = AsyncMock()
await init_entry(hass, ufp, [camera])
event_start = fixed_now - timedelta(seconds=30)
event = Event(
model=ModelType.EVENT,
api=ufp.api,
camera_id=camera.id,
start=event_start,
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
url = async_generate_event_video_url(event)
from_value = event_start if start is not None else fixed_now
to_value = start if start is not None else end
url = url.replace(from_value.replace(microsecond=0).isoformat(), to_value)
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 400
ufp.api.request.assert_not_called()
async def test_video_bad_video(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test video URL with no video."""
ufp.api.request = AsyncMock(side_effect=ClientError)
await init_entry(hass, ufp, [camera])
event_start = fixed_now - timedelta(seconds=30)
event = Event(
model=ModelType.EVENT,
api=ufp.api,
camera_id=camera.id,
start=event_start,
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
url = async_generate_event_video_url(event)
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 404
ufp.api.request.assert_called_once()
async def test_video(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test video URL with no video."""
content = Mock()
content.__anext__ = AsyncMock(side_effect=[b"test", b"test", StopAsyncIteration()])
content.__aiter__ = Mock(return_value=content)
mock_response = Mock()
mock_response.content_length = 8
mock_response.content.iter_chunked = Mock(return_value=content)
ufp.api.request = AsyncMock(return_value=mock_response)
await init_entry(hass, ufp, [camera])
event_start = fixed_now - timedelta(seconds=30)
event = Event(
model=ModelType.EVENT,
api=ufp.api,
camera_id=camera.id,
start=event_start,
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
url = async_generate_event_video_url(event)
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert await response.content.read() == b"testtest"
assert response.status == 200
ufp.api.request.assert_called_once()
async def test_video_entity_id(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test video URL with no video."""
content = Mock()
content.__anext__ = AsyncMock(side_effect=[b"test", b"test", StopAsyncIteration()])
content.__aiter__ = Mock(return_value=content)
mock_response = Mock()
mock_response.content_length = 8
mock_response.content.iter_chunked = Mock(return_value=content)
ufp.api.request = AsyncMock(return_value=mock_response)
await init_entry(hass, ufp, [camera])
event_start = fixed_now - timedelta(seconds=30)
event = Event(
model=ModelType.EVENT,
api=ufp.api,
camera_id=camera.id,
start=event_start,
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
url = async_generate_event_video_url(event)
url = url.replace(camera.id, "camera.test_camera_high_resolution_channel")
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert await response.content.read() == b"testtest"
assert response.status == 200
ufp.api.request.assert_called_once()
async def test_video_event_bad_nvr_id(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
camera: Camera,
ufp: MockUFPFixture,
) -> None:
"""Test video proxy URL with bad NVR id."""
ufp.api.request = AsyncMock()
await init_entry(hass, ufp, [camera])
url = async_generate_proxy_event_video_url("bad_id", "test_id")
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 404
ufp.api.request.assert_not_called()
async def test_video_event_bad_event(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
) -> None:
"""Test generating event with bad event ID."""
ufp.api.get_event = AsyncMock(side_effect=ClientError())
await init_entry(hass, ufp, [camera])
url = async_generate_proxy_event_video_url(ufp.api.bootstrap.nvr.id, "bad_event_id")
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 404
ufp.api.request.assert_not_called()
async def test_video_event_bad_camera(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
) -> None:
"""Test generating event with bad camera ID."""
ufp.api.get_event = AsyncMock(side_effect=ClientError())
await init_entry(hass, ufp, [camera])
url = async_generate_proxy_event_video_url(ufp.api.bootstrap.nvr.id, "bad_event_id")
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 404
ufp.api.request.assert_not_called()
async def test_video_event_bad_camera_perms(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test video URL with bad camera perms."""
ufp.api.request = AsyncMock()
await init_entry(hass, ufp, [camera])
event_start = fixed_now - timedelta(seconds=30)
event = Event(
model=ModelType.EVENT,
api=ufp.api,
start=event_start,
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
camera_id="bad_id",
camera=camera,
)
ufp.api.get_event = AsyncMock(return_value=event)
url = async_generate_proxy_event_video_url(ufp.api.bootstrap.nvr.id, "test_id")
ufp.api.bootstrap.auth_user.all_permissions = []
ufp.api.bootstrap.auth_user._perm_cache = {}
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 404
ufp.api.request.assert_not_called()
async def test_video_event_ongoing(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test video URL with ongoing event."""
ufp.api.request = AsyncMock()
await init_entry(hass, ufp, [camera])
event_start = fixed_now - timedelta(seconds=30)
event = Event(
model=ModelType.EVENT,
api=ufp.api,
start=event_start,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
camera_id=camera.id,
camera=camera,
)
ufp.api.get_event = AsyncMock(return_value=event)
url = async_generate_proxy_event_video_url(ufp.api.bootstrap.nvr.id, "test_id")
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 400
ufp.api.request.assert_not_called()
async def test_event_video_no_data(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test invalid no event video returned."""
await init_entry(hass, ufp, [camera])
event_start = fixed_now - timedelta(seconds=30)
event = Event(
model=ModelType.EVENT,
api=ufp.api,
start=event_start,
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
camera_id=camera.id,
camera=camera,
)
ufp.api.request = AsyncMock(side_effect=ClientError)
ufp.api.get_event = AsyncMock(return_value=event)
url = async_generate_proxy_event_video_url(ufp.api.bootstrap.nvr.id, "test_id")
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 404
async def test_event_video(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test event video URL with no video."""
content = Mock()
content.__anext__ = AsyncMock(side_effect=[b"test", b"test", StopAsyncIteration()])
content.__aiter__ = Mock(return_value=content)
mock_response = Mock()
mock_response.content_length = 8
mock_response.content.iter_chunked = Mock(return_value=content)
ufp.api.request = AsyncMock(return_value=mock_response)
await init_entry(hass, ufp, [camera])
event_start = fixed_now - timedelta(seconds=30)
event = Event(
model=ModelType.EVENT,
api=ufp.api,
start=event_start,
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
camera_id=camera.id,
camera=camera,
)
ufp.api.get_event = AsyncMock(return_value=event)
url = async_generate_proxy_event_video_url(ufp.api.bootstrap.nvr.id, "test_id")
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert await response.content.read() == b"testtest"
assert response.status == 200
ufp.api.request.assert_called_once()

View File

@@ -0,0 +1,245 @@
"""Test helpers for UniFi Protect."""
from __future__ import annotations
from collections.abc import Callable, Sequence
from dataclasses import dataclass
from datetime import timedelta
from unittest.mock import Mock
from uiprotect import ProtectApiClient
from uiprotect.data import (
Bootstrap,
Camera,
Event,
EventType,
ModelType,
ProtectAdoptableDeviceModel,
WSSubscriptionMessage,
)
from uiprotect.data.bootstrap import ProtectDeviceRef
from uiprotect.test_util.anonymize import random_hex
from uiprotect.websocket import WebsocketState
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant, split_entity_id
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.entity import EntityDescription
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
from tests.common import MockConfigEntry, async_fire_time_changed
@dataclass
class MockUFPFixture:
"""Mock for NVR."""
entry: MockConfigEntry
api: ProtectApiClient
ws_subscription: Callable[[WSSubscriptionMessage], None] | None = None
ws_state_subscription: Callable[[WebsocketState], None] | None = None
def ws_msg(self, msg: WSSubscriptionMessage) -> None:
"""Emit WS message for testing."""
if self.ws_subscription is not None:
self.ws_subscription(msg)
def reset_objects(bootstrap: Bootstrap):
"""Reset bootstrap objects."""
bootstrap.cameras = {}
bootstrap.lights = {}
bootstrap.sensors = {}
bootstrap.viewers = {}
bootstrap.events = {}
bootstrap.doorlocks = {}
bootstrap.chimes = {}
async def time_changed(hass: HomeAssistant, seconds: int) -> None:
"""Trigger time changed."""
next_update = dt_util.utcnow() + timedelta(seconds)
async_fire_time_changed(hass, next_update)
await hass.async_block_till_done()
async def enable_entity(
hass: HomeAssistant, entry_id: str, entity_id: str
) -> er.RegistryEntry:
"""Enable a disabled entity."""
entity_registry = er.async_get(hass)
updated_entity = entity_registry.async_update_entity(entity_id, disabled_by=None)
assert not updated_entity.disabled
await hass.config_entries.async_reload(entry_id)
await hass.async_block_till_done()
return updated_entity
def assert_entity_counts(
hass: HomeAssistant, platform: Platform, total: int, enabled: int
) -> None:
"""Assert entity counts for a given platform."""
entity_registry = er.async_get(hass)
entities = [
e for e in entity_registry.entities if split_entity_id(e)[0] == platform.value
]
assert len(entities) == total
assert len(hass.states.async_all(platform.value)) == enabled
def normalize_name(name: str) -> str:
"""Normalize name."""
return name.lower().replace(":", "").replace(" ", "_").replace("-", "_")
def ids_from_device_description(
platform: Platform,
device: ProtectAdoptableDeviceModel,
description: EntityDescription,
) -> tuple[str, str]:
"""Return expected unique_id and entity_id for a give platform/device/description combination."""
entity_name = normalize_name(device.display_name)
if description.name and isinstance(description.name, str):
description_entity_name = normalize_name(description.name)
else:
description_entity_name = normalize_name(description.key)
unique_id = f"{device.mac}_{description.key}"
entity_id = f"{platform.value}.{entity_name}_{description_entity_name}"
return unique_id, entity_id
def generate_random_ids() -> tuple[str, str]:
"""Generate random IDs for device."""
return random_hex(24).lower(), random_hex(12).upper()
def regenerate_device_ids(device: ProtectAdoptableDeviceModel) -> None:
"""Regenerate the IDs on UFP device."""
device.id, device.mac = generate_random_ids()
def add_device_ref(bootstrap: Bootstrap, device: ProtectAdoptableDeviceModel) -> None:
"""Manually add device ref to bootstrap for lookup."""
ref = ProtectDeviceRef(id=device.id, model=device.model)
bootstrap.id_lookup[device.id] = ref
bootstrap.mac_lookup[device.mac.lower()] = ref
def add_device(
bootstrap: Bootstrap, device: ProtectAdoptableDeviceModel, regenerate_ids: bool
) -> None:
"""Add test device to bootstrap."""
if device.model is None:
return
device._api = bootstrap.api
if isinstance(device, Camera):
for channel in device.channels:
channel._api = bootstrap.api
if regenerate_ids:
regenerate_device_ids(device)
devices = getattr(bootstrap, f"{device.model.value}s")
devices[device.id] = device
add_device_ref(bootstrap, device)
async def init_entry(
hass: HomeAssistant,
ufp: MockUFPFixture,
devices: Sequence[ProtectAdoptableDeviceModel],
regenerate_ids: bool = True,
debug: bool = False,
) -> None:
"""Initialize Protect entry with given devices."""
reset_objects(ufp.api.bootstrap)
for device in devices:
add_device(ufp.api.bootstrap, device, regenerate_ids)
if debug:
assert await async_setup_component(hass, "logger", {"logger": {}})
await hass.services.async_call(
"logger",
"set_level",
{"homeassistant.components.unifiprotect": "DEBUG"},
blocking=True,
)
await hass.config_entries.async_setup(ufp.entry.entry_id)
await hass.async_block_till_done()
async def remove_entities(
hass: HomeAssistant,
ufp: MockUFPFixture,
ufp_devices: list[ProtectAdoptableDeviceModel],
) -> None:
"""Remove all entities for given Protect devices."""
for ufp_device in ufp_devices:
if not ufp_device.is_adopted_by_us:
continue
devices = getattr(ufp.api.bootstrap, f"{ufp_device.model.value}s")
del devices[ufp_device.id]
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.old_obj = ufp_device
mock_msg.new_obj = None
ufp.ws_msg(mock_msg)
await time_changed(hass, 30)
async def adopt_devices(
hass: HomeAssistant,
ufp: MockUFPFixture,
ufp_devices: list[ProtectAdoptableDeviceModel],
fully_adopt: bool = False,
):
"""Emit WS to re-adopt give Protect devices."""
for ufp_device in ufp_devices:
if fully_adopt:
ufp_device.is_adopted = True
ufp_device.is_adopted_by_other = False
ufp_device.can_adopt = False
devices = getattr(ufp.api.bootstrap, f"{ufp_device.model.value}s")
devices[ufp_device.id] = ufp_device
mock_msg = Mock()
mock_msg.changed_data = {}
mock_msg.new_obj = Event(
api=ufp_device.api,
id=random_hex(24),
smart_detect_types=[],
smart_detect_event_ids=[],
type=EventType.DEVICE_ADOPTED,
start=dt_util.utcnow(),
score=100,
metadata={"device_id": ufp_device.id},
model=ModelType.EVENT,
)
ufp.ws_msg(mock_msg)
await hass.async_block_till_done()