Merge remote-tracking branch 'balloob/dev' into automation-decorator

# Conflicts:
#	homeassistant/helpers/service.py
#	tests/helpers/test_service.py
This commit is contained in:
Ryan Kraus 2016-01-24 22:51:00 -05:00
commit 60dd2d441d
28 changed files with 374 additions and 191 deletions

View File

@ -228,7 +228,7 @@ def from_config_file(config_path, hass=None, verbose=False, daemon=False,
enable_logging(hass, verbose, daemon, log_rotate_days)
config_dict = config_util.load_config_file(config_path)
config_dict = config_util.load_yaml_config_file(config_path)
return from_config_dict(config_dict, hass, enable_log=False,
skip_pip=skip_pip)

View File

@ -16,8 +16,8 @@ import itertools as it
import logging
import homeassistant.core as ha
import homeassistant.util as util
from homeassistant.helpers import extract_entity_ids
from homeassistant.helpers.entity import split_entity_id
from homeassistant.helpers.service import extract_entity_ids
from homeassistant.loader import get_component
from homeassistant.const import (
ATTR_ENTITY_ID, SERVICE_TURN_ON, SERVICE_TURN_OFF, SERVICE_TOGGLE)
@ -36,7 +36,7 @@ def is_on(hass, entity_id=None):
entity_ids = hass.states.entity_ids()
for entity_id in entity_ids:
domain = util.split_entity_id(entity_id)[0]
domain = split_entity_id(entity_id)[0]
module = get_component(domain)
@ -92,7 +92,7 @@ def setup(hass, config):
# Group entity_ids by domain. groupby requires sorted data.
by_domain = it.groupby(sorted(entity_ids),
lambda item: util.split_entity_id(item)[0])
lambda item: split_entity_id(item)[0])
for domain, ent_ids in by_domain:
# We want to block for all calls and only return when all calls

View File

