Convert device tracker init tests to async (#18640)

This commit is contained in:
Adam Mills 2018-11-23 02:55:25 -05:00 committed by Paulus Schoutsen
parent 98f159a039
commit c99204149c
2 changed files with 457 additions and 416 deletions

View File

@ -0,0 +1,31 @@
"""Collection of helper methods.
All containing methods are legacy helpers that should not be used by new
components. Instead call the service directly.
"""
from homeassistant.components.device_tracker import (
DOMAIN, ATTR_ATTRIBUTES, ATTR_BATTERY, ATTR_GPS, ATTR_GPS_ACCURACY,
ATTR_LOCATION_NAME, ATTR_MAC, ATTR_DEV_ID, ATTR_HOST_NAME, SERVICE_SEE)
from homeassistant.core import callback
from homeassistant.helpers.typing import GPSType, HomeAssistantType
from homeassistant.loader import bind_hass
@callback
@bind_hass
def async_see(hass: HomeAssistantType, mac: str = None, dev_id: str = None,
host_name: str = None, location_name: str = None,
gps: GPSType = None, gps_accuracy=None,
battery: int = None, attributes: dict = None):
"""Call service to notify you see device."""
data = {key: value for key, value in
((ATTR_MAC, mac),
(ATTR_DEV_ID, dev_id),
(ATTR_HOST_NAME, host_name),
(ATTR_LOCATION_NAME, location_name),
(ATTR_GPS, gps),
(ATTR_GPS_ACCURACY, gps_accuracy),
(ATTR_BATTERY, battery)) if value is not None}
if attributes:
data[ATTR_ATTRIBUTES] = attributes
hass.async_add_job(hass.services.async_call(DOMAIN, SERVICE_SEE, data))

View File

@ -3,69 +3,60 @@
import asyncio import asyncio
import json import json
import logging import logging
import unittest from unittest.mock import call
from unittest.mock import call, patch
from datetime import datetime, timedelta from datetime import datetime, timedelta
import os import os
from asynctest import patch
import pytest
from homeassistant.components import zone from homeassistant.components import zone
from homeassistant.core import callback, State from homeassistant.core import callback, State
from homeassistant.setup import setup_component, async_setup_component from homeassistant.setup import async_setup_component
from homeassistant.helpers import discovery from homeassistant.helpers import discovery
from homeassistant.loader import get_component from homeassistant.loader import get_component
from homeassistant.util.async_ import run_coroutine_threadsafe
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
from homeassistant.const import ( from homeassistant.const import (
ATTR_ENTITY_ID, ATTR_ENTITY_PICTURE, ATTR_FRIENDLY_NAME, ATTR_HIDDEN, ATTR_ENTITY_ID, ATTR_ENTITY_PICTURE, ATTR_FRIENDLY_NAME, ATTR_HIDDEN,
STATE_HOME, STATE_NOT_HOME, CONF_PLATFORM, ATTR_ICON) STATE_HOME, STATE_NOT_HOME, CONF_PLATFORM, ATTR_ICON)
import homeassistant.components.device_tracker as device_tracker import homeassistant.components.device_tracker as device_tracker
from tests.components.device_tracker import common
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.json import JSONEncoder from homeassistant.helpers.json import JSONEncoder
from tests.common import ( from tests.common import (
get_test_home_assistant, fire_time_changed, async_fire_time_changed, patch_yaml_files, assert_setup_component,
patch_yaml_files, assert_setup_component, mock_restore_cache) mock_restore_cache)
import pytest
TEST_PLATFORM = {device_tracker.DOMAIN: {CONF_PLATFORM: 'test'}} TEST_PLATFORM = {device_tracker.DOMAIN: {CONF_PLATFORM: 'test'}}
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
class TestComponentsDeviceTracker(unittest.TestCase): @pytest.fixture
"""Test the Device tracker.""" def yaml_devices(hass):
"""Get a path for storing yaml devices."""
yaml_devices = hass.config.path(device_tracker.YAML_DEVICES)
if os.path.isfile(yaml_devices):
os.remove(yaml_devices)
yield yaml_devices
if os.path.isfile(yaml_devices):
os.remove(yaml_devices)
hass = None # HomeAssistant
yaml_devices = None # type: str
# pylint: disable=invalid-name async def test_is_on(hass):
def setUp(self):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.yaml_devices = self.hass.config.path(device_tracker.YAML_DEVICES)
# pylint: disable=invalid-name
def tearDown(self):
"""Stop everything that was started."""
if os.path.isfile(self.yaml_devices):
os.remove(self.yaml_devices)
self.hass.stop()
def test_is_on(self):
"""Test is_on method.""" """Test is_on method."""
entity_id = device_tracker.ENTITY_ID_FORMAT.format('test') entity_id = device_tracker.ENTITY_ID_FORMAT.format('test')
self.hass.states.set(entity_id, STATE_HOME) hass.states.async_set(entity_id, STATE_HOME)
assert device_tracker.is_on(self.hass, entity_id) assert device_tracker.is_on(hass, entity_id)
self.hass.states.set(entity_id, STATE_NOT_HOME) hass.states.async_set(entity_id, STATE_NOT_HOME)
assert not device_tracker.is_on(self.hass, entity_id) assert not device_tracker.is_on(hass, entity_id)
# pylint: disable=no-self-use
def test_reading_broken_yaml_config(self): async def test_reading_broken_yaml_config(hass):
"""Test when known devices contains invalid data.""" """Test when known devices contains invalid data."""
files = {'empty.yaml': '', files = {'empty.yaml': '',
'nodict.yaml': '100', 'nodict.yaml': '100',
@ -74,36 +65,41 @@ class TestComponentsDeviceTracker(unittest.TestCase):
'allok.yaml': 'My Device:\n name: Device', 'allok.yaml': 'My Device:\n name: Device',
'oneok.yaml': ('My Device!:\n name: Device\n' 'oneok.yaml': ('My Device!:\n name: Device\n'
'bad_device:\n nme: Device')} 'bad_device:\n nme: Device')}
args = {'hass': self.hass, 'consider_home': timedelta(seconds=60)} args = {'hass': hass, 'consider_home': timedelta(seconds=60)}
with patch_yaml_files(files): with patch_yaml_files(files):
assert device_tracker.load_config('empty.yaml', **args) == [] assert await device_tracker.async_load_config(
assert device_tracker.load_config('nodict.yaml', **args) == [] 'empty.yaml', **args) == []
assert device_tracker.load_config('noname.yaml', **args) == [] assert await device_tracker.async_load_config(
assert device_tracker.load_config('badkey.yaml', **args) == [] 'nodict.yaml', **args) == []
assert await device_tracker.async_load_config(
'noname.yaml', **args) == []
assert await device_tracker.async_load_config(
'badkey.yaml', **args) == []
res = device_tracker.load_config('allok.yaml', **args) res = await device_tracker.async_load_config('allok.yaml', **args)
assert len(res) == 1 assert len(res) == 1
assert res[0].name == 'Device' assert res[0].name == 'Device'
assert res[0].dev_id == 'my_device' assert res[0].dev_id == 'my_device'
res = device_tracker.load_config('oneok.yaml', **args) res = await device_tracker.async_load_config('oneok.yaml', **args)
assert len(res) == 1 assert len(res) == 1
assert res[0].name == 'Device' assert res[0].name == 'Device'
assert res[0].dev_id == 'my_device' assert res[0].dev_id == 'my_device'
def test_reading_yaml_config(self):
async def test_reading_yaml_config(hass, yaml_devices):
"""Test the rendering of the YAML configuration.""" """Test the rendering of the YAML configuration."""
dev_id = 'test' dev_id = 'test'
device = device_tracker.Device( device = device_tracker.Device(
self.hass, timedelta(seconds=180), True, dev_id, hass, timedelta(seconds=180), True, dev_id,
'AB:CD:EF:GH:IJ', 'Test name', picture='http://test.picture', 'AB:CD:EF:GH:IJ', 'Test name', picture='http://test.picture',
hide_if_away=True, icon='mdi:kettle') hide_if_away=True, icon='mdi:kettle')
device_tracker.update_config(self.yaml_devices, dev_id, device) device_tracker.update_config(yaml_devices, dev_id, device)
with assert_setup_component(1, device_tracker.DOMAIN): with assert_setup_component(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN, assert await async_setup_component(hass, device_tracker.DOMAIN,
TEST_PLATFORM) TEST_PLATFORM)
config = device_tracker.load_config(self.yaml_devices, self.hass, config = (await device_tracker.async_load_config(yaml_devices, hass,
device.consider_home)[0] device.consider_home))[0]
assert device.dev_id == config.dev_id assert device.dev_id == config.dev_id
assert device.track == config.track assert device.track == config.track
assert device.mac == config.mac assert device.mac == config.mac
@ -112,16 +108,17 @@ class TestComponentsDeviceTracker(unittest.TestCase):
assert device.consider_home == config.consider_home assert device.consider_home == config.consider_home
assert device.icon == config.icon assert device.icon == config.icon
# pylint: disable=invalid-name # pylint: disable=invalid-name
@patch('homeassistant.components.device_tracker._LOGGER.warning') @patch('homeassistant.components.device_tracker._LOGGER.warning')
def test_track_with_duplicate_mac_dev_id(self, mock_warning): async def test_track_with_duplicate_mac_dev_id(mock_warning, hass):
"""Test adding duplicate MACs or device IDs to DeviceTracker.""" """Test adding duplicate MACs or device IDs to DeviceTracker."""
devices = [ devices = [
device_tracker.Device(self.hass, True, True, 'my_device', 'AB:01', device_tracker.Device(hass, True, True, 'my_device', 'AB:01',
'My device', None, None, False), 'My device', None, None, False),
device_tracker.Device(self.hass, True, True, 'your_device', device_tracker.Device(hass, True, True, 'your_device',
'AB:01', 'Your device', None, None, False)] 'AB:01', 'Your device', None, None, False)]
device_tracker.DeviceTracker(self.hass, False, True, {}, devices) device_tracker.DeviceTracker(hass, False, True, {}, devices)
_LOGGER.debug(mock_warning.call_args_list) _LOGGER.debug(mock_warning.call_args_list)
assert mock_warning.call_count == 1, \ assert mock_warning.call_count == 1, \
"The only warning call should be duplicates (check DEBUG)" "The only warning call should be duplicates (check DEBUG)"
@ -131,11 +128,11 @@ class TestComponentsDeviceTracker(unittest.TestCase):
mock_warning.reset_mock() mock_warning.reset_mock()
devices = [ devices = [
device_tracker.Device(self.hass, True, True, 'my_device', device_tracker.Device(hass, True, True, 'my_device',
'AB:01', 'My device', None, None, False), 'AB:01', 'My device', None, None, False),
device_tracker.Device(self.hass, True, True, 'my_device', device_tracker.Device(hass, True, True, 'my_device',
None, 'Your device', None, None, False)] None, 'Your device', None, None, False)]
device_tracker.DeviceTracker(self.hass, False, True, {}, devices) device_tracker.DeviceTracker(hass, False, True, {}, devices)
_LOGGER.debug(mock_warning.call_args_list) _LOGGER.debug(mock_warning.call_args_list)
assert mock_warning.call_count == 1, \ assert mock_warning.call_count == 1, \
@ -144,53 +141,58 @@ class TestComponentsDeviceTracker(unittest.TestCase):
assert 'Duplicate device IDs' in args[0], \ assert 'Duplicate device IDs' in args[0], \
'Duplicate device IDs warning expected' 'Duplicate device IDs warning expected'
def test_setup_without_yaml_file(self):
async def test_setup_without_yaml_file(hass):
"""Test with no YAML file.""" """Test with no YAML file."""
with assert_setup_component(1, device_tracker.DOMAIN): with assert_setup_component(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN, assert await async_setup_component(hass, device_tracker.DOMAIN,
TEST_PLATFORM) TEST_PLATFORM)
def test_gravatar(self):
async def test_gravatar(hass):
"""Test the Gravatar generation.""" """Test the Gravatar generation."""
dev_id = 'test' dev_id = 'test'
device = device_tracker.Device( device = device_tracker.Device(
self.hass, timedelta(seconds=180), True, dev_id, hass, timedelta(seconds=180), True, dev_id,
'AB:CD:EF:GH:IJ', 'Test name', gravatar='test@example.com') 'AB:CD:EF:GH:IJ', 'Test name', gravatar='test@example.com')
gravatar_url = ("https://www.gravatar.com/avatar/" gravatar_url = ("https://www.gravatar.com/avatar/"
"55502f40dc8b7c769880b10874abc9d0.jpg?s=80&d=wavatar") "55502f40dc8b7c769880b10874abc9d0.jpg?s=80&d=wavatar")
assert device.config_picture == gravatar_url assert device.config_picture == gravatar_url
def test_gravatar_and_picture(self):
async def test_gravatar_and_picture(hass):
"""Test that Gravatar overrides picture.""" """Test that Gravatar overrides picture."""
dev_id = 'test' dev_id = 'test'
device = device_tracker.Device( device = device_tracker.Device(
self.hass, timedelta(seconds=180), True, dev_id, hass, timedelta(seconds=180), True, dev_id,
'AB:CD:EF:GH:IJ', 'Test name', picture='http://test.picture', 'AB:CD:EF:GH:IJ', 'Test name', picture='http://test.picture',
gravatar='test@example.com') gravatar='test@example.com')
gravatar_url = ("https://www.gravatar.com/avatar/" gravatar_url = ("https://www.gravatar.com/avatar/"
"55502f40dc8b7c769880b10874abc9d0.jpg?s=80&d=wavatar") "55502f40dc8b7c769880b10874abc9d0.jpg?s=80&d=wavatar")
assert device.config_picture == gravatar_url assert device.config_picture == gravatar_url
@patch( @patch(
'homeassistant.components.device_tracker.DeviceTracker.see') 'homeassistant.components.device_tracker.DeviceTracker.see')
@patch( @patch(
'homeassistant.components.device_tracker.demo.setup_scanner', 'homeassistant.components.device_tracker.demo.setup_scanner',
autospec=True) autospec=True)
def test_discover_platform(self, mock_demo_setup_scanner, mock_see): async def test_discover_platform(mock_demo_setup_scanner, mock_see, hass):
"""Test discovery of device_tracker demo platform.""" """Test discovery of device_tracker demo platform."""
assert device_tracker.DOMAIN not in self.hass.config.components assert device_tracker.DOMAIN not in hass.config.components
discovery.load_platform( await discovery.async_load_platform(
self.hass, device_tracker.DOMAIN, 'demo', {'test_key': 'test_val'}, hass, device_tracker.DOMAIN, 'demo', {'test_key': 'test_val'},
{'demo': {}}) {'demo': {}})
self.hass.block_till_done() await hass.async_block_till_done()
assert device_tracker.DOMAIN in self.hass.config.components assert device_tracker.DOMAIN in hass.config.components
assert mock_demo_setup_scanner.called assert mock_demo_setup_scanner.called
assert mock_demo_setup_scanner.call_args[0] == ( assert mock_demo_setup_scanner.call_args[0] == (
self.hass, {}, mock_see, {'test_key': 'test_val'}) hass, {}, mock_see, {'test_key': 'test_val'})
def test_update_stale(self):
async def test_update_stale(hass):
"""Test stalled update.""" """Test stalled update."""
scanner = get_component(self.hass, 'device_tracker.test').SCANNER scanner = get_component(hass, 'device_tracker.test').SCANNER
scanner.reset() scanner.reset()
scanner.come_home('DEV1') scanner.come_home('DEV1')
@ -200,27 +202,28 @@ class TestComponentsDeviceTracker(unittest.TestCase):
with patch('homeassistant.components.device_tracker.dt_util.utcnow', with patch('homeassistant.components.device_tracker.dt_util.utcnow',
return_value=register_time): return_value=register_time):
with assert_setup_component(1, device_tracker.DOMAIN): with assert_setup_component(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN, { assert await async_setup_component(hass, device_tracker.DOMAIN, {
device_tracker.DOMAIN: { device_tracker.DOMAIN: {
CONF_PLATFORM: 'test', CONF_PLATFORM: 'test',
device_tracker.CONF_CONSIDER_HOME: 59, device_tracker.CONF_CONSIDER_HOME: 59,
}}) }})
self.hass.block_till_done() await hass.async_block_till_done()
assert STATE_HOME == \ assert STATE_HOME == \
self.hass.states.get('device_tracker.dev1').state hass.states.get('device_tracker.dev1').state
scanner.leave_home('DEV1') scanner.leave_home('DEV1')
with patch('homeassistant.components.device_tracker.dt_util.utcnow', with patch('homeassistant.components.device_tracker.dt_util.utcnow',
return_value=scan_time): return_value=scan_time):
fire_time_changed(self.hass, scan_time) async_fire_time_changed(hass, scan_time)
self.hass.block_till_done() await hass.async_block_till_done()
assert STATE_NOT_HOME == \ assert STATE_NOT_HOME == \
self.hass.states.get('device_tracker.dev1').state hass.states.get('device_tracker.dev1').state
def test_entity_attributes(self):
async def test_entity_attributes(hass, yaml_devices):
"""Test the entity attributes.""" """Test the entity attributes."""
dev_id = 'test_entity' dev_id = 'test_entity'
entity_id = device_tracker.ENTITY_ID_FORMAT.format(dev_id) entity_id = device_tracker.ENTITY_ID_FORMAT.format(dev_id)
@ -229,66 +232,68 @@ class TestComponentsDeviceTracker(unittest.TestCase):
icon = 'mdi:kettle' icon = 'mdi:kettle'
device = device_tracker.Device( device = device_tracker.Device(
self.hass, timedelta(seconds=180), True, dev_id, None, hass, timedelta(seconds=180), True, dev_id, None,
friendly_name, picture, hide_if_away=True, icon=icon) friendly_name, picture, hide_if_away=True, icon=icon)
device_tracker.update_config(self.yaml_devices, dev_id, device) device_tracker.update_config(yaml_devices, dev_id, device)
with assert_setup_component(1, device_tracker.DOMAIN): with assert_setup_component(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN, assert await async_setup_component(hass, device_tracker.DOMAIN,
TEST_PLATFORM) TEST_PLATFORM)
attrs = self.hass.states.get(entity_id).attributes attrs = hass.states.get(entity_id).attributes
assert friendly_name == attrs.get(ATTR_FRIENDLY_NAME) assert friendly_name == attrs.get(ATTR_FRIENDLY_NAME)
assert icon == attrs.get(ATTR_ICON) assert icon == attrs.get(ATTR_ICON)
assert picture == attrs.get(ATTR_ENTITY_PICTURE) assert picture == attrs.get(ATTR_ENTITY_PICTURE)
def test_device_hidden(self):
async def test_device_hidden(hass, yaml_devices):
"""Test hidden devices.""" """Test hidden devices."""
dev_id = 'test_entity' dev_id = 'test_entity'
entity_id = device_tracker.ENTITY_ID_FORMAT.format(dev_id) entity_id = device_tracker.ENTITY_ID_FORMAT.format(dev_id)
device = device_tracker.Device( device = device_tracker.Device(
self.hass, timedelta(seconds=180), True, dev_id, None, hass, timedelta(seconds=180), True, dev_id, None,
hide_if_away=True) hide_if_away=True)
device_tracker.update_config(self.yaml_devices, dev_id, device) device_tracker.update_config(yaml_devices, dev_id, device)
scanner = get_component(self.hass, 'device_tracker.test').SCANNER scanner = get_component(hass, 'device_tracker.test').SCANNER
scanner.reset() scanner.reset()
with assert_setup_component(1, device_tracker.DOMAIN): with assert_setup_component(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN, assert await async_setup_component(hass, device_tracker.DOMAIN,
TEST_PLATFORM) TEST_PLATFORM)
assert self.hass.states.get(entity_id) \ assert hass.states.get(entity_id).attributes.get(ATTR_HIDDEN)
.attributes.get(ATTR_HIDDEN)
def test_group_all_devices(self):
async def test_group_all_devices(hass, yaml_devices):
"""Test grouping of devices.""" """Test grouping of devices."""
dev_id = 'test_entity' dev_id = 'test_entity'
entity_id = device_tracker.ENTITY_ID_FORMAT.format(dev_id) entity_id = device_tracker.ENTITY_ID_FORMAT.format(dev_id)
device = device_tracker.Device( device = device_tracker.Device(
self.hass, timedelta(seconds=180), True, dev_id, None, hass, timedelta(seconds=180), True, dev_id, None,
hide_if_away=True) hide_if_away=True)
device_tracker.update_config(self.yaml_devices, dev_id, device) device_tracker.update_config(yaml_devices, dev_id, device)
scanner = get_component(self.hass, 'device_tracker.test').SCANNER scanner = get_component(hass, 'device_tracker.test').SCANNER
scanner.reset() scanner.reset()
with assert_setup_component(1, device_tracker.DOMAIN): with assert_setup_component(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN, assert await async_setup_component(hass, device_tracker.DOMAIN,
TEST_PLATFORM) TEST_PLATFORM)
self.hass.block_till_done() await hass.async_block_till_done()
state = self.hass.states.get(device_tracker.ENTITY_ID_ALL_DEVICES) state = hass.states.get(device_tracker.ENTITY_ID_ALL_DEVICES)
assert state is not None assert state is not None
assert STATE_NOT_HOME == state.state assert STATE_NOT_HOME == state.state
assert (entity_id,) == state.attributes.get(ATTR_ENTITY_ID) assert (entity_id,) == state.attributes.get(ATTR_ENTITY_ID)
@patch('homeassistant.components.device_tracker.DeviceTracker.async_see') @patch('homeassistant.components.device_tracker.DeviceTracker.async_see')
def test_see_service(self, mock_see): async def test_see_service(mock_see, hass):
"""Test the see service with a unicode dev_id and NO MAC.""" """Test the see service with a unicode dev_id and NO MAC."""
with assert_setup_component(1, device_tracker.DOMAIN): with assert_setup_component(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN, assert await async_setup_component(hass, device_tracker.DOMAIN,
TEST_PLATFORM) TEST_PLATFORM)
params = { params = {
'dev_id': 'some_device', 'dev_id': 'some_device',
@ -299,8 +304,8 @@ class TestComponentsDeviceTracker(unittest.TestCase):
'test': 'test' 'test': 'test'
} }
} }
device_tracker.see(self.hass, **params) common.async_see(hass, **params)
self.hass.block_till_done() await hass.async_block_till_done()
assert mock_see.call_count == 1 assert mock_see.call_count == 1
assert mock_see.call_count == 1 assert mock_see.call_count == 1
assert mock_see.call_args == call(**params) assert mock_see.call_args == call(**params)
@ -308,16 +313,17 @@ class TestComponentsDeviceTracker(unittest.TestCase):
mock_see.reset_mock() mock_see.reset_mock()
params['dev_id'] += chr(233) # e' acute accent from icloud params['dev_id'] += chr(233) # e' acute accent from icloud
device_tracker.see(self.hass, **params) common.async_see(hass, **params)
self.hass.block_till_done() await hass.async_block_till_done()
assert mock_see.call_count == 1 assert mock_see.call_count == 1
assert mock_see.call_count == 1 assert mock_see.call_count == 1
assert mock_see.call_args == call(**params) assert mock_see.call_args == call(**params)
def test_new_device_event_fired(self):
async def test_new_device_event_fired(hass):
"""Test that the device tracker will fire an event.""" """Test that the device tracker will fire an event."""
with assert_setup_component(1, device_tracker.DOMAIN): with assert_setup_component(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN, assert await async_setup_component(hass, device_tracker.DOMAIN,
TEST_PLATFORM) TEST_PLATFORM)
test_events = [] test_events = []
@ -326,12 +332,12 @@ class TestComponentsDeviceTracker(unittest.TestCase):
"""Record that our event got called.""" """Record that our event got called."""
test_events.append(event) test_events.append(event)
self.hass.bus.listen("device_tracker_new_device", listener) hass.bus.async_listen("device_tracker_new_device", listener)
device_tracker.see(self.hass, 'mac_1', host_name='hello') common.async_see(hass, 'mac_1', host_name='hello')
device_tracker.see(self.hass, 'mac_1', host_name='hello') common.async_see(hass, 'mac_1', host_name='hello')
self.hass.block_till_done() await hass.async_block_till_done()
assert len(test_events) == 1 assert len(test_events) == 1
@ -344,38 +350,41 @@ class TestComponentsDeviceTracker(unittest.TestCase):
'mac': 'MAC_1', 'mac': 'MAC_1',
} }
# pylint: disable=invalid-name # pylint: disable=invalid-name
def test_not_write_duplicate_yaml_keys(self): async def test_not_write_duplicate_yaml_keys(hass, yaml_devices):
"""Test that the device tracker will not generate invalid YAML.""" """Test that the device tracker will not generate invalid YAML."""
with assert_setup_component(1, device_tracker.DOMAIN): with assert_setup_component(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN, assert await async_setup_component(hass, device_tracker.DOMAIN,
TEST_PLATFORM) TEST_PLATFORM)
device_tracker.see(self.hass, 'mac_1', host_name='hello') common.async_see(hass, 'mac_1', host_name='hello')
device_tracker.see(self.hass, 'mac_2', host_name='hello') common.async_see(hass, 'mac_2', host_name='hello')
self.hass.block_till_done() await hass.async_block_till_done()
config = device_tracker.load_config(self.yaml_devices, self.hass, config = await device_tracker.async_load_config(yaml_devices, hass,
timedelta(seconds=0)) timedelta(seconds=0))
assert len(config) == 2 assert len(config) == 2
# pylint: disable=invalid-name # pylint: disable=invalid-name
def test_not_allow_invalid_dev_id(self): async def test_not_allow_invalid_dev_id(hass, yaml_devices):
"""Test that the device tracker will not allow invalid dev ids.""" """Test that the device tracker will not allow invalid dev ids."""
with assert_setup_component(1, device_tracker.DOMAIN): with assert_setup_component(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN, assert await async_setup_component(hass, device_tracker.DOMAIN,
TEST_PLATFORM) TEST_PLATFORM)
device_tracker.see(self.hass, dev_id='hello-world') common.async_see(hass, dev_id='hello-world')
config = device_tracker.load_config(self.yaml_devices, self.hass, config = await device_tracker.async_load_config(yaml_devices, hass,
timedelta(seconds=0)) timedelta(seconds=0))
assert len(config) == 0 assert len(config) == 0
def test_see_state(self):
async def test_see_state(hass, yaml_devices):
"""Test device tracker see records state correctly.""" """Test device tracker see records state correctly."""
assert setup_component(self.hass, device_tracker.DOMAIN, assert await async_setup_component(hass, device_tracker.DOMAIN,
TEST_PLATFORM) TEST_PLATFORM)
params = { params = {
@ -392,14 +401,14 @@ class TestComponentsDeviceTracker(unittest.TestCase):
}, },
} }
device_tracker.see(self.hass, **params) common.async_see(hass, **params)
self.hass.block_till_done() await hass.async_block_till_done()
config = device_tracker.load_config(self.yaml_devices, self.hass, config = await device_tracker.async_load_config(yaml_devices, hass,
timedelta(seconds=0)) timedelta(seconds=0))
assert len(config) == 1 assert len(config) == 1
state = self.hass.states.get('device_tracker.examplecom') state = hass.states.get('device_tracker.examplecom')
attrs = state.attributes attrs = state.attributes
assert state.state == 'Work' assert state.state == 'Work'
assert state.object_id == 'examplecom' assert state.object_id == 'examplecom'
@ -413,7 +422,8 @@ class TestComponentsDeviceTracker(unittest.TestCase):
assert attrs['source_type'] == 'gps' assert attrs['source_type'] == 'gps'
assert attrs['number'] == 1 assert attrs['number'] == 1
def test_see_passive_zone_state(self):
async def test_see_passive_zone_state(hass):
"""Test that the device tracker sets gps for passive trackers.""" """Test that the device tracker sets gps for passive trackers."""
register_time = datetime(2015, 9, 15, 23, tzinfo=dt_util.UTC) register_time = datetime(2015, 9, 15, 23, tzinfo=dt_util.UTC)
scan_time = datetime(2015, 9, 15, 23, 1, tzinfo=dt_util.UTC) scan_time = datetime(2015, 9, 15, 23, 1, tzinfo=dt_util.UTC)
@ -427,25 +437,25 @@ class TestComponentsDeviceTracker(unittest.TestCase):
'passive': False 'passive': False
} }
setup_component(self.hass, zone.DOMAIN, { await async_setup_component(hass, zone.DOMAIN, {
'zone': zone_info 'zone': zone_info
}) })
scanner = get_component(self.hass, 'device_tracker.test').SCANNER scanner = get_component(hass, 'device_tracker.test').SCANNER
scanner.reset() scanner.reset()
scanner.come_home('dev1') scanner.come_home('dev1')
with patch('homeassistant.components.device_tracker.dt_util.utcnow', with patch('homeassistant.components.device_tracker.dt_util.utcnow',
return_value=register_time): return_value=register_time):
with assert_setup_component(1, device_tracker.DOMAIN): with assert_setup_component(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN, { assert await async_setup_component(hass, device_tracker.DOMAIN, {
device_tracker.DOMAIN: { device_tracker.DOMAIN: {
CONF_PLATFORM: 'test', CONF_PLATFORM: 'test',
device_tracker.CONF_CONSIDER_HOME: 59, device_tracker.CONF_CONSIDER_HOME: 59,
}}) }})
self.hass.block_till_done() await hass.async_block_till_done()
state = self.hass.states.get('device_tracker.dev1') state = hass.states.get('device_tracker.dev1')
attrs = state.attributes attrs = state.attributes
assert STATE_HOME == state.state assert STATE_HOME == state.state
assert state.object_id == 'dev1' assert state.object_id == 'dev1'
@ -461,10 +471,10 @@ class TestComponentsDeviceTracker(unittest.TestCase):
with patch('homeassistant.components.device_tracker.dt_util.utcnow', with patch('homeassistant.components.device_tracker.dt_util.utcnow',
return_value=scan_time): return_value=scan_time):
fire_time_changed(self.hass, scan_time) async_fire_time_changed(hass, scan_time)
self.hass.block_till_done() await hass.async_block_till_done()
state = self.hass.states.get('device_tracker.dev1') state = hass.states.get('device_tracker.dev1')
attrs = state.attributes attrs = state.attributes
assert STATE_NOT_HOME == state.state assert STATE_NOT_HOME == state.state
assert state.object_id == 'dev1' assert state.object_id == 'dev1'
@ -476,27 +486,27 @@ class TestComponentsDeviceTracker(unittest.TestCase):
assert attrs.get('source_type') == \ assert attrs.get('source_type') == \
device_tracker.SOURCE_TYPE_ROUTER device_tracker.SOURCE_TYPE_ROUTER
@patch('homeassistant.components.device_tracker._LOGGER.warning') @patch('homeassistant.components.device_tracker._LOGGER.warning')
def test_see_failures(self, mock_warning): async def test_see_failures(mock_warning, hass, yaml_devices):
"""Test that the device tracker see failures.""" """Test that the device tracker see failures."""
tracker = device_tracker.DeviceTracker( tracker = device_tracker.DeviceTracker(
self.hass, timedelta(seconds=60), 0, {}, []) hass, timedelta(seconds=60), 0, {}, [])
# MAC is not a string (but added) # MAC is not a string (but added)
tracker.see(mac=567, host_name="Number MAC") await tracker.async_see(mac=567, host_name="Number MAC")
# No device id or MAC(not added) # No device id or MAC(not added)
with pytest.raises(HomeAssistantError): with pytest.raises(HomeAssistantError):
run_coroutine_threadsafe( await tracker.async_see()
tracker.async_see(), self.hass.loop).result()
assert mock_warning.call_count == 0 assert mock_warning.call_count == 0
# Ignore gps on invalid GPS (both added & warnings) # Ignore gps on invalid GPS (both added & warnings)
tracker.see(mac='mac_1_bad_gps', gps=1) await tracker.async_see(mac='mac_1_bad_gps', gps=1)
tracker.see(mac='mac_2_bad_gps', gps=[1]) await tracker.async_see(mac='mac_2_bad_gps', gps=[1])
tracker.see(mac='mac_3_bad_gps', gps='gps') await tracker.async_see(mac='mac_3_bad_gps', gps='gps')
self.hass.block_till_done() await hass.async_block_till_done()
config = device_tracker.load_config(self.yaml_devices, self.hass, config = await device_tracker.async_load_config(yaml_devices, hass,
timedelta(seconds=0)) timedelta(seconds=0))
assert mock_warning.call_count == 3 assert mock_warning.call_count == 3