async def test_light_set_light(light_obj: Light, status: bool, level: Optional[int]): light_obj.api.api_request.reset_mock() light_obj.light_on_settings.is_led_force_on = not status if level is not None: light_obj.light_device_settings.led_level = 2 light_obj._initial_data = light_obj.dict() if level in (0, 7): with pytest.raises(ValidationError): await light_obj.set_light(status, level) assert not light_obj.api.api_request.called else: await light_obj.set_light(status, level) if level is None: expected = {"lightOnSettings": {"isLedForceOn": status}} else: expected = { "lightOnSettings": { "isLedForceOn": status }, "lightDeviceSettings": { "ledLevel": level } } light_obj.api.api_request.assert_called_with( f"lights/{light_obj.id}", method="patch", json=expected, )
async def test_light_set_duration( light_obj: Light, duration: timedelta, ): light_obj.api.api_request.reset_mock() light_obj.light_device_settings.pir_duration = timedelta(seconds=30) light_obj._initial_data = light_obj.dict() duration_invalid = duration is not None and int( duration.total_seconds()) in (1, 1000) if duration_invalid: with pytest.raises(BadRequest): await light_obj.set_duration(duration) assert not light_obj.api.api_request.called else: await light_obj.set_duration(duration) expected = {"lightDeviceSettings": {"pirDuration": to_ms(duration)}} light_obj.api.api_request.assert_called_with( f"lights/{light_obj.id}", method="patch", json=expected, )
async def test_switch_light_status(hass: HomeAssistant, ufp: MockUFPFixture, light: Light): """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.__fields__["set_status_light"] = Mock() 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_select_set_option_light_camera( hass: HomeAssistant, light: Light, ): """Test Paired Camera select.""" _, entity_id = ids_from_device_description(Platform.SELECT, light, LIGHT_SELECTS[1]) light.__fields__["set_paired_camera"] = Mock() 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_migrate_reboot_button( hass: HomeAssistant, mock_entry: MockEntityFixture, mock_light: Light ): """Test migrating unique ID of reboot button.""" light1 = mock_light.copy() light1._api = mock_entry.api light1.name = "Test Light 1" light1.id = "lightid1" light2 = mock_light.copy() light2._api = mock_entry.api light2.name = "Test Light 2" light2.id = "lightid2" mock_entry.api.bootstrap.lights = { light1.id: light1, light2.id: light2, } mock_entry.api.get_bootstrap = AsyncMock(return_value=mock_entry.api.bootstrap) registry = er.async_get(hass) registry.async_get_or_create( Platform.BUTTON, DOMAIN, light1.id, config_entry=mock_entry.entry ) registry.async_get_or_create( Platform.BUTTON, DOMAIN, f"{light2.id}_reboot", config_entry=mock_entry.entry, ) await hass.config_entries.async_setup(mock_entry.entry.entry_id) await hass.async_block_till_done() assert mock_entry.entry.state == ConfigEntryState.LOADED assert mock_entry.api.update.called assert mock_entry.entry.unique_id == mock_entry.api.bootstrap.nvr.mac buttons = [] for entity in er.async_entries_for_config_entry( registry, mock_entry.entry.entry_id ): if entity.domain == Platform.BUTTON.value: buttons.append(entity) print(entity.entity_id) assert len(buttons) == 2 assert registry.async_get(f"{Platform.BUTTON}.test_light_1_reboot_device") is None assert registry.async_get(f"{Platform.BUTTON}.test_light_1_reboot_device_2") is None light = registry.async_get(f"{Platform.BUTTON}.unifiprotect_lightid1") assert light is not None assert light.unique_id == f"{light1.id}_reboot" assert registry.async_get(f"{Platform.BUTTON}.test_light_2_reboot_device") is None assert registry.async_get(f"{Platform.BUTTON}.test_light_2_reboot_device_2") is None light = registry.async_get(f"{Platform.BUTTON}.unifiprotect_lightid2_reboot") assert light is not None assert light.unique_id == f"{light2.id}_reboot"
async def test_light_set_light_settings( light_obj: Light, mode: LightModeType, enable_at: Optional[LightModeEnableType], duration: Optional[timedelta], sensitivity: Optional[int], ): light_obj.api.api_request.reset_mock() light_obj.light_mode_settings.mode = LightModeType.MOTION light_obj.light_mode_settings.enable_at = LightModeEnableType.DARK light_obj.light_device_settings.pir_duration = timedelta(seconds=30) light_obj.light_device_settings.pir_sensitivity = 50 light_obj._initial_data = light_obj.dict() duration_invalid = duration is not None and int( duration.total_seconds()) in (1, 1000) if duration_invalid: with pytest.raises(BadRequest): await light_obj.set_light_settings(mode, enable_at=enable_at, duration=duration, sensitivity=sensitivity) assert not light_obj.api.api_request.called elif sensitivity == -10: with pytest.raises(ValidationError): await light_obj.set_light_settings(mode, enable_at=enable_at, duration=duration, sensitivity=sensitivity) assert not light_obj.api.api_request.called else: await light_obj.set_light_settings(mode, enable_at=enable_at, duration=duration, sensitivity=sensitivity) expected = {"lightModeSettings": {"mode": mode.value}} if enable_at is not None: expected["lightModeSettings"].update({"enableAt": enable_at.value}) if duration is not None: expected["lightDeviceSettings"] = expected.get( "lightDeviceSettings", {}) expected["lightDeviceSettings"].update( {"pirDuration": to_ms(duration)}) if sensitivity is not None: expected["lightDeviceSettings"] = expected.get( "lightDeviceSettings", {}) expected["lightDeviceSettings"].update( {"pirSensitivity": sensitivity}) light_obj.api.api_request.assert_called_with( f"lights/{light_obj.id}", method="patch", json=expected, )
async def test_migrate_reboot_button(hass: HomeAssistant, ufp: MockUFPFixture, light: Light): """Test migrating unique ID of reboot button.""" light1 = light.copy() light1.name = "Test Light 1" regenerate_device_ids(light1) light2 = light.copy() light2.name = "Test Light 2" regenerate_device_ids(light2) registry = er.async_get(hass) registry.async_get_or_create(Platform.BUTTON, DOMAIN, light1.id, config_entry=ufp.entry) registry.async_get_or_create( Platform.BUTTON, DOMAIN, f"{light2.mac}_reboot", config_entry=ufp.entry, ) ufp.api.get_bootstrap = AsyncMock(return_value=ufp.api.bootstrap) await init_entry(hass, ufp, [light1, light2], regenerate_ids=False) assert ufp.entry.state == ConfigEntryState.LOADED assert ufp.api.update.called assert ufp.entry.unique_id == ufp.api.bootstrap.nvr.mac buttons = [] for entity in er.async_entries_for_config_entry(registry, ufp.entry.entry_id): if entity.domain == Platform.BUTTON.value: buttons.append(entity) assert len(buttons) == 4 assert registry.async_get( f"{Platform.BUTTON}.test_light_1_reboot_device") is None assert registry.async_get( f"{Platform.BUTTON}.test_light_1_reboot_device_2") is None light = registry.async_get( f"{Platform.BUTTON}.unifiprotect_{light1.id.lower()}") assert light is not None assert light.unique_id == f"{light1.mac}_reboot" assert registry.async_get( f"{Platform.BUTTON}.test_light_2_reboot_device") is None assert registry.async_get( f"{Platform.BUTTON}.test_light_2_reboot_device_2") is None light = registry.async_get( f"{Platform.BUTTON}.unifiprotect_{light2.mac.lower()}_reboot") assert light is not None assert light.unique_id == f"{light2.mac}_reboot"
async def test_light_set_status_light(light_obj: Light, status: bool): light_obj.api.api_request.reset_mock() light_obj.light_device_settings.is_indicator_enabled = not status light_obj._initial_data = light_obj.dict() await light_obj.set_status_light(status) light_obj.api.api_request.assert_called_with( f"lights/{light_obj.id}", method="patch", json={"lightDeviceSettings": { "isIndicatorEnabled": status }}, )
async def light_fixture( hass: HomeAssistant, mock_entry: MockEntityFixture, mock_light: Light, camera: Camera, ): """Fixture for a single light for testing the select platform.""" # disable pydantic validation so mocking can happen Light.__config__.validate_assignment = False light_obj = mock_light.copy(deep=True) light_obj._api = mock_entry.api light_obj.name = "Test Light" light_obj.camera_id = None light_obj.light_mode_settings.mode = LightModeType.MOTION light_obj.light_mode_settings.enable_at = LightModeEnableType.DARK mock_entry.api.bootstrap.reset_objects() mock_entry.api.bootstrap.cameras = {camera.id: camera} mock_entry.api.bootstrap.lights = { light_obj.id: light_obj, } await hass.config_entries.async_reload(mock_entry.entry.entry_id) await hass.async_block_till_done() assert_entity_counts(hass, Platform.SELECT, 6, 6) yield light_obj Light.__config__.validate_assignment = True
async def light_fixture(hass: HomeAssistant, mock_entry: MockEntityFixture, mock_light: Light): """Fixture for a single light for testing the number platform.""" # disable pydantic validation so mocking can happen Light.__config__.validate_assignment = False light_obj = mock_light.copy(deep=True) light_obj._api = mock_entry.api light_obj.name = "Test Light" light_obj.light_device_settings.pir_sensitivity = 45 light_obj.light_device_settings.pir_duration = timedelta(seconds=45) mock_entry.api.bootstrap.reset_objects() mock_entry.api.bootstrap.lights = { light_obj.id: light_obj, } await hass.config_entries.async_setup(mock_entry.entry.entry_id) await hass.async_block_till_done() assert_entity_counts(hass, Platform.NUMBER, 2, 2) yield light_obj Light.__config__.validate_assignment = True
async def light_fixture(hass: HomeAssistant, mock_entry: MockEntityFixture, mock_light: Light, now: datetime): """Fixture for a single light for testing the binary_sensor platform.""" # disable pydantic validation so mocking can happen Light.__config__.validate_assignment = False light_obj = mock_light.copy(deep=True) light_obj._api = mock_entry.api light_obj.name = "Test Light" light_obj.is_dark = False light_obj.is_pir_motion_detected = False light_obj.last_motion = now - timedelta(hours=1) mock_entry.api.bootstrap.reset_objects() mock_entry.api.bootstrap.nvr.system_info.storage.devices = [] mock_entry.api.bootstrap.lights = { light_obj.id: light_obj, } await hass.config_entries.async_setup(mock_entry.entry.entry_id) await hass.async_block_till_done() assert_entity_counts(hass, Platform.BINARY_SENSOR, 2, 2) yield light_obj Light.__config__.validate_assignment = True
async def light_fixture(hass: HomeAssistant, mock_entry: MockEntityFixture, mock_light: Light): """Fixture for a single light for testing the switch platform.""" # disable pydantic validation so mocking can happen Light.__config__.validate_assignment = False light_obj = mock_light.copy(deep=True) light_obj._api = mock_entry.api light_obj.name = "Test Light" light_obj.is_ssh_enabled = False light_obj.light_device_settings.is_indicator_enabled = False mock_entry.api.bootstrap.reset_objects() mock_entry.api.bootstrap.lights = { light_obj.id: light_obj, } await hass.config_entries.async_setup(mock_entry.entry.entry_id) await hass.async_block_till_done() assert_entity_counts(hass, Platform.SWITCH, 2, 1) yield light_obj Light.__config__.validate_assignment = True
def unadopted_light(light: Light): """Mock UniFi Protect Light device (unadopted).""" no_light = light.copy() no_light.name = "Unadopted Light" no_light.is_adopted = False return no_light
async def test_number_light_duration(hass: HomeAssistant, light: Light): """Test auto-shutoff duration number entity for lights.""" description = LIGHT_NUMBERS[1] light.__fields__["set_duration"] = Mock() 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))
def light_fixture(): """Mock UniFi Protect Light device.""" # disable pydantic validation so mocking can happen Light.__config__.validate_assignment = False data = json.loads(load_fixture("sample_light.json", integration=DOMAIN)) yield Light.from_unifi_dict(**data) Light.__config__.validate_assignment = True
async def test_light_turn_off(hass: HomeAssistant, ufp: MockUFPFixture, light: Light, unadopted_light: Light): """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.__fields__["set_light"] = Mock() 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)
async def test_select_set_option_light_motion( hass: HomeAssistant, light: Light, ): """Test Light Mode select.""" _, entity_id = ids_from_device_description(Platform.SELECT, light, LIGHT_SELECTS[0]) light.__fields__["set_light_settings"] = Mock() 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_number_light_sensitivity(hass: HomeAssistant, light: Light): """Test sensitivity number entity for lights.""" description = LIGHT_NUMBERS[0] assert description.ufp_set_method is not None light.__fields__["set_sensitivity"] = Mock() 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_light_set_led_level(light_obj: Light, level: int): light_obj.api.api_request.reset_mock() light_obj.light_device_settings.led_level = 2 light_obj._initial_data = light_obj.dict() if level in (0, 7): with pytest.raises(ValidationError): await light_obj.set_led_level(level) assert not light_obj.api.api_request.called else: await light_obj.set_led_level(level) light_obj.api.api_request.assert_called_with( f"lights/{light_obj.id}", method="patch", json={"lightDeviceSettings": { "ledLevel": level }}, )
async def test_migrate_nvr_mac(hass: HomeAssistant, ufp: MockUFPFixture, light: Light): """Test migrating unique ID of NVR to use MAC address.""" light1 = light.copy() light1.name = "Test Light 1" regenerate_device_ids(light1) light2 = light.copy() light2.name = "Test Light 2" regenerate_device_ids(light2) nvr = ufp.api.bootstrap.nvr regenerate_device_ids(nvr) registry = er.async_get(hass) registry.async_get_or_create( Platform.SENSOR, DOMAIN, f"{nvr.id}_storage_utilization", config_entry=ufp.entry, ) ufp.api.get_bootstrap = AsyncMock(return_value=ufp.api.bootstrap) await init_entry(hass, ufp, [light1, light2], regenerate_ids=False) assert ufp.entry.state == ConfigEntryState.LOADED assert ufp.api.update.called assert ufp.entry.unique_id == ufp.api.bootstrap.nvr.mac assert registry.async_get( f"{Platform.SENSOR}.{DOMAIN}_storage_utilization") is None assert ( registry.async_get(f"{Platform.SENSOR}.{DOMAIN}_storage_utilization_2") is None) sensor = registry.async_get( f"{Platform.SENSOR}.{DOMAIN}_{nvr.id}_storage_utilization") assert sensor is not None assert sensor.unique_id == f"{nvr.mac}_storage_utilization"
async def test_light_set_sensitivity( light_obj: Light, sensitivity: int, ): light_obj.api.api_request.reset_mock() light_obj.light_device_settings.pir_sensitivity = 50 light_obj._initial_data = light_obj.dict() if sensitivity == -10: with pytest.raises(ValidationError): await light_obj.set_sensitivity(sensitivity) assert not light_obj.api.api_request.called else: await light_obj.set_sensitivity(sensitivity) expected = {"lightDeviceSettings": {"pirSensitivity": sensitivity}} light_obj.api.api_request.assert_called_with( f"lights/{light_obj.id}", method="patch", json=expected, )
async def subdevice_fixture(hass: HomeAssistant, mock_entry: MockEntityFixture, mock_light: Light): """Fixture with entry setup to call services with.""" mock_light._api = mock_entry.api mock_entry.api.bootstrap.lights = { mock_light.id: mock_light, } await hass.config_entries.async_setup(mock_entry.entry.entry_id) await hass.async_block_till_done() device_registry = dr.async_get(hass) return [ d for d in device_registry.devices.values() if d.name != "UnifiProtect" ][0]
async def test_migrate_reboot_button_fail(hass: HomeAssistant, mock_entry: MockEntityFixture, mock_light: Light): """Test migrating unique ID of reboot button.""" light1 = mock_light.copy() light1._api = mock_entry.api light1.name = "Test Light 1" light1.id = "lightid1" mock_entry.api.bootstrap.lights = { light1.id: light1, } mock_entry.api.get_bootstrap = AsyncMock( return_value=mock_entry.api.bootstrap) registry = er.async_get(hass) registry.async_get_or_create( Platform.BUTTON, DOMAIN, light1.id, config_entry=mock_entry.entry, suggested_object_id=light1.name, ) registry.async_get_or_create( Platform.BUTTON, DOMAIN, f"{light1.id}_reboot", config_entry=mock_entry.entry, suggested_object_id=light1.name, ) await hass.config_entries.async_setup(mock_entry.entry.entry_id) await hass.async_block_till_done() assert mock_entry.entry.state == ConfigEntryState.LOADED assert mock_entry.api.update.called assert mock_entry.entry.unique_id == mock_entry.api.bootstrap.nvr.mac light = registry.async_get(f"{Platform.BUTTON}.test_light_1") assert light is not None assert light.unique_id == f"{light1.id}"
async def test_binary_sensor_update_light_motion( hass: HomeAssistant, ufp: MockUFPFixture, light: Light, fixed_now: datetime ): """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( 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.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_device_remove_devices( hass: HomeAssistant, mock_entry: MockEntityFixture, mock_light: Light, hass_ws_client: Callable[[HomeAssistant], Awaitable[aiohttp.ClientWebSocketResponse]], ) -> None: """Test we can only remove a device that no longer exists.""" assert await async_setup_component(hass, "config", {}) light1 = mock_light.copy() light1._api = mock_entry.api light1.name = "Test Light 1" light1.id = "lightid1" light1.mac = "AABBCCDDEEFF" mock_entry.api.bootstrap.lights = { light1.id: light1, } mock_entry.api.get_bootstrap = AsyncMock( return_value=mock_entry.api.bootstrap) light_entity_id = "light.test_light_1" await hass.config_entries.async_setup(mock_entry.entry.entry_id) await hass.async_block_till_done() entry_id = mock_entry.entry.entry_id registry: er.EntityRegistry = er.async_get(hass) entity = registry.entities[light_entity_id] device_registry = dr.async_get(hass) live_device_entry = device_registry.async_get(entity.device_id) assert (await remove_device(await hass_ws_client(hass), live_device_entry.id, entry_id) is False) 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")}, ) assert (await remove_device(await hass_ws_client(hass), dead_device_entry.id, entry_id) is True)
async def test_binary_sensor_update_light_motion(hass: HomeAssistant, mock_entry: MockEntityFixture, light: Light, now: datetime): """Test binary_sensor motion entity.""" _, entity_id = ids_from_device_description(Platform.BINARY_SENSOR, light, LIGHT_SENSORS[1]) event_metadata = EventMetadata(light_id=light.id) event = Event( id="test_event_id", type=EventType.MOTION_LIGHT, start=now - timedelta(seconds=1), end=None, score=100, smart_detect_types=[], smart_detect_event_ids=[], metadata=event_metadata, api=mock_entry.api, ) new_bootstrap = copy(mock_entry.api.bootstrap) new_light = light.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 new_bootstrap.lights = {new_light.id: new_light} new_bootstrap.events = {event.id: event} mock_entry.api.bootstrap = new_bootstrap mock_entry.api.ws_subscription(mock_msg) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state assert state.state == STATE_ON
async def test_light_update(hass: HomeAssistant, ufp: MockUFPFixture, light: Light, unadopted_light: Light): """Test light entity update.""" await init_entry(hass, ufp, [light, unadopted_light]) assert_entity_counts(hass, Platform.LIGHT, 1, 1) new_light = light.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 light_fixture(hass: HomeAssistant, mock_entry: MockEntityFixture, mock_light: Light): """Fixture for a single light for testing the light platform.""" # disable pydantic validation so mocking can happen Light.__config__.validate_assignment = False light_obj = mock_light.copy(deep=True) light_obj._api = mock_entry.api light_obj.name = "Test Light" light_obj.is_light_on = False mock_entry.api.bootstrap.lights = { light_obj.id: light_obj, } await hass.config_entries.async_setup(mock_entry.entry.entry_id) await hass.async_block_till_done() assert_entity_counts(hass, Platform.LIGHT, 1, 1) yield (light_obj, "light.test_light") Light.__config__.validate_assignment = True
def mock_light(): """Mock UniFi Protect Light device.""" data = json.loads(load_fixture("sample_light.json", integration=DOMAIN)) return Light.from_unifi_dict(**data)