Skip to content
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

Device tracker component & platform validation. No more home_range. #2908

Merged
merged 8 commits into from
Aug 30, 2016
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Coverage
  • Loading branch information
kellerza committed Aug 29, 2016
commit b7ad6b3c3c333359ed28424d8e88c8b157ad64e6
22 changes: 12 additions & 10 deletions homeassistant/components/device_tracker/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import os
import threading
import voluptuous as vol
from typing import Sequence

from homeassistant.bootstrap import (prepare_setup_platform,
log_exception)
Expand All @@ -23,6 +24,7 @@
import homeassistant.helpers.config_validation as cv
import homeassistant.util as util
import homeassistant.util.dt as dt_util
from homeassistant.core import HomeAssistant

from homeassistant.helpers.event import track_utc_time_change
from homeassistant.const import (
Expand Down Expand Up @@ -174,7 +176,8 @@ def see_service(call):
class DeviceTracker(object):
"""Representation of a device tracker."""

def __init__(self, hass, consider_home, track_new, devices):
def __init__(self, hass: HomeAssistant, consider_home: timedelta,
track_new: bool, devices: Sequence):
"""Initialize a device tracker."""
self.hass = hass
self.devices = {dev.dev_id: dev for dev in devices}
Expand All @@ -195,14 +198,15 @@ def __init__(self, hass, consider_home, track_new, devices):

self.group = None

def see(self, mac=None, dev_id=None, host_name=None, location_name=None,
gps=None, gps_accuracy=None, battery=None):
def see(self, mac: str=None, dev_id=None, host_name=None,
location_name=None, gps=None, gps_accuracy=None,
battery=None):
"""Notify the device tracker that you see a device."""
with self.lock:
if mac is None and dev_id is None:
raise HomeAssistantError('Neither mac or device id passed in')
elif mac is not None:
mac = mac.upper()
mac = str(mac).upper()
device = self.mac_to_dev.get(mac)
if not device:
dev_id = util.slugify(host_name or '') or util.slugify(mac)
Expand Down Expand Up @@ -337,15 +341,13 @@ def seen(self, host_name=None, location_name=None, gps=None,
self.location_name = location_name
self.gps_accuracy = gps_accuracy or 0
self.battery = battery
if gps is None:
self.gps = None
else:
self.gps = None
if gps is not None:
try:
self.gps = tuple(float(val) for val in gps)
except ValueError:
self.gps = float(gps[0]), float(gps[1])
except (ValueError, TypeError, IndexError):
_LOGGER.warning('Could not parse gps value for %s: %s',
self.dev_id, gps)
self.gps = None
self.update()

def stale(self, now=None):
Expand Down
66 changes: 42 additions & 24 deletions tests/components/device_tracker/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
ATTR_ENTITY_ID, ATTR_ENTITY_PICTURE, ATTR_FRIENDLY_NAME, ATTR_HIDDEN,
STATE_HOME, STATE_NOT_HOME, CONF_PLATFORM)
import homeassistant.components.device_tracker as device_tracker
from homeassistant.exceptions import HomeAssistantError

from tests.common import (
get_test_home_assistant, fire_time_changed, fire_service_discovered)
Expand All @@ -21,7 +22,8 @@

class TestComponentsDeviceTracker(unittest.TestCase):
"""Test the Device tracker."""
hass = None
hass = None # HomeAssistant
yaml_devices = None # type: str

def setup_method(self, _):
"""Setup things to be run when tests are started."""
Expand Down Expand Up @@ -80,7 +82,8 @@ def test_reading_yaml_config(self):
self.assertEqual(device.consider_home, config.consider_home)

@patch('homeassistant.components.device_tracker._LOGGER.warning')
def test_track_with_duplicate_mac_dev_id(self, mock_warning):
def test_track_with_duplicate_mac_dev_id(self, mock_warning): \
# pylint: disable=invalid-name
"""Test adding duplicate MACs or device IDs to DeviceTracker."""

devices = [
Expand Down Expand Up @@ -250,38 +253,29 @@ def test_group_all_devices(self):

@patch('homeassistant.components.device_tracker.DeviceTracker.see')
def test_see_service(self, mock_see):
"""Test the see service."""
self.assertTrue(device_tracker.setup(self.hass, TEST_PLATFORM))
mac = 'AB:CD:EF:GH'
dev_id = 'some_device'
host_name = 'example.com'
location_name = 'Work'
gps = [.3, .8]

device_tracker.see(self.hass, mac, dev_id, host_name, location_name,
gps)

self.hass.pool.block_till_done()

mock_see.assert_called_once_with(
mac=mac, dev_id=dev_id, host_name=host_name,
location_name=location_name, gps=gps)

@patch('homeassistant.components.device_tracker.DeviceTracker.see')
def test_see_service_unicode_dev_id(self, mock_see):
"""Test the see service with a unicode dev_id and NO MAC."""
self.assertTrue(device_tracker.setup(self.hass, TEST_PLATFORM))
params = {
'dev_id': chr(233), # e' acute accent from icloud
'dev_id': 'some_device',
'host_name': 'example.com',
'location_name': 'Work',
'gps': [.3, .8]
}
device_tracker.see(self.hass, **params)
self.hass.pool.block_till_done()
assert mock_see.call_count == 1
mock_see.assert_called_once_with(**params)

def test_not_write_duplicate_yaml_keys(self):
mock_see.reset_mock()
params['dev_id'] += chr(233) # e' acute accent from icloud

device_tracker.see(self.hass, **params)
self.hass.pool.block_till_done()
assert mock_see.call_count == 1
mock_see.assert_called_once_with(**params)

def test_not_write_duplicate_yaml_keys(self): \
# pylint: disable=invalid-name
"""Test that the device tracker will not generate invalid YAML."""
self.assertTrue(device_tracker.setup(self.hass, TEST_PLATFORM))

Expand All @@ -294,7 +288,7 @@ def test_not_write_duplicate_yaml_keys(self):
timedelta(seconds=0))
assert len(config) == 2

def test_not_allow_invalid_dev_id(self):
def test_not_allow_invalid_dev_id(self): # pylint: disable=invalid-name
"""Test that the device tracker will not allow invalid dev ids."""
self.assertTrue(device_tracker.setup(self.hass, TEST_PLATFORM))

Expand All @@ -303,3 +297,27 @@ def test_not_allow_invalid_dev_id(self):
config = device_tracker.load_config(self.yaml_devices, self.hass,
timedelta(seconds=0))
assert len(config) == 0

@patch('homeassistant.components.device_tracker._LOGGER.warning')
def test_see_failures(self, mock_warning):
"""Test that the device tracker see failures."""
tracker = device_tracker.DeviceTracker(
self.hass, timedelta(seconds=60), 0, [])

# MAC is not a string (but added)
tracker.see(mac=567, host_name="Number MAC")

# No device id or MAC(not added)
with self.assertRaises(HomeAssistantError):
tracker.see()
assert mock_warning.call_count == 0

# Ignore gps on invalid GPS (both added & warnings)
tracker.see(mac='mac_1_bad_gps', gps=1)
tracker.see(mac='mac_2_bad_gps', gps=[1])
tracker.see(mac='mac_3_bad_gps', gps='gps')
config = device_tracker.load_config(self.yaml_devices, self.hass,
timedelta(seconds=0))
assert mock_warning.call_count == 3

assert len(config) == 4