-
-
Notifications
You must be signed in to change notification settings - Fork 38.6k
Detect and discard stale iCloud locations #181391
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
TeroPihlaja
wants to merge
1
commit into
home-assistant:dev
Choose a base branch
from
TeroPihlaja:icloud/stale-location-detection
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,41 @@ | ||
| """Tests for the iCloud component.""" | ||
|
|
||
|
|
||
| class MockAppleDevice: | ||
| """Mock Apple device implementing .status() used by the account.""" | ||
|
|
||
| def __init__(self, status_dict) -> None: | ||
| """Set status.""" | ||
| self._status = status_dict | ||
|
|
||
| def status(self, key): | ||
| """Return current status.""" | ||
| return self._status | ||
|
|
||
| def __getitem__(self, key): | ||
| """Allow indexing to proxy into the raw status dict.""" | ||
| return self._status.get(key) | ||
|
|
||
|
|
||
| class MockDevicesContainer: | ||
| """Mock devices container, iterable and indexable.""" | ||
|
|
||
| def __init__(self, userinfo, devices) -> None: | ||
| """Initialize with userinfo and list of device objects.""" | ||
| self.user_info = userinfo | ||
| self._devices = devices | ||
|
|
||
| def __iter__(self): | ||
| """Iterate returns device objects (each must have .status(...)).""" | ||
| return iter(self._devices) | ||
|
|
||
| def __len__(self): | ||
| """Return number of devices.""" | ||
| return len(self._devices) | ||
|
|
||
| def __getitem__(self, idx): | ||
| """Indexing returns device object (which must have .status(...)).""" | ||
| dev = self._devices[idx] | ||
| if hasattr(dev, "status"): | ||
| return dev.status(None) | ||
| return dev |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| """Tests for the iCloud device tracker.""" | ||
|
|
||
| from datetime import timedelta | ||
|
|
||
| from freezegun.api import FrozenDateTimeFactory | ||
| import pytest | ||
|
|
||
| from homeassistant.components.icloud.const import DEFAULT_MAX_INTERVAL, DOMAIN | ||
| from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE, STATE_UNKNOWN | ||
| from homeassistant.core import HomeAssistant | ||
| from homeassistant.util import dt as dt_util | ||
|
|
||
| from .const import MOCK_CONFIG, USERNAME | ||
|
|
||
| from tests.common import MockConfigEntry, async_fire_time_changed | ||
|
|
||
| ENTITY_ID = "device_tracker.iphone" | ||
|
|
||
|
|
||
| def location(*, is_old: bool, age: timedelta) -> dict: | ||
| """Return a location fix of a given age, as iCloud reports it.""" | ||
| fixed_at = dt_util.utcnow() - age | ||
| return { | ||
| "latitude": 1.0, | ||
| "longitude": 2.0, | ||
| "horizontalAccuracy": 10, | ||
| "isOld": is_old, | ||
| "timeStamp": fixed_at.timestamp() * 1000, | ||
| } | ||
|
|
||
|
|
||
| async def setup_account(hass: HomeAssistant) -> MockConfigEntry: | ||
| """Set up the iCloud integration.""" | ||
| config_entry = MockConfigEntry( | ||
| domain=DOMAIN, data=MOCK_CONFIG, entry_id="test", unique_id=USERNAME | ||
| ) | ||
| config_entry.add_to_hass(hass) | ||
| await hass.config_entries.async_setup(config_entry.entry_id) | ||
| await hass.async_block_till_done() | ||
| return config_entry | ||
|
|
||
|
|
||
| async def next_fetch(hass: HomeAssistant, freezer: FrozenDateTimeFactory) -> None: | ||
| """Let the account poll iCloud again.""" | ||
| freezer.tick(timedelta(minutes=DEFAULT_MAX_INTERVAL + 1)) | ||
| async_fire_time_changed(hass) | ||
| await hass.async_block_till_done() | ||
|
|
||
|
|
||
| @pytest.mark.usefixtures("locating_service") | ||
| async def test_location_reported(hass: HomeAssistant) -> None: | ||
| """Test that a fresh fix is reported.""" | ||
| await setup_account(hass) | ||
|
|
||
| state = hass.states.get(ENTITY_ID) | ||
| assert state.attributes[ATTR_LATITUDE] == 1.0 | ||
| assert state.attributes[ATTR_LONGITUDE] == 2.0 | ||
|
|
||
|
|
||
| async def test_stale_location_cleared( | ||
| hass: HomeAssistant, | ||
| locating_service: tuple, | ||
| freezer: FrozenDateTimeFactory, | ||
| ) -> None: | ||
| """Test that a cached fix older than a polling cycle is discarded.""" | ||
| _, status = locating_service | ||
| await setup_account(hass) | ||
| assert ATTR_LATITUDE in hass.states.get(ENTITY_ID).attributes | ||
|
|
||
| # iCloud keeps serving the same fix, now a cached one and older than a | ||
| # full polling cycle: the device has moved on without telling us. | ||
| status["location"] = location( | ||
| is_old=True, age=timedelta(minutes=DEFAULT_MAX_INTERVAL * 3) | ||
| ) | ||
| await next_fetch(hass, freezer) | ||
|
|
||
| state = hass.states.get(ENTITY_ID) | ||
| assert ATTR_LATITUDE not in state.attributes | ||
| # No coordinates and no zone, so the tracker reports that it does not | ||
| # know where the device is rather than claiming it is away. | ||
| assert state.state == STATE_UNKNOWN | ||
|
|
||
|
|
||
| async def test_recent_cached_location_kept( | ||
| hass: HomeAssistant, | ||
| locating_service: tuple, | ||
| freezer: FrozenDateTimeFactory, | ||
| ) -> None: | ||
| """Test that a cached but recent fix is kept. | ||
|
|
||
| A device that was only briefly unreachable is reported the same way as one | ||
| that has moved away, so the flag alone must not discard a location. | ||
| """ | ||
| _, status = locating_service | ||
| await setup_account(hass) | ||
|
|
||
| status["location"] = location(is_old=True, age=timedelta(seconds=30)) | ||
| await next_fetch(hass, freezer) | ||
|
|
||
| assert hass.states.get(ENTITY_ID).attributes[ATTR_LATITUDE] == 1.0 | ||
|
|
||
|
|
||
| async def test_old_uncached_location_kept( | ||
| hass: HomeAssistant, | ||
| locating_service: tuple, | ||
| freezer: FrozenDateTimeFactory, | ||
| ) -> None: | ||
| """Test that an old fix iCloud still considers current is kept. | ||
|
|
||
| A device that is sitting still reports an old timestamp indefinitely, so | ||
| age alone must not be enough to discard a location either. | ||
| """ | ||
| _, status = locating_service | ||
| await setup_account(hass) | ||
|
|
||
| status["location"] = location( | ||
| is_old=False, age=timedelta(minutes=DEFAULT_MAX_INTERVAL * 3) | ||
| ) | ||
| await next_fetch(hass, freezer) | ||
|
|
||
| assert hass.states.get(ENTITY_ID).attributes[ATTR_LATITUDE] == 1.0 | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.