@ -11,7 +11,7 @@ the user has submitted configuration information.
"""
import logging
from homeassistant.helpers import generate_entity_id
from homeassistant.helpers.entity import generate_entity_id
from homeassistant.const import EVENT_TIME_CHANGED
DOMAIN = "configurator"

View File

@ -19,7 +19,7 @@ from homeassistant.components.device_tracker import DOMAIN
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['pynetgear==0.3.1']
REQUIREMENTS = ['pynetgear==0.3.2']
def get_scanner(hass, config):

View File

@ -7,10 +7,9 @@ For more details about this component, please refer to the documentation at
https://home-assistant.io/components/group/
"""
import homeassistant.core as ha
from homeassistant.helpers import generate_entity_id
from homeassistant.helpers.event import track_state_change
from homeassistant.helpers.entity import Entity
import homeassistant.util as util
from homeassistant.helpers.entity import (
Entity, split_entity_id, generate_entity_id)
from homeassistant.const import (
ATTR_ENTITY_ID, STATE_ON, STATE_OFF,
STATE_HOME, STATE_NOT_HOME, STATE_OPEN, STATE_CLOSED,
@ -62,7 +61,7 @@ def expand_entity_ids(hass, entity_ids):
try:
# If entity_id points at a group, expand it
domain, _ = util.split_entity_id(entity_id)
domain, _ = split_entity_id(entity_id)
if domain == DOMAIN:
found_ids.extend(
@ -75,7 +74,7 @@ def expand_entity_ids(hass, entity_ids):
found_ids.append(entity_id)
except AttributeError:
# Raised by util.split_entity_id if entity_id is not a string
# Raised by split_entity_id if entity_id is not a string
pass
return found_ids

View File

@ -9,7 +9,7 @@ https://home-assistant.io/components/light.rfxtrx/
import logging
import homeassistant.components.rfxtrx as rfxtrx
from homeassistant.components.light import Light
from homeassistant.components.light import Light, ATTR_BRIGHTNESS
from homeassistant.util import slugify
from homeassistant.const import ATTR_ENTITY_ID
@ -112,6 +112,7 @@ class RfxtrxLight(Light):
self._event = event
self._state = datas[ATTR_STATE]
self._should_fire_event = datas[ATTR_FIREEVENT]
self._brightness = 0
@property
def should_poll(self):
@ -133,12 +134,25 @@ class RfxtrxLight(Light):
""" True if light is on. """
return self._state
@property
def brightness(self):
""" Brightness of this light between 0..255. """
return self._brightness
def turn_on(self, **kwargs):
""" Turn the light on. """
brightness = kwargs.get(ATTR_BRIGHTNESS)
if brightness is None:
self._brightness = 100
else:
self._brightness = ((brightness + 4) * 100 // 255 - 1)
if hasattr(self, '_event') and self._event:
self._event.device.send_on(rfxtrx.RFXOBJECT.transport)
self._event.device.send_dim(rfxtrx.RFXOBJECT.transport,
self._brightness)
self._brightness = (self._brightness * 255 // 100)
self._state = True
self.update_ha_state()
@ -148,5 +162,6 @@ class RfxtrxLight(Light):
if hasattr(self, '_event') and self._event:
self._event.device.send_off(rfxtrx.RFXOBJECT.transport)
self._brightness = 0
self._state = False
self.update_ha_state()

View File

@ -14,10 +14,9 @@ from homeassistant.core import State, DOMAIN as HA_DOMAIN
from homeassistant.const import (
EVENT_STATE_CHANGED, STATE_NOT_HOME, STATE_ON, STATE_OFF,
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP, HTTP_BAD_REQUEST)
from homeassistant import util
import homeassistant.util.dt as dt_util
from homeassistant.components import recorder, sun
from homeassistant.helpers.entity import split_entity_id
DOMAIN = "logbook"
DEPENDENCIES = ['recorder', 'http']
@ -209,7 +208,7 @@ def humanify(events):
entity_id = event.data.get(ATTR_ENTITY_ID)
if domain is None and entity_id is not None:
try:
domain = util.split_entity_id(str(entity_id))[0]
domain = split_entity_id(str(entity_id))[0]
except IndexError:
pass

View File

@ -20,7 +20,7 @@ from homeassistant.components.media_player import (
SUPPORT_PREVIOUS_TRACK, SUPPORT_NEXT_TRACK,
MEDIA_TYPE_MUSIC, MEDIA_TYPE_TVSHOW, MEDIA_TYPE_VIDEO)
REQUIREMENTS = ['pychromecast==0.6.14']
REQUIREMENTS = ['pychromecast==0.7.1']
CONF_IGNORE_CEC = 'ignore_cec'
CAST_SPLASH = 'https://home-assistant.io/images/cast/splash.png'
SUPPORT_CAST = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \

View File

@ -112,7 +112,7 @@ def setup_plexserver(host, token, hass, add_devices_callback):
{host: {'token': token}}):
_LOGGER.error('failed to save config file')
_LOGGER.info('Connected to: htts://%s', host)
_LOGGER.info('Connected to: http://%s', host)
plex_clients = {}
plex_sessions = {}

View File

@ -202,9 +202,12 @@ class SqueezeBoxDevice(MediaPlayerDevice):
""" Image url of current playing media. """
if 'artwork_url' in self._status:
media_url = self._status['artwork_url']
else:
elif 'id' in self._status:
media_url = ('/music/{track_id}/cover.jpg').format(
track_id=self._status["id"])
track_id=self._status['id'])
else:
media_url = ('/music/current/cover.jpg?player={player}').format(
player=self._id)
base_url = 'http://{server}:{port}/'.format(
server=self._lms.host,

View File

@ -21,37 +21,38 @@ def get_service(hass, config):
""" Get the mail notification service. """
if not validate_config({DOMAIN: config},
{DOMAIN: ['server', 'port', 'sender', 'username',
'password', 'recipient']},
{DOMAIN: ['recipient']},
_LOGGER):
return None
smtp_server = config['server']
port = int(config['port'])
username = config['username']
password = config['password']
starttls = int(config['starttls'])
smtp_server = config.get('server', 'localhost')
port = int(config.get('port', '25'))
username = config.get('username', None)
password = config.get('password', None)
starttls = int(config.get('starttls', 0))
debug = config.get('debug', 0)
server = None
try:
server = smtplib.SMTP(smtp_server, port)
server = smtplib.SMTP(smtp_server, port, timeout=5)
server.set_debuglevel(debug)
server.ehlo()
if starttls == 1:
server.starttls()
server.ehlo()
if username and password:
try:
server.login(username, password)
try:
server.login(username, password)
except (smtplib.SMTPException, smtplib.SMTPSenderRefused):
_LOGGER.exception("Please check your settings.")
return None
except (smtplib.SMTPException, smtplib.SMTPSenderRefused):
_LOGGER.exception("Please check your settings.")
return None
except smtplib.socket.gaierror:
_LOGGER.exception(
"SMTP server not found. "
"Please check the IP address or hostname of your SMTP server.")
"SMTP server not found (%s:%s). "
"Please check the IP address or hostname of your SMTP server.",
smtp_server, port)
return None
@ -68,7 +69,7 @@ def get_service(hass, config):
return MailNotificationService(
smtp_server, port, config['sender'], starttls, username, password,
config['recipient'])
config['recipient'], debug)
# pylint: disable=too-few-public-methods, too-many-instance-attributes
@ -77,7 +78,7 @@ class MailNotificationService(BaseNotificationService):
# pylint: disable=too-many-arguments
def __init__(self, server, port, sender, starttls, username,
password, recipient):
password, recipient, debug):
self._server = server
self._port = port
self._sender = sender
@ -85,24 +86,26 @@ class MailNotificationService(BaseNotificationService):
self.username = username
self.password = password
self.recipient = recipient
self.debug = debug
self.tries = 2
self.mail = None
self.connect()
def connect(self):
""" Connect/Authenticate to SMTP Server """
self.mail = smtplib.SMTP(self._server, self._port)
self.mail.ehlo_or_helo_if_needed()
mail = smtplib.SMTP(self._server, self._port, timeout=5)
mail.set_debuglevel(self.debug)
mail.ehlo_or_helo_if_needed()
if self.starttls == 1:
self.mail.starttls()
self.mail.ehlo()
self.mail.login(self.username, self.password)
mail.starttls()
mail.ehlo()
if self.username and self.password:
mail.login(self.username, self.password)
return mail
def send_message(self, message="", **kwargs):
""" Send a message to a user. """
mail = self.connect()
subject = kwargs.get(ATTR_TITLE)
msg = MIMEText(message)
@ -113,10 +116,13 @@ class MailNotificationService(BaseNotificationService):
for _ in range(self.tries):
try:
self.mail.sendmail(self._sender, self.recipient,
msg.as_string())
mail.sendmail(self._sender, self.recipient,
msg.as_string())
break
except smtplib.SMTPException:
_LOGGER.warning('SMTPException sending mail: '
'retrying connection')
self.connect()
mail.quit()
mail = self.connect()
mail.quit()

View File

@ -13,10 +13,10 @@ from itertools import islice
import threading
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.helpers.entity import ToggleEntity, split_entity_id
from homeassistant.helpers.event import track_point_in_utc_time
from homeassistant.helpers.service import call_from_config
from homeassistant.util import slugify, split_entity_id
from homeassistant.util import slugify
import homeassistant.util.dt as date_util
from homeassistant.const import (
ATTR_ENTITY_ID, EVENT_TIME_CHANGED, STATE_ON, SERVICE_TURN_ON,

View File

@ -10,8 +10,8 @@ import logging
from homeassistant.const import (
ATTR_HIDDEN, ATTR_ICON, ATTR_LATITUDE, ATTR_LONGITUDE, CONF_NAME)
from homeassistant.helpers import extract_domain_configs, generate_entity_id
from homeassistant.helpers.entity import Entity
from homeassistant.helpers import extract_domain_configs
from homeassistant.helpers.entity import Entity, generate_entity_id
from homeassistant.util.location import distance
DOMAIN = "zone"
@ -24,6 +24,9 @@ DEFAULT_NAME = 'Unnamed zone'
ATTR_RADIUS = 'radius'
DEFAULT_RADIUS = 100
ATTR_PASSIVE = 'passive'
DEFAULT_PASSIVE = False
ICON_HOME = 'mdi:home'
@ -37,6 +40,9 @@ def active_zone(hass, latitude, longitude, radius=0):
closest = None
for zone in zones:
if zone.attributes.get(ATTR_PASSIVE):
continue
zone_dist = distance(
latitude, longitude,
zone.attributes[ATTR_LATITUDE], zone.attributes[ATTR_LONGITUDE])
@ -78,13 +84,14 @@ def setup(hass, config):
longitude = entry.get(ATTR_LONGITUDE)
radius = entry.get(ATTR_RADIUS, DEFAULT_RADIUS)
icon = entry.get(ATTR_ICON)
passive = entry.get(ATTR_PASSIVE, DEFAULT_PASSIVE)
if None in (latitude, longitude):
logging.getLogger(__name__).error(
'Each zone needs a latitude and longitude.')
continue
zone = Zone(hass, name, latitude, longitude, radius, icon)
zone = Zone(hass, name, latitude, longitude, radius, icon, passive)
zone.entity_id = generate_entity_id(ENTITY_ID_FORMAT, name,
entities)
zone.update_ha_state()
@ -92,7 +99,7 @@ def setup(hass, config):
if ENTITY_ID_HOME not in entities:
zone = Zone(hass, hass.config.location_name, hass.config.latitude,
hass.config.longitude, DEFAULT_RADIUS, ICON_HOME)
hass.config.longitude, DEFAULT_RADIUS, ICON_HOME, False)
zone.entity_id = ENTITY_ID_HOME
zone.update_ha_state()
@ -101,17 +108,15 @@ def setup(hass, config):
class Zone(Entity):
""" Represents a Zone in Home Assistant. """
# pylint: disable=too-many-arguments
def __init__(self, hass, name, latitude, longitude, radius, icon):
# pylint: disable=too-many-arguments, too-many-instance-attributes
def __init__(self, hass, name, latitude, longitude, radius, icon, passive):
self.hass = hass
self._name = name
self.latitude = latitude
self.longitude = longitude
self.radius = radius
self._latitude = latitude
self._longitude = longitude
self._radius = radius
self._icon = icon
def should_poll(self):
return False
self._passive = passive
@property
def name(self):
@ -128,9 +133,12 @@ class Zone(Entity):
@property
def state_attributes(self):
return {
data = {
ATTR_HIDDEN: True,
ATTR_LATITUDE: self.latitude,
ATTR_LONGITUDE: self.longitude,
ATTR_RADIUS: self.radius,
ATTR_LATITUDE: self._latitude,
ATTR_LONGITUDE: self._longitude,
ATTR_RADIUS: self._radius,
}
if self._passive:
data[ATTR_PASSIVE] = self._passive
return data

View File

@ -12,6 +12,7 @@ from homeassistant.const import (
CONF_LATITUDE, CONF_LONGITUDE, CONF_TEMPERATURE_UNIT, CONF_NAME,
CONF_TIME_ZONE)
import homeassistant.util.location as loc_util
from homeassistant.util.yaml import load_yaml
_LOGGER = logging.getLogger(__name__)
@ -113,40 +114,9 @@ def find_config_file(config_dir):
return config_path if os.path.isfile(config_path) else None
def load_config_file(config_path):
""" Loads given config file. """
return load_yaml_config_file(config_path)
def load_yaml_config_file(config_path):
""" Parse a YAML configuration file. """
import yaml
def parse(fname):
""" Parse a YAML file. """
try:
with open(fname, encoding='utf-8') as conf_file:
# If configuration file is empty YAML returns None
# We convert that to an empty dict
return yaml.load(conf_file) or {}
except yaml.YAMLError:
error = 'Error reading YAML configuration file {}'.format(fname)
_LOGGER.exception(error)
raise HomeAssistantError(error)
def yaml_include(loader, node):
"""
Loads another YAML file and embeds it using the !include tag.
Example:
device_tracker: !include device_tracker.yaml
"""
fname = os.path.join(os.path.dirname(loader.name), node.value)
return parse(fname)
yaml.add_constructor('!include', yaml_include)
conf_dict = parse(config_path)
conf_dict = load_yaml(config_path)
if not isinstance(conf_dict, dict):
_LOGGER.error(

View File

@ -11,7 +11,6 @@ import logging
import signal
import threading
import enum
import re
import functools as ft
from collections import namedtuple
@ -26,6 +25,7 @@ from homeassistant.exceptions import (
import homeassistant.util as util
import homeassistant.util.dt as dt_util
import homeassistant.util.location as location
from homeassistant.helpers.entity import valid_entity_id, split_entity_id
import homeassistant.helpers.temperature as temp_helper
from homeassistant.config import get_default_config_dir
@ -42,9 +42,6 @@ SERVICE_CALL_LIMIT = 10 # seconds
# will be added for each component that polls devices.
MIN_WORKER_THREAD = 2
# Pattern for validating entity IDs (format: <domain>.<entity>)
ENTITY_ID_PATTERN = re.compile(r"^(?P<domain>\w+)\.(?P<entity>\w+)$")
_LOGGER = logging.getLogger(__name__)
# Temporary to support deprecated methods
@ -339,7 +336,7 @@ class State(object):
def __init__(self, entity_id, state, attributes=None, last_changed=None,
last_updated=None):
"""Initialize a new state."""
if not ENTITY_ID_PATTERN.match(entity_id):
if not valid_entity_id(entity_id):
raise InvalidEntityFormatError((
"Invalid entity id encountered: {}. "
"Format should be <domain>.<object_id>").format(entity_id))
@ -360,12 +357,12 @@ class State(object):
@property
def domain(self):
"""Domain of this state."""
return util.split_entity_id(self.entity_id)[0]
return split_entity_id(self.entity_id)[0]
@property
def object_id(self):
"""Object id of this state."""
return util.split_entity_id(self.entity_id)[1]
return split_entity_id(self.entity_id)[1]
@property
def name(self):

View File

@ -3,42 +3,7 @@ Helper methods for components within Home Assistant.
"""
import re
from homeassistant.loader import get_component
from homeassistant.const import (
ATTR_ENTITY_ID, CONF_PLATFORM, DEVICE_DEFAULT_NAME)
from homeassistant.util import ensure_unique_string, slugify
def generate_entity_id(entity_id_format, name, current_ids=None, hass=None):
""" Generate a unique entity ID based on given entity IDs or used ids. """
name = name.lower() or DEVICE_DEFAULT_NAME.lower()
if current_ids is None:
if hass is None:
raise RuntimeError("Missing required parameter currentids or hass")
current_ids = hass.states.entity_ids()
return ensure_unique_string(
entity_id_format.format(slugify(name.lower())), current_ids)
def extract_entity_ids(hass, service):
"""
Helper method to extract a list of entity ids from a service call.
Will convert group entity ids to the entity ids it represents.
"""
if not (service.data and ATTR_ENTITY_ID in service.data):
return []
group = get_component('group')
# Entity ID attr can be a list or a string
service_ent_id = service.data[ATTR_ENTITY_ID]
if isinstance(service_ent_id, str):
return group.expand_entity_ids(hass, [service_ent_id])
return [ent_id for ent_id in group.expand_entity_ids(hass, service_ent_id)]
from homeassistant.const import CONF_PLATFORM
def validate_config(config, items, logger):

View File

@ -6,8 +6,10 @@ Provides ABC for entities in HA.
"""
from collections import defaultdict
import re
from homeassistant.exceptions import NoEntitySpecifiedError
from homeassistant.util import ensure_unique_string, slugify
from homeassistant.const import (
ATTR_FRIENDLY_NAME, ATTR_HIDDEN, ATTR_UNIT_OF_MEASUREMENT, ATTR_ICON,
@ -17,6 +19,32 @@ from homeassistant.const import (
# Dict mapping entity_id to a boolean that overwrites the hidden property
_OVERWRITE = defaultdict(dict)
# Pattern for validating entity IDs (format: <domain>.<entity>)
ENTITY_ID_PATTERN = re.compile(r"^(\w+)\.(\w+)$")
def generate_entity_id(entity_id_format, name, current_ids=None, hass=None):
""" Generate a unique entity ID based on given entity IDs or used ids. """
name = name.lower() or DEVICE_DEFAULT_NAME.lower()
if current_ids is None:
if hass is None:
raise RuntimeError("Missing required parameter currentids or hass")
current_ids = hass.states.entity_ids()
return ensure_unique_string(
entity_id_format.format(slugify(name.lower())), current_ids)
def split_entity_id(entity_id):
""" Splits a state entity_id into domain, object_id. """
return entity_id.split(".", 1)
def valid_entity_id(entity_id):
"""Test if an entity ID is a valid format."""
return ENTITY_ID_PATTERN.match(entity_id) is not None
class Entity(object):
""" ABC for Home Assistant entities. """

View File

@ -7,9 +7,10 @@ Provides helpers for components that manage entities.
from threading import Lock
from homeassistant.bootstrap import prepare_setup_platform
from homeassistant.helpers import (
generate_entity_id, config_per_platform, extract_entity_ids)
from homeassistant.helpers import config_per_platform
from homeassistant.helpers.entity import generate_entity_id
from homeassistant.helpers.event import track_utc_time_change
from homeassistant.helpers.service import extract_entity_ids
from homeassistant.components import group, discovery
from homeassistant.const import ATTR_ENTITY_ID

View File

@ -2,8 +2,9 @@
import functools
import logging
from homeassistant.util import split_entity_id
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.helpers.entity import split_entity_id
from homeassistant.loader import get_component
HASS = None
@ -61,3 +62,22 @@ def call_from_config(hass, config, blocking=False):
service_data[ATTR_ENTITY_ID] = entity_id
hass.services.call(domain, service_name, service_data, blocking)
def extract_entity_ids(hass, service):
"""
Helper method to extract a list of entity ids from a service call.
Will convert group entity ids to the entity ids it represents.
"""
if not (service.data and ATTR_ENTITY_ID in service.data):
return []
group = get_component('group')
# Entity ID attr can be a list or a string
service_ent_id = service.data[ATTR_ENTITY_ID]
if isinstance(service_ent_id, str):
return group.expand_entity_ids(hass, [service_ent_id])
return [ent_id for ent_id in group.expand_entity_ids(hass, service_ent_id)]

View File

@ -41,11 +41,6 @@ def slugify(text):
return RE_SLUGIFY.sub("", text)
def split_entity_id(entity_id):
""" Splits a state entity_id into domain, object_id. """
return entity_id.split(".", 1)
def repr_helper(inp):
""" Helps creating a more readable string representation of objects. """
if isinstance(inp, dict):

View File

@ -0,0 +1,50 @@
"""
YAML utility functions.
"""
from collections import OrderedDict
import logging
import os
import yaml
from homeassistant.exceptions import HomeAssistantError
_LOGGER = logging.getLogger(__name__)
def load_yaml(fname):
"""Load a YAML file."""
try:
with open(fname, encoding='utf-8') as conf_file:
# If configuration file is empty YAML returns None
# We convert that to an empty dict
return yaml.load(conf_file) or {}
except yaml.YAMLError:
error = 'Error reading YAML configuration file {}'.format(fname)
_LOGGER.exception(error)
raise HomeAssistantError(error)
def _include_yaml(loader, node):
"""
Loads another YAML file and embeds it using the !include tag.
Example:
device_tracker: !include device_tracker.yaml
"""
fname = os.path.join(os.path.dirname(loader.name), node.value)
return load_yaml(fname)
def _ordered_dict(loader, node):
"""
Loads YAML mappings into an ordered dict to preserve key order.
"""
loader.flatten_mapping(node)
return OrderedDict(loader.construct_pairs(node))
yaml.add_constructor('!include', _include_yaml)
yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
_ordered_dict)

View File

@ -19,7 +19,7 @@ fuzzywuzzy==0.8.0
pyicloud==0.7.2
# homeassistant.components.device_tracker.netgear
pynetgear==0.3.1
pynetgear==0.3.2
# homeassistant.components.device_tracker.nmap_tracker
python-nmap==0.4.3
@ -75,7 +75,7 @@ pyvera==0.2.7
python-wink==0.4.2
# homeassistant.components.media_player.cast
pychromecast==0.6.14
pychromecast==0.7.1
# homeassistant.components.media_player.kodi
jsonrpc-requests==0.1

View File

@ -0,0 +1,126 @@
"""
tests.components.automation.test_location
±±±~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tests location automation.
"""
import unittest
from homeassistant.components import zone
from tests.common import get_test_home_assistant
class TestAutomationZone(unittest.TestCase):
""" Test the event automation. """
def setUp(self): # pylint: disable=invalid-name
self.hass = get_test_home_assistant()
def tearDown(self): # pylint: disable=invalid-name
""" Stop down stuff we started. """
self.hass.stop()
def test_setup(self):
info = {
'name': 'Test Zone',
'latitude': 32.880837,
'longitude': -117.237561,
'radius': 250,
'passive': True
}
assert zone.setup(self.hass, {
'zone': info
})
state = self.hass.states.get('zone.test_zone')
assert info['name'] == state.name
assert info['latitude'] == state.attributes['latitude']
assert info['longitude'] == state.attributes['longitude']
assert info['radius'] == state.attributes['radius']
assert info['passive'] == state.attributes['passive']
def test_active_zone_skips_passive_zones(self):
assert zone.setup(self.hass, {
'zone': [
{
'name': 'Passive Zone',
'latitude': 32.880600,
'longitude': -117.237561,
'radius': 250,
'passive': True
},
]
})
active = zone.active_zone(self.hass, 32.880600, -117.237561)
assert active is None
assert zone.setup(self.hass, {
'zone': [
{
'name': 'Active Zone',
'latitude': 32.880800,
'longitude': -117.237561,
'radius': 500,
},
]
})
active = zone.active_zone(self.hass, 32.880700, -117.237561)
assert 'zone.active_zone' == active.entity_id
def test_active_zone_prefers_smaller_zone_if_same_distance(self):
latitude = 32.880600
longitude = -117.237561
assert zone.setup(self.hass, {
'zone': [
{
'name': 'Small Zone',
'latitude': latitude,
'longitude': longitude,
'radius': 250,
},
{
'name': 'Big Zone',
'latitude': latitude,
'longitude': longitude,
'radius': 500,
},
]
})
active = zone.active_zone(self.hass, latitude, longitude)
assert 'zone.small_zone' == active.entity_id
assert zone.setup(self.hass, {
'zone': [
{
'name': 'Smallest Zone',
'latitude': latitude,
'longitude': longitude,
'radius': 50,
},
]
})
active = zone.active_zone(self.hass, latitude, longitude)
assert 'zone.smallest_zone' == active.entity_id
def test_in_zone_works_for_passive_zones(self):
latitude = 32.880600
longitude = -117.237561
assert zone.setup(self.hass, {
'zone': [
{
'name': 'Passive Zone',
'latitude': latitude,
'longitude': longitude,
'radius': 250,
'passive': True
},
]
})
assert zone.in_zone(self.hass.states.get('zone.passive_zone'),
latitude, longitude)

View File

@ -42,3 +42,8 @@ class TestHelpersEntity(unittest.TestCase):
state = self.hass.states.get(self.entity.entity_id)
self.assertTrue(state.attributes.get(ATTR_HIDDEN))
def test_split_entity_id(self):
""" Test split_entity_id. """
self.assertEqual(['domain', 'object_id'],
entity.split_entity_id('domain.object_id'))

View File

@ -7,45 +7,22 @@ Tests component helpers.
# pylint: disable=protected-access,too-many-public-methods
import unittest
import homeassistant.core as ha
from homeassistant import loader, helpers
from homeassistant.const import STATE_ON, STATE_OFF, ATTR_ENTITY_ID
from homeassistant import helpers
from tests.common import get_test_home_assistant
class TestComponentsCore(unittest.TestCase):
""" Tests homeassistant.components module. """
class TestHelpers(unittest.TestCase):
""" Tests homeassistant.helpers module. """
def setUp(self): # pylint: disable=invalid-name
""" Init needed objects. """
self.hass = get_test_home_assistant()
self.hass.states.set('light.Bowl', STATE_ON)
self.hass.states.set('light.Ceiling', STATE_OFF)
self.hass.states.set('light.Kitchen', STATE_OFF)
loader.get_component('group').setup_group(
self.hass, 'test', ['light.Ceiling', 'light.Kitchen'])
def tearDown(self): # pylint: disable=invalid-name
""" Stop down stuff we started. """
self.hass.stop()
def test_extract_entity_ids(self):
""" Test extract_entity_ids method. """
call = ha.ServiceCall('light', 'turn_on',
{ATTR_ENTITY_ID: 'light.Bowl'})
self.assertEqual(['light.bowl'],
helpers.extract_entity_ids(self.hass, call))
call = ha.ServiceCall('light', 'turn_on',
{ATTR_ENTITY_ID: 'group.test'})
self.assertEqual(['light.ceiling', 'light.kitchen'],
helpers.extract_entity_ids(self.hass, call))
def test_extract_domain_configs(self):
config = {
'zone': None,

View File

@ -7,6 +7,8 @@ Test service helpers.
import unittest
from unittest.mock import patch
from homeassistant import core as ha, loader
from homeassistant.const import STATE_ON, STATE_OFF, ATTR_ENTITY_ID
from homeassistant.helpers import service
from tests.common import get_test_home_assistant, mock_service
@ -78,3 +80,24 @@ class TestServiceHelpers(unittest.TestCase):
'service': 'invalid'
})
self.assertEqual(3, mock_log.call_count)
def test_extract_entity_ids(self):
""" Test extract_entity_ids method. """
self.hass.states.set('light.Bowl', STATE_ON)
self.hass.states.set('light.Ceiling', STATE_OFF)
self.hass.states.set('light.Kitchen', STATE_OFF)
loader.get_component('group').setup_group(
self.hass, 'test', ['light.Ceiling', 'light.Kitchen'])
call = ha.ServiceCall('light', 'turn_on',
{ATTR_ENTITY_ID: 'light.Bowl'})
self.assertEqual(['light.bowl'],
service.extract_entity_ids(self.hass, call))
call = ha.ServiceCall('light', 'turn_on',
{ATTR_ENTITY_ID: 'group.test'})
self.assertEqual(['light.ceiling', 'light.kitchen'],
service.extract_entity_ids(self.hass, call))

View File

@ -94,13 +94,14 @@ class TestConfig(unittest.TestCase):
with self.assertRaises(HomeAssistantError):
config_util.load_yaml_config_file(YAML_PATH)
def test_load_config_loads_yaml_config(self):
""" Test correct YAML config loading. """
def test_load_yaml_config_preserves_key_order(self):
with open(YAML_PATH, 'w') as f:
f.write('hello: world')
f.write('hello: 0\n')
f.write('world: 1\n')
self.assertEqual({'hello': 'world'},
config_util.load_config_file(YAML_PATH))
self.assertEqual(
[('hello', 0), ('world', 1)],
list(config_util.load_yaml_config_file(YAML_PATH).items()))
@mock.patch('homeassistant.util.location.detect_location_info',
mock_detect_location_info)
@ -109,7 +110,7 @@ class TestConfig(unittest.TestCase):
""" Test that detect location sets the correct config keys. """
config_util.ensure_config_exists(CONFIG_DIR)
config = config_util.load_config_file(YAML_PATH)
config = config_util.load_yaml_config_file(YAML_PATH)
self.assertIn(DOMAIN, config)

View File

@ -36,11 +36,6 @@ class TestUtil(unittest.TestCase):
self.assertEqual("test_more", util.slugify("Test More"))
self.assertEqual("test_more", util.slugify("Test_(More)"))
def test_split_entity_id(self):
""" Test split_entity_id. """
self.assertEqual(['domain', 'object_id'],
util.split_entity_id('domain.object_id'))
def test_repr_helper(self):
""" Test repr_helper. """
self.assertEqual("A", util.repr_helper("A"))