From ac498100a10d6001cd33febe304972a3b792e830 Mon Sep 17 00:00:00 2001 From: Tero Pihlaja Date: Fri, 16 Oct 2026 20:34:13 +0300 Subject: [PATCH] Do not lose an iCloud poll to a failed locate request (#182855) Co-authored-by: Claude Opus 5 --- homeassistant/components/icloud/account.py | 22 ++-- tests/components/icloud/test_account.py | 119 +++++++++++++++++++++ 2 files changed, 134 insertions(+), 7 deletions(-) diff --git a/homeassistant/components/icloud/account.py b/homeassistant/components/icloud/account.py index bfc244f51f11..639cfffbdbd0 100644 --- a/homeassistant/components/icloud/account.py +++ b/homeassistant/components/icloud/account.py @@ -267,13 +267,6 @@ class IcloudAccount: try: api_devices = self.api.devices - if locate: - # Since pyicloud 2.3.0 device reads are cache-only and the - # library requests an active locate from Apple only at service - # creation, so explicitly refresh with locate=True to get a - # fresh GPS fix on every poll instead of Apple's cached - # location. - api_devices.refresh(locate=True) except Exception as err: if _is_auth_failure(err): # Refreshing the devices is where a stored session is usually @@ -286,6 +279,21 @@ class IcloudAccount: self._schedule_next_fetch() return + if locate: + # Since pyicloud 2.3.0 device reads are cache-only and the library + # requests an active locate from Apple only at service creation, so + # explicitly refresh with locate=True to get a fresh GPS fix on + # every poll instead of Apple's cached location. + try: + api_devices.refresh(locate=True) + except Exception as err: + if _is_auth_failure(err): + raise + # Best effort: the devices read below still carry whichever + # fixes iCloud already held, which beats skipping the poll + # altogether. + _LOGGER.debug("Could not request an iCloud location refresh: %s", err) + if self._owner_fullname is None and api_devices.user_info is not None: # setup() returns before reading these when iCloud asks for a # verification code, and keep_alive() only runs a full setup again diff --git a/tests/components/icloud/test_account.py b/tests/components/icloud/test_account.py index a4b86b5c19f9..b21d5c87529f 100644 --- a/tests/components/icloud/test_account.py +++ b/tests/components/icloud/test_account.py @@ -240,6 +240,125 @@ async def test_setup_success_with_devices( assert mock_icloud_service.return_value.devices.refresh_calls == [True] +async def test_a_failed_locate_does_not_cost_the_poll( + hass: HomeAssistant, + mock_store: Mock, + mock_icloud_service: MagicMock, +) -> None: + """Test that the devices are still read when the locate request fails. + + Locating is best effort. iCloud still holds whichever fixes it had, and + reading those beats leaving the account with nothing at all until the + next poll comes round. + """ + config_entry = MockConfigEntry( + domain=DOMAIN, data=MOCK_CONFIG, entry_id="test", unique_id=USERNAME + ) + config_entry.add_to_hass(hass) + + account = IcloudAccount( + hass, + MOCK_CONFIG[CONF_USERNAME], + MOCK_CONFIG[CONF_PASSWORD], + mock_store, + MOCK_CONFIG[CONF_WITH_FAMILY], + MOCK_CONFIG[CONF_MAX_INTERVAL], + MOCK_CONFIG[CONF_GPS_ACCURACY_THRESHOLD], + config_entry, + ) + service = mock_icloud_service.return_value + + with patch.object(account, "_schedule_next_fetch"): + await hass.async_add_executor_job(account.setup) + + # A later poll asks for a locate, and iCloud refuses it. + service.devices.refresh = Mock(side_effect=Exception("locate failed")) + await hass.async_add_executor_job(account.update_devices) + + service.devices.refresh.assert_called_once_with(locate=True) + # An error ending the poll early would have left the two minute retry + # interval in place; reading the devices recomputes it. + assert account.fetch_interval != 2 + assert "device1" in account.devices + + +async def test_a_rejected_session_on_locate_reaches_the_caller( + hass: HomeAssistant, + mock_store: Mock, + mock_icloud_service: MagicMock, +) -> None: + """Test that a locate refused for authentication is not treated as best effort. + + Only a failure to locate is swallowed. A rejected session is what the + caller acts on, by logging in again or asking the user, so it has to be + raised instead of leaving every later poll to fail the same way. + """ + config_entry = MockConfigEntry( + domain=DOMAIN, data=MOCK_CONFIG, entry_id="test", unique_id=USERNAME + ) + config_entry.add_to_hass(hass) + + account = IcloudAccount( + hass, + MOCK_CONFIG[CONF_USERNAME], + MOCK_CONFIG[CONF_PASSWORD], + mock_store, + MOCK_CONFIG[CONF_WITH_FAMILY], + MOCK_CONFIG[CONF_MAX_INTERVAL], + MOCK_CONFIG[CONF_GPS_ACCURACY_THRESHOLD], + config_entry, + ) + service = mock_icloud_service.return_value + + with patch.object(account, "_schedule_next_fetch"): + await hass.async_add_executor_job(account.setup) + + service.devices.refresh = Mock( + side_effect=PyiCloudFailedLoginException("rejected") + ) + with pytest.raises(PyiCloudFailedLoginException): + await hass.async_add_executor_job(account.update_devices) + + +async def test_a_poll_with_no_devices_still_schedules_the_next_one( + hass: HomeAssistant, + mock_store: Mock, + mock_icloud_service: MagicMock, +) -> None: + """Test that an empty device list is not indexed after a failed locate. + + Carrying on past a failed locate reaches the pending-device check with + whatever iCloud had, which can be nothing. Indexing that ends the poll + before it arms the next one, leaving the account stopped. + """ + config_entry = MockConfigEntry( + domain=DOMAIN, data=MOCK_CONFIG, entry_id="test", unique_id=USERNAME + ) + config_entry.add_to_hass(hass) + + account = IcloudAccount( + hass, + MOCK_CONFIG[CONF_USERNAME], + MOCK_CONFIG[CONF_PASSWORD], + mock_store, + MOCK_CONFIG[CONF_WITH_FAMILY], + MOCK_CONFIG[CONF_MAX_INTERVAL], + MOCK_CONFIG[CONF_GPS_ACCURACY_THRESHOLD], + config_entry, + ) + service = mock_icloud_service.return_value + + with patch.object(account, "_schedule_next_fetch") as schedule: + await hass.async_add_executor_job(account.setup) + schedule.reset_mock() + + service.devices = MockDevicesContainer(USER_INFO, []) + service.devices.refresh = Mock(side_effect=Exception("locate failed")) + await hass.async_add_executor_job(account.update_devices) + + schedule.assert_called_once() + + class FakeAppleDevice: """A device that reports status through pyicloud's own implementation.