Fix OwnTracks race condition (#24303)

* Fix OwnTracks race condition

* Lint
This commit is contained in:
Paulus Schoutsen 2019-06-04 14:06:49 -07:00 committed by GitHub
parent 6d280084fb
commit df1da7554c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 34 additions and 3 deletions

View File

@ -192,6 +192,7 @@ class OwnTracksContext:
self.region_mapping = region_mapping
self.events_only = events_only
self.mqtt_topic = mqtt_topic
self._pending_msg = []
@callback
def async_valid_accuracy(self, message):
@ -222,10 +223,19 @@ class OwnTracksContext:
return True
@callback
def set_async_see(self, func):
"""Set a new async_see function."""
self.async_see = func
for msg in self._pending_msg:
func(**msg)
self._pending_msg.clear()
# pylint: disable=method-hidden
@callback
def async_see(self, **data):
"""Send a see message to the device tracker."""
raise NotImplementedError
self._pending_msg.append(data)
@callback
def async_see_beacons(self, hass, dev_id, kwargs_param):

View File

@ -36,7 +36,7 @@ async def async_setup_entry(hass, entry, async_add_entities):
)
async_add_entities([entity])
hass.data[OT_DOMAIN]['context'].async_see = _receive_data
hass.data[OT_DOMAIN]['context'].set_async_see(_receive_data)
# Restore previously loaded devices
dev_reg = await device_registry.async_get_registry(hass)

View File

@ -4,7 +4,7 @@ import asyncio
import pytest
from homeassistant.setup import async_setup_component
from homeassistant.components import owntracks
from tests.common import mock_component, MockConfigEntry
MINIMAL_LOCATION_MESSAGE = {
@ -160,3 +160,24 @@ def test_returns_error_missing_device(mock_client):
json = yield from resp.json()
assert json == []
def test_context_delivers_pending_msg():
"""Test that context is able to hold pending messages while being init."""
context = owntracks.OwnTracksContext(
None, None, None, None, None, None, None, None
)
context.async_see(hello='world')
context.async_see(world='hello')
received = []
context.set_async_see(lambda **data: received.append(data))
assert len(received) == 2
assert received[0] == {'hello': 'world'}
assert received[1] == {'world': 'hello'}
received.clear()
context.set_async_see(lambda **data: received.append(data))
assert len(received) == 0