Migrate core from threads to async awesomeness (#3248)

* Add event loop to the core

* Add block_till_done to HA core object

* Fix some tests

* Linting core

* Fix statemachine tests

* Core test fixes

* fix block_till_done to wait for loop and queue to empty

* fix test_core for passing, and correct start/stop/block_till_done

* Fix remote tests

* Fix tests: block_till_done

* Fix linting

* Fix more tests

* Fix final linting

* Fix remote test

* remove unnecessary import

* reduce sleep to avoid slowing down the tests excessively

* fix remaining tests to wait for non-threadsafe operations

* Add async_ doc strings for event loop / coroutine info

* Fix command line test to block for the right timeout

* Fix py3.4.2 loop var access

* Fix SERVICE_CALL_LIMIT being in effect for other tests

* Fix lint errors

* Fix lint error with proper placement

* Fix slave start to not start a timer

* Add asyncio compatible listeners.

* Increase min Python version to 3.4.2

* Move async backports to util

* Add backported async tests

* Fix linting

* Simplify Python version check

* Fix lint

* Remove unneeded try/except and queue listener appproriately.

* Fix tuple vs. list unorderable error on version compare.

* Fix version tests
This commit is contained in:
Paulus Schoutsen 2016-09-12 19:16:14 -07:00 committed by Ben Bangert
parent 24f1bff7f1
commit 609d7ebea5
98 changed files with 1680 additions and 1109 deletions

View file

@ -16,16 +16,14 @@ from homeassistant.const import (
REQUIRED_PYTHON_VER, REQUIRED_PYTHON_VER,
RESTART_EXIT_CODE, RESTART_EXIT_CODE,
) )
from homeassistant.util.async import run_callback_threadsafe
def validate_python() -> None: def validate_python() -> None:
"""Validate we're running the right Python version.""" """Validate we're running the right Python version."""
major, minor = sys.version_info[:2] if sys.version_info[:3] < REQUIRED_PYTHON_VER:
req_major, req_minor = REQUIRED_PYTHON_VER print("Home Assistant requires at least Python {}.{}.{}".format(
*REQUIRED_PYTHON_VER))
if major < req_major or (major == req_major and minor < req_minor):
print("Home Assistant requires at least Python {}.{}".format(
req_major, req_minor))
sys.exit(1) sys.exit(1)
@ -256,12 +254,14 @@ def setup_and_run_hass(config_dir: str,
import webbrowser import webbrowser
webbrowser.open(hass.config.api.base_url) webbrowser.open(hass.config.api.base_url)
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, open_browser) run_callback_threadsafe(
hass.loop,
hass.bus.async_listen_once,
EVENT_HOMEASSISTANT_START, open_browser
)
hass.start() hass.start()
exit_code = int(hass.block_till_stopped()) return hass.exit_code
return exit_code
def try_to_restart() -> None: def try_to_restart() -> None:

View file

@ -122,7 +122,8 @@ def _setup_component(hass: core.HomeAssistant, domain: str, config) -> bool:
hass.pool.add_worker() hass.pool.add_worker()
hass.bus.fire( hass.bus.fire(
EVENT_COMPONENT_LOADED, {ATTR_COMPONENT: component.DOMAIN}) EVENT_COMPONENT_LOADED, {ATTR_COMPONENT: component.DOMAIN}
)
return True return True
@ -278,6 +279,9 @@ def from_config_dict(config: Dict[str, Any],
components = set(key.split(' ')[0] for key in config.keys() components = set(key.split(' ')[0] for key in config.keys()
if key != core.DOMAIN) if key != core.DOMAIN)
# Setup in a thread to avoid blocking
def component_setup():
"""Set up a component."""
if not core_components.setup(hass, config): if not core_components.setup(hass, config):
_LOGGER.error('Home Assistant core failed to initialize. ' _LOGGER.error('Home Assistant core failed to initialize. '
'Further initialization aborted.') 'Further initialization aborted.')
@ -295,6 +299,9 @@ def from_config_dict(config: Dict[str, Any],
for domain in loader.load_order_components(components): for domain in loader.load_order_components(components):
_setup_component(hass, domain, config) _setup_component(hass, domain, config)
hass.loop.run_until_complete(
hass.loop.run_in_executor(None, component_setup)
)
return hass return hass

View file

@ -4,6 +4,7 @@ Rest API for Home Assistant.
For more details about the RESTful API, please refer to the documentation at For more details about the RESTful API, please refer to the documentation at
https://home-assistant.io/developers/api/ https://home-assistant.io/developers/api/
""" """
import asyncio
import json import json
import logging import logging
import queue import queue
@ -79,6 +80,7 @@ class APIEventStream(HomeAssistantView):
if restrict: if restrict:
restrict = restrict.split(',') + [EVENT_HOMEASSISTANT_STOP] restrict = restrict.split(',') + [EVENT_HOMEASSISTANT_STOP]
@asyncio.coroutine
def forward_events(event): def forward_events(event):
"""Forward events to the open request.""" """Forward events to the open request."""
if event.event_type == EVENT_TIME_CHANGED: if event.event_type == EVENT_TIME_CHANGED:

View file

@ -7,6 +7,7 @@ to query this database.
For more details about this component, please refer to the documentation at For more details about this component, please refer to the documentation at
https://home-assistant.io/components/recorder/ https://home-assistant.io/components/recorder/
""" """
import asyncio
import logging import logging
import queue import queue
import threading import threading
@ -230,6 +231,7 @@ class Recorder(threading.Thread):
self.queue.task_done() self.queue.task_done()
@asyncio.coroutine
def event_listener(self, event): def event_listener(self, event):
"""Listen for new events and put them in the process queue.""" """Listen for new events and put them in the process queue."""
self.queue.put(event) self.queue.put(event)

View file

@ -5,7 +5,7 @@ MINOR_VERSION = 29
PATCH_VERSION = '0.dev0' PATCH_VERSION = '0.dev0'
__short_version__ = '{}.{}'.format(MAJOR_VERSION, MINOR_VERSION) __short_version__ = '{}.{}'.format(MAJOR_VERSION, MINOR_VERSION)
__version__ = '{}.{}'.format(__short_version__, PATCH_VERSION) __version__ = '{}.{}'.format(__short_version__, PATCH_VERSION)
REQUIRED_PYTHON_VER = (3, 4) REQUIRED_PYTHON_VER = (3, 4, 2)
PROJECT_NAME = 'Home Assistant' PROJECT_NAME = 'Home Assistant'
PROJECT_PACKAGE_NAME = 'homeassistant' PROJECT_PACKAGE_NAME = 'homeassistant'

View file

@ -4,18 +4,20 @@ Core components of Home Assistant.
Home Assistant is a Home Automation framework for observing the state Home Assistant is a Home Automation framework for observing the state
of entities and react to changes. of entities and react to changes.
""" """
# pylint: disable=unused-import, too-many-lines
import asyncio
import enum import enum
import functools as ft import functools as ft
import logging import logging
import os import os
import re import re
import signal import signal
import threading import sys
import time import time
from concurrent.futures import ThreadPoolExecutor
from types import MappingProxyType from types import MappingProxyType
# pylint: disable=unused-import
from typing import Optional, Any, Callable, List # NOQA from typing import Optional, Any, Callable, List # NOQA
import voluptuous as vol import voluptuous as vol
@ -30,6 +32,8 @@ from homeassistant.const import (
SERVICE_HOMEASSISTANT_RESTART, SERVICE_HOMEASSISTANT_STOP, __version__) SERVICE_HOMEASSISTANT_RESTART, SERVICE_HOMEASSISTANT_STOP, __version__)
from homeassistant.exceptions import ( from homeassistant.exceptions import (
HomeAssistantError, InvalidEntityFormatError) HomeAssistantError, InvalidEntityFormatError)
from homeassistant.util.async import (
run_coroutine_threadsafe, run_callback_threadsafe)
import homeassistant.util as util import homeassistant.util as util
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
import homeassistant.util.location as location import homeassistant.util.location as location
@ -103,14 +107,20 @@ class JobPriority(util.OrderedEnum):
class HomeAssistant(object): class HomeAssistant(object):
"""Root object of the Home Assistant home automation.""" """Root object of the Home Assistant home automation."""
def __init__(self): # pylint: disable=too-many-instance-attributes
def __init__(self, loop=None):
"""Initialize new Home Assistant object.""" """Initialize new Home Assistant object."""
self.loop = loop or asyncio.get_event_loop()
self.executer = ThreadPoolExecutor(max_workers=5)
self.loop.set_default_executor(self.executer)
self.pool = pool = create_worker_pool() self.pool = pool = create_worker_pool()
self.bus = EventBus(pool) self.bus = EventBus(pool, self.loop)
self.services = ServiceRegistry(self.bus, self.add_job) self.services = ServiceRegistry(self.bus, self.add_job, self.loop)
self.states = StateMachine(self.bus) self.states = StateMachine(self.bus, self.loop)
self.config = Config() # type: Config self.config = Config() # type: Config
self.state = CoreState.not_running self.state = CoreState.not_running
self.exit_code = None
@property @property
def is_running(self) -> bool: def is_running(self) -> bool:
@ -123,9 +133,65 @@ class HomeAssistant(object):
"Starting Home Assistant (%d threads)", self.pool.worker_count) "Starting Home Assistant (%d threads)", self.pool.worker_count)
self.state = CoreState.starting self.state = CoreState.starting
# Register the async start
self.loop.create_task(self.async_start())
@asyncio.coroutine
def stop_homeassistant(*args):
"""Stop Home Assistant."""
self.exit_code = 0
yield from self.async_stop()
@asyncio.coroutine
def restart_homeassistant(*args):
"""Restart Home Assistant."""
self.exit_code = RESTART_EXIT_CODE
yield from self.async_stop()
# Register the restart/stop event
self.loop.call_soon(
self.services.async_register,
DOMAIN, SERVICE_HOMEASSISTANT_STOP, stop_homeassistant
)
self.loop.call_soon(
self.services.async_register,
DOMAIN, SERVICE_HOMEASSISTANT_RESTART, restart_homeassistant
)
# Setup signal handling
try:
signal.signal(signal.SIGTERM, stop_homeassistant)
except ValueError:
_LOGGER.warning(
'Could not bind to SIGTERM. Are you running in a thread?')
try:
signal.signal(signal.SIGHUP, restart_homeassistant)
except ValueError:
_LOGGER.warning(
'Could not bind to SIGHUP. Are you running in a thread?')
except AttributeError:
pass
# Run forever and catch keyboard interrupt
try:
# Block until stopped
_LOGGER.info("Starting Home Assistant core loop")
self.loop.run_forever()
except KeyboardInterrupt:
pass
finally:
self.loop.create_task(stop_homeassistant())
self.loop.run_forever()
@asyncio.coroutine
def async_start(self):
"""Finalize startup from inside the event loop.
This method is a coroutine.
"""
create_timer(self) create_timer(self)
self.bus.fire(EVENT_HOMEASSISTANT_START) self.bus.async_fire(EVENT_HOMEASSISTANT_START)
self.pool.block_till_done() yield from self.loop.run_in_executor(None, self.pool.block_till_done)
self.state = CoreState.running self.state = CoreState.running
def add_job(self, def add_job(self,
@ -139,55 +205,66 @@ class HomeAssistant(object):
""" """
self.pool.add_job(priority, (target,) + args) self.pool.add_job(priority, (target,) + args)
def block_till_stopped(self) -> int: def _loop_empty(self):
"""Register service homeassistant/stop and will block until called.""" """Python 3.4.2 empty loop compatibility function."""
request_shutdown = threading.Event() # pylint: disable=protected-access
request_restart = threading.Event() if sys.version_info < (3, 4, 3):
return len(self.loop._scheduled) == 0 and \
len(self.loop._ready) == 0
else:
return self.loop._current_handle is None and \
len(self.loop._ready) == 0
def stop_homeassistant(*args): def block_till_done(self):
"""Stop Home Assistant.""" """Block till all pending work is done."""
request_shutdown.set() import threading
def restart_homeassistant(*args): complete = threading.Event()
"""Reset Home Assistant."""
_LOGGER.warning('Home Assistant requested a restart.')
request_restart.set()
request_shutdown.set()
self.services.register( @asyncio.coroutine
DOMAIN, SERVICE_HOMEASSISTANT_STOP, stop_homeassistant) def sleep_wait():
self.services.register( """Sleep in thread pool."""
DOMAIN, SERVICE_HOMEASSISTANT_RESTART, restart_homeassistant) yield from self.loop.run_in_executor(None, time.sleep, 0)
try: def notify_when_done():
signal.signal(signal.SIGTERM, stop_homeassistant) """Notify event loop when pool done."""
except ValueError: while True:
_LOGGER.warning( # Wait for the work queue to empty
'Could not bind to SIGTERM. Are you running in a thread?') self.pool.block_till_done()
try:
signal.signal(signal.SIGHUP, restart_homeassistant)
except ValueError:
_LOGGER.warning(
'Could not bind to SIGHUP. Are you running in a thread?')
except AttributeError:
pass
try:
while not request_shutdown.is_set():
time.sleep(1)
except KeyboardInterrupt:
pass
finally:
self.stop()
return RESTART_EXIT_CODE if request_restart.is_set() else 0 # Verify the loop is empty
if self._loop_empty():
break
# sleep in the loop executor, this forces execution back into
# the event loop to avoid the block thread from starving the
# async loop
run_coroutine_threadsafe(
sleep_wait(),
self.loop
).result()
complete.set()
threading.Thread(name="BlockThread", target=notify_when_done).start()
complete.wait()
def stop(self) -> None: def stop(self) -> None:
"""Stop Home Assistant and shuts down all threads.""" """Stop Home Assistant and shuts down all threads."""
_LOGGER.info("Stopping") run_coroutine_threadsafe(self.async_stop(), self.loop)
@asyncio.coroutine
def async_stop(self) -> None:
"""Stop Home Assistant and shuts down all threads.
This method is a coroutine.
"""
self.state = CoreState.stopping self.state = CoreState.stopping
self.bus.fire(EVENT_HOMEASSISTANT_STOP) self.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
self.pool.stop() yield from self.loop.run_in_executor(None, self.pool.block_till_done)
yield from self.loop.run_in_executor(None, self.pool.stop)
self.state = CoreState.not_running self.state = CoreState.not_running
self.loop.stop()
class EventOrigin(enum.Enum): class EventOrigin(enum.Enum):
@ -247,25 +324,43 @@ class Event(object):
class EventBus(object): class EventBus(object):
"""Allows firing of and listening for events.""" """Allows firing of and listening for events."""
def __init__(self, pool: util.ThreadPool) -> None: def __init__(self, pool: util.ThreadPool,
loop: asyncio.AbstractEventLoop) -> None:
"""Initialize a new event bus.""" """Initialize a new event bus."""
self._listeners = {} self._listeners = {}
self._lock = threading.Lock()
self._pool = pool self._pool = pool
self._loop = loop
def async_listeners(self):
"""Dict with events and the number of listeners.
This method must be run in the event loop.
"""
return {key: len(self._listeners[key])
for key in self._listeners}
@property @property
def listeners(self): def listeners(self):
"""Dict with events and the number of listeners.""" """Dict with events and the number of listeners."""
with self._lock: return run_callback_threadsafe(
return {key: len(self._listeners[key]) self._loop, self.async_listeners
for key in self._listeners} ).result()
def fire(self, event_type: str, event_data=None, origin=EventOrigin.local): def fire(self, event_type: str, event_data=None, origin=EventOrigin.local):
"""Fire an event.""" """Fire an event."""
if not self._pool.running: if not self._pool.running:
raise HomeAssistantError('Home Assistant has shut down.') raise HomeAssistantError('Home Assistant has shut down.')
with self._lock: self._loop.call_soon_threadsafe(self.async_fire, event_type,
event_data, origin)
return
def async_fire(self, event_type: str, event_data=None,
origin=EventOrigin.local, wait=False):
"""Fire an event.
This method must be run in the event loop.
"""
# Copy the list of the current listeners because some listeners # Copy the list of the current listeners because some listeners
# remove themselves as a listener while being executed which # remove themselves as a listener while being executed which
# causes the iterator to be confused. # causes the iterator to be confused.
@ -282,8 +377,16 @@ class EventBus(object):
job_priority = JobPriority.from_event_type(event_type) job_priority = JobPriority.from_event_type(event_type)
sync_jobs = []
for func in listeners: for func in listeners:
self._pool.add_job(job_priority, (func, event)) if asyncio.iscoroutinefunction(func):
self._loop.create_task(func(event))
else:
sync_jobs.append((job_priority, (func, event)))
# Send all the sync jobs at once
if sync_jobs:
self._pool.add_many_jobs(sync_jobs)
def listen(self, event_type, listener): def listen(self, event_type, listener):
"""Listen for all events or events of a specific type. """Listen for all events or events of a specific type.
@ -291,7 +394,24 @@ class EventBus(object):
To listen to all events specify the constant ``MATCH_ALL`` To listen to all events specify the constant ``MATCH_ALL``
as event_type. as event_type.
""" """
with self._lock: future = run_callback_threadsafe(
self._loop, self.async_listen, event_type, listener)
future.result()
def remove_listener():
"""Remove the listener."""
self._remove_listener(event_type, listener)
return remove_listener
def async_listen(self, event_type, listener):
"""Listen for all events or events of a specific type.
To listen to all events specify the constant ``MATCH_ALL``
as event_type.
This method must be run in the event loop.
"""
if event_type in self._listeners: if event_type in self._listeners:
self._listeners[event_type].append(listener) self._listeners[event_type].append(listener)
else: else:
@ -299,7 +419,7 @@ class EventBus(object):
def remove_listener(): def remove_listener():
"""Remove the listener.""" """Remove the listener."""
self._remove_listener(event_type, listener) self.async_remove_listener(event_type, listener)
return remove_listener return remove_listener
@ -331,6 +451,41 @@ class EventBus(object):
return remove_listener return remove_listener
def async_listen_once(self, event_type, listener):
"""Listen once for event of a specific type.
To listen to all events specify the constant ``MATCH_ALL``
as event_type.
Returns registered listener that can be used with remove_listener.
This method must be run in the event loop.
"""
@ft.wraps(listener)
@asyncio.coroutine
def onetime_listener(event):
"""Remove listener from eventbus and then fire listener."""
if hasattr(onetime_listener, 'run'):
return
# Set variable so that we will never run twice.
# Because the event bus loop might have async_fire queued multiple
# times, its possible this listener may already be lined up
# multiple times as well.
# This will make sure the second time it does nothing.
setattr(onetime_listener, 'run', True)
self.async_remove_listener(event_type, onetime_listener)
if asyncio.iscoroutinefunction(listener):
yield from listener(event)
else:
job_priority = JobPriority.from_event_type(event.event_type)
self._pool.add_job(job_priority, (listener, event))
self.async_listen(event_type, onetime_listener)
return onetime_listener
def remove_listener(self, event_type, listener): def remove_listener(self, event_type, listener):
"""Remove a listener of a specific event_type. (DEPRECATED 0.28).""" """Remove a listener of a specific event_type. (DEPRECATED 0.28)."""
_LOGGER.warning('bus.remove_listener has been deprecated. Please use ' _LOGGER.warning('bus.remove_listener has been deprecated. Please use '
@ -339,14 +494,23 @@ class EventBus(object):
def _remove_listener(self, event_type, listener): def _remove_listener(self, event_type, listener):
"""Remove a listener of a specific event_type.""" """Remove a listener of a specific event_type."""
with self._lock: future = run_callback_threadsafe(
self._loop,
self.async_remove_listener, event_type, listener
)
future.result()
def async_remove_listener(self, event_type, listener):
"""Remove a listener of a specific event_type.
This method must be run in the event loop.
"""
try: try:
self._listeners[event_type].remove(listener) self._listeners[event_type].remove(listener)
# delete event_type list if empty # delete event_type list if empty
if not self._listeners[event_type]: if not self._listeners[event_type]:
self._listeners.pop(event_type) self._listeners.pop(event_type)
except (KeyError, ValueError): except (KeyError, ValueError):
# KeyError is key event_type listener did not exist # KeyError is key event_type listener did not exist
# ValueError if listener did not exist within event_type # ValueError if listener did not exist within event_type
@ -455,26 +619,38 @@ class State(object):
class StateMachine(object): class StateMachine(object):
"""Helper class that tracks the state of different entities.""" """Helper class that tracks the state of different entities."""
def __init__(self, bus): def __init__(self, bus, loop):
"""Initialize state machine.""" """Initialize state machine."""
self._states = {} self._states = {}
self._bus = bus self._bus = bus
self._lock = threading.Lock() self._loop = loop
def entity_ids(self, domain_filter=None): def entity_ids(self, domain_filter=None):
"""List of entity ids that are being tracked."""
future = run_callback_threadsafe(
self._loop, self.async_entity_ids, domain_filter
)
return future.result()
def async_entity_ids(self, domain_filter=None):
"""List of entity ids that are being tracked.""" """List of entity ids that are being tracked."""
if domain_filter is None: if domain_filter is None:
return list(self._states.keys()) return list(self._states.keys())
domain_filter = domain_filter.lower() domain_filter = domain_filter.lower()
with self._lock:
return [state.entity_id for state in self._states.values() return [state.entity_id for state in self._states.values()
if state.domain == domain_filter] if state.domain == domain_filter]
def all(self): def all(self):
"""Create a list of all states.""" """Create a list of all states."""
with self._lock: return run_callback_threadsafe(self._loop, self.async_all).result()
def async_all(self):
"""Create a list of all states.
This method must be run in the event loop.
"""
return list(self._states.values()) return list(self._states.values())
def get(self, entity_id): def get(self, entity_id):
@ -483,6 +659,15 @@ class StateMachine(object):
def is_state(self, entity_id, state): def is_state(self, entity_id, state):
"""Test if entity exists and is specified state.""" """Test if entity exists and is specified state."""
return run_callback_threadsafe(
self._loop, self.async_is_state, entity_id, state
).result()
def async_is_state(self, entity_id, state):
"""Test if entity exists and is specified state.
This method must be run in the event loop.
"""
entity_id = entity_id.lower() entity_id = entity_id.lower()
return (entity_id in self._states and return (entity_id in self._states and
@ -490,6 +675,15 @@ class StateMachine(object):
def is_state_attr(self, entity_id, name, value): def is_state_attr(self, entity_id, name, value):
"""Test if entity exists and has a state attribute set to value.""" """Test if entity exists and has a state attribute set to value."""
return run_callback_threadsafe(
self._loop, self.async_is_state_attr, entity_id, name, value
).result()
def async_is_state_attr(self, entity_id, name, value):
"""Test if entity exists and has a state attribute set to value.
This method must be run in the event loop.
"""
entity_id = entity_id.lower() entity_id = entity_id.lower()
return (entity_id in self._states and return (entity_id in self._states and
@ -500,9 +694,18 @@ class StateMachine(object):
Returns boolean to indicate if an entity was removed. Returns boolean to indicate if an entity was removed.
""" """
return run_callback_threadsafe(
self._loop, self.async_remove, entity_id).result()
def async_remove(self, entity_id):
"""Remove the state of an entity.
Returns boolean to indicate if an entity was removed.
This method must be run in the event loop.
"""
entity_id = entity_id.lower() entity_id = entity_id.lower()
with self._lock:
old_state = self._states.pop(entity_id, None) old_state = self._states.pop(entity_id, None)
if old_state is None: if old_state is None:
@ -514,7 +717,7 @@ class StateMachine(object):
'new_state': None, 'new_state': None,
} }
self._bus.fire(EVENT_STATE_CHANGED, event_data) self._bus.async_fire(EVENT_STATE_CHANGED, event_data)
return True return True
@ -526,11 +729,26 @@ class StateMachine(object):
If you just update the attributes and not the state, last changed will If you just update the attributes and not the state, last changed will
not be affected. not be affected.
""" """
run_callback_threadsafe(
self._loop,
self.async_set, entity_id, new_state, attributes, force_update,
).result()
def async_set(self, entity_id, new_state, attributes=None,
force_update=False):
"""Set the state of an entity, add entity if it does not exist.
Attributes is an optional dict to specify attributes of this state.
If you just update the attributes and not the state, last changed will
not be affected.
This method must be run in the event loop.
"""
entity_id = entity_id.lower() entity_id = entity_id.lower()
new_state = str(new_state) new_state = str(new_state)
attributes = attributes or {} attributes = attributes or {}
with self._lock:
old_state = self._states.get(entity_id) old_state = self._states.get(entity_id)
is_existing = old_state is not None is_existing = old_state is not None
@ -553,7 +771,7 @@ class StateMachine(object):
'new_state': state, 'new_state': state,
} }
self._bus.fire(EVENT_STATE_CHANGED, event_data) self._bus.async_fire(EVENT_STATE_CHANGED, event_data)
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
@ -615,19 +833,27 @@ class ServiceCall(object):
class ServiceRegistry(object): class ServiceRegistry(object):
"""Offers services over the eventbus.""" """Offers services over the eventbus."""
def __init__(self, bus, add_job): def __init__(self, bus, add_job, loop):
"""Initialize a service registry.""" """Initialize a service registry."""
self._services = {} self._services = {}
self._lock = threading.Lock()
self._add_job = add_job self._add_job = add_job
self._bus = bus self._bus = bus
self._loop = loop
self._cur_id = 0 self._cur_id = 0
bus.listen(EVENT_CALL_SERVICE, self._event_to_service_call) run_callback_threadsafe(
loop,
bus.async_listen, EVENT_CALL_SERVICE, self._event_to_service_call,
)
@property @property
def services(self): def services(self):
"""Dict with per domain a list of available services.""" """Dict with per domain a list of available services."""
with self._lock: return run_callback_threadsafe(
self._loop, self.async_services,
).result()
def async_services(self):
"""Dict with per domain a list of available services."""
return {domain: {key: value.as_dict() for key, value return {domain: {key: value.as_dict() for key, value
in self._services[domain].items()} in self._services[domain].items()}
for domain in self._services} for domain in self._services}
@ -647,20 +873,39 @@ class ServiceRegistry(object):
Schema is called to coerce and validate the service data. Schema is called to coerce and validate the service data.
""" """
run_callback_threadsafe(
self._loop,
self.async_register, domain, service, service_func, description,
schema
).result()
def async_register(self, domain, service, service_func, description=None,
schema=None):
"""
Register a service.
Description is a dict containing key 'description' to describe
the service and a key 'fields' to describe the fields.
Schema is called to coerce and validate the service data.
This method must be run in the event loop.
"""
domain = domain.lower() domain = domain.lower()
service = service.lower() service = service.lower()
description = description or {} description = description or {}
service_obj = Service(service_func, description.get('description'), service_obj = Service(service_func, description.get('description'),
description.get('fields', {}), schema) description.get('fields', {}), schema)
with self._lock:
if domain in self._services: if domain in self._services:
self._services[domain][service] = service_obj self._services[domain][service] = service_obj
else: else:
self._services[domain] = {service: service_obj} self._services[domain] = {service: service_obj}
self._bus.fire( self._bus.async_fire(
EVENT_SERVICE_REGISTERED, EVENT_SERVICE_REGISTERED,
{ATTR_DOMAIN: domain, ATTR_SERVICE: service}) {ATTR_DOMAIN: domain, ATTR_SERVICE: service}
)
def call(self, domain, service, service_data=None, blocking=False): def call(self, domain, service, service_data=None, blocking=False):
""" """
@ -679,6 +924,31 @@ class ServiceRegistry(object):
Because the service is sent as an event you are not allowed to use Because the service is sent as an event you are not allowed to use
the keys ATTR_DOMAIN and ATTR_SERVICE in your service_data. the keys ATTR_DOMAIN and ATTR_SERVICE in your service_data.
""" """
return run_coroutine_threadsafe(
self.async_call(domain, service, service_data, blocking),
self._loop
).result()
@asyncio.coroutine
def async_call(self, domain, service, service_data=None, blocking=False):
"""
Call a service.
Specify blocking=True to wait till service is executed.
Waits a maximum of SERVICE_CALL_LIMIT.
If blocking = True, will return boolean if service executed
succesfully within SERVICE_CALL_LIMIT.
This method will fire an event to call the service.
This event will be picked up by this ServiceRegistry and any
other ServiceRegistry that is listening on the EventBus.
Because the service is sent as an event you are not allowed to use
the keys ATTR_DOMAIN and ATTR_SERVICE in your service_data.
This method is a coroutine.
"""
call_id = self._generate_unique_id() call_id = self._generate_unique_id()
event_data = { event_data = {
@ -689,19 +959,23 @@ class ServiceRegistry(object):
} }
if blocking: if blocking:
executed_event = threading.Event() fut = asyncio.Future(loop=self._loop)
@asyncio.coroutine
def service_executed(call): def service_executed(call):
"""Callback method that is called when service is executed.""" """Callback method that is called when service is executed."""
if call.data[ATTR_SERVICE_CALL_ID] == call_id: if call.data[ATTR_SERVICE_CALL_ID] == call_id:
executed_event.set() fut.set_result(True)
unsub = self._bus.listen(EVENT_SERVICE_EXECUTED, service_executed) unsub = self._bus.async_listen(EVENT_SERVICE_EXECUTED,
service_executed)
self._bus.fire(EVENT_CALL_SERVICE, event_data) self._bus.async_fire(EVENT_CALL_SERVICE, event_data)
if blocking: if blocking:
success = executed_event.wait(SERVICE_CALL_LIMIT) done, _ = yield from asyncio.wait([fut], loop=self._loop,
timeout=SERVICE_CALL_LIMIT)
success = bool(done)
unsub() unsub()
return success return success
@ -797,16 +1071,19 @@ def create_timer(hass, interval=TIMER_INTERVAL):
# every minute. # every minute.
assert 60 % interval == 0, "60 % TIMER_INTERVAL should be 0!" assert 60 % interval == 0, "60 % TIMER_INTERVAL should be 0!"
def timer(): stop_event = asyncio.Event(loop=hass.loop)
"""Send an EVENT_TIME_CHANGED on interval."""
stop_event = threading.Event()
# Setting the Event inside the loop by marking it as a coroutine
@asyncio.coroutine
def stop_timer(event): def stop_timer(event):
"""Stop the timer.""" """Stop the timer."""
stop_event.set() stop_event.set()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_timer) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_timer)
@asyncio.coroutine
def timer(interval, stop_event):
"""Create an async timer."""
_LOGGER.info("Timer:starting") _LOGGER.info("Timer:starting")
last_fired_on_second = -1 last_fired_on_second = -1
@ -830,7 +1107,7 @@ def create_timer(hass, interval=TIMER_INTERVAL):
slp_seconds = interval - now.second % interval + \ slp_seconds = interval - now.second % interval + \
.5 - now.microsecond/1000000.0 .5 - now.microsecond/1000000.0
time.sleep(slp_seconds) yield from asyncio.sleep(slp_seconds, loop=hass.loop)
now = calc_now() now = calc_now()
@ -839,18 +1116,22 @@ def create_timer(hass, interval=TIMER_INTERVAL):
# Event might have been set while sleeping # Event might have been set while sleeping
if not stop_event.is_set(): if not stop_event.is_set():
try: try:
hass.bus.fire(EVENT_TIME_CHANGED, {ATTR_NOW: now}) # Schedule the bus event
hass.loop.call_soon(
hass.bus.async_fire,
EVENT_TIME_CHANGED,
{ATTR_NOW: now}
)
except HomeAssistantError: except HomeAssistantError:
# HA raises error if firing event after it has shut down # HA raises error if firing event after it has shut down
break break
@asyncio.coroutine
def start_timer(event): def start_timer(event):
"""Start the timer.""" """Start our async timer."""
thread = threading.Thread(target=timer, name='Timer') hass.loop.create_task(timer(interval, stop_event))
thread.daemon = True
thread.start()
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_timer) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, start_timer)
def create_worker_pool(worker_count=None): def create_worker_pool(worker_count=None):

View file

@ -7,6 +7,7 @@ HomeAssistantError will be raised.
For more details about the Python API, please refer to the documentation at For more details about the Python API, please refer to the documentation at
https://home-assistant.io/developers/python_api/ https://home-assistant.io/developers/python_api/
""" """
import asyncio
from datetime import datetime from datetime import datetime
import enum import enum
import json import json
@ -113,7 +114,7 @@ class HomeAssistant(ha.HomeAssistant):
"""Home Assistant that forwards work.""" """Home Assistant that forwards work."""
# pylint: disable=super-init-not-called,too-many-instance-attributes # pylint: disable=super-init-not-called,too-many-instance-attributes
def __init__(self, remote_api, local_api=None): def __init__(self, remote_api, local_api=None, loop=None):
"""Initalize the forward instance.""" """Initalize the forward instance."""
if not remote_api.validate_api(): if not remote_api.validate_api():
raise HomeAssistantError( raise HomeAssistantError(
@ -122,11 +123,12 @@ class HomeAssistant(ha.HomeAssistant):
self.remote_api = remote_api self.remote_api = remote_api
self.loop = loop or asyncio.get_event_loop()
self.pool = pool = ha.create_worker_pool() self.pool = pool = ha.create_worker_pool()
self.bus = EventBus(remote_api, pool) self.bus = EventBus(remote_api, pool, self.loop)
self.services = ha.ServiceRegistry(self.bus, pool) self.services = ha.ServiceRegistry(self.bus, self.add_job, self.loop)
self.states = StateMachine(self.bus, self.remote_api) self.states = StateMachine(self.bus, self.loop, self.remote_api)
self.config = ha.Config() self.config = ha.Config()
self.state = ha.CoreState.not_running self.state = ha.CoreState.not_running
@ -147,7 +149,7 @@ class HomeAssistant(ha.HomeAssistant):
origin=ha.EventOrigin.remote) origin=ha.EventOrigin.remote)
# Ensure local HTTP is started # Ensure local HTTP is started
self.pool.block_till_done() self.block_till_done()
self.state = ha.CoreState.running self.state = ha.CoreState.running
time.sleep(0.05) time.sleep(0.05)
@ -178,9 +180,9 @@ class EventBus(ha.EventBus):
"""EventBus implementation that forwards fire_event to remote API.""" """EventBus implementation that forwards fire_event to remote API."""
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
def __init__(self, api, pool=None): def __init__(self, api, pool, loop):
"""Initalize the eventbus.""" """Initalize the eventbus."""
super().__init__(pool) super().__init__(pool, loop)
self._api = api self._api = api
def fire(self, event_type, event_data=None, origin=ha.EventOrigin.local): def fire(self, event_type, event_data=None, origin=ha.EventOrigin.local):
@ -256,9 +258,9 @@ class EventForwarder(object):
class StateMachine(ha.StateMachine): class StateMachine(ha.StateMachine):
"""Fire set events to an API. Uses state_change events to track states.""" """Fire set events to an API. Uses state_change events to track states."""
def __init__(self, bus, api): def __init__(self, bus, loop, api):
"""Initalize the statemachine.""" """Initalize the statemachine."""
super().__init__(None) super().__init__(bus, loop)
self._api = api self._api = api
self.mirror() self.mirror()

View file

@ -377,6 +377,26 @@ class ThreadPool(object):
self.worker_count, self.current_jobs, self.worker_count, self.current_jobs,
self._work_queue.qsize()) self._work_queue.qsize())
def add_many_jobs(self, jobs):
"""Add a list of jobs to the queue."""
with self._lock:
if not self.running:
raise RuntimeError("ThreadPool not running")
for priority, job in jobs:
self._work_queue.put(PriorityQueueItem(priority, job))
# Check if our queue is getting too big.
if self._work_queue.qsize() > self.busy_warning_limit \
and self._busy_callback is not None:
# Increase limit we will issue next warning.
self.busy_warning_limit *= 2
self._busy_callback(
self.worker_count, self.current_jobs,
self._work_queue.qsize())
def block_till_done(self): def block_till_done(self):
"""Block till current work is done.""" """Block till current work is done."""
self._work_queue.join() self._work_queue.join()

154
homeassistant/util/async.py Normal file
View file

@ -0,0 +1,154 @@
"""Asyncio backports for Python 3.4.3 compatibility."""
import concurrent.futures
from asyncio import coroutines
from asyncio.futures import Future
try:
from asyncio import ensure_future
except ImportError:
# Python 3.4.3 and earlier has this as async
# pylint: disable=unused-import
from asyncio import async
ensure_future = async
def _set_result_unless_cancelled(fut, result):
"""Helper setting the result only if the future was not cancelled."""
if fut.cancelled():
return
fut.set_result(result)
def _set_concurrent_future_state(concurr, source):
"""Copy state from a future to a concurrent.futures.Future."""
assert source.done()
if source.cancelled():
concurr.cancel()
if not concurr.set_running_or_notify_cancel():
return
exception = source.exception()
if exception is not None:
concurr.set_exception(exception)
else:
result = source.result()
concurr.set_result(result)
def _copy_future_state(source, dest):
"""Internal helper to copy state from another Future.
The other Future may be a concurrent.futures.Future.
"""
assert source.done()
if dest.cancelled():
return
assert not dest.done()
if source.cancelled():
dest.cancel()
else:
exception = source.exception()
if exception is not None:
dest.set_exception(exception)
else:
result = source.result()
dest.set_result(result)
def _chain_future(source, destination):
"""Chain two futures so that when one completes, so does the other.
The result (or exception) of source will be copied to destination.
If destination is cancelled, source gets cancelled too.
Compatible with both asyncio.Future and concurrent.futures.Future.
"""
if not isinstance(source, (Future, concurrent.futures.Future)):
raise TypeError('A future is required for source argument')
if not isinstance(destination, (Future, concurrent.futures.Future)):
raise TypeError('A future is required for destination argument')
# pylint: disable=protected-access
source_loop = source._loop if isinstance(source, Future) else None
dest_loop = destination._loop if isinstance(destination, Future) else None
def _set_state(future, other):
if isinstance(future, Future):
_copy_future_state(other, future)
else:
_set_concurrent_future_state(future, other)
def _call_check_cancel(destination):
if destination.cancelled():
if source_loop is None or source_loop is dest_loop:
source.cancel()
else:
source_loop.call_soon_threadsafe(source.cancel)
def _call_set_state(source):
if dest_loop is None or dest_loop is source_loop:
_set_state(destination, source)
else:
dest_loop.call_soon_threadsafe(_set_state, destination, source)
destination.add_done_callback(_call_check_cancel)
source.add_done_callback(_call_set_state)
def run_coroutine_threadsafe(coro, loop):
"""Submit a coroutine object to a given event loop.
Return a concurrent.futures.Future to access the result.
"""
if not coroutines.iscoroutine(coro):
raise TypeError('A coroutine object is required')
future = concurrent.futures.Future()
def callback():
"""Callback to call the coroutine."""
try:
# pylint: disable=deprecated-method
_chain_future(ensure_future(coro, loop=loop), future)
except Exception as exc:
if future.set_running_or_notify_cancel():
future.set_exception(exc)
raise
loop.call_soon_threadsafe(callback)
return future
def fire_coroutine_threadsafe(coro, loop):
"""Submit a coroutine object to a given event loop.
This method does not provide a way to retrieve the result and
is intended for fire-and-forget use. This reduces the
work involved to fire the function on the loop.
"""
if not coroutines.iscoroutine(coro):
raise TypeError('A coroutine object is required: %s' % coro)
def callback():
"""Callback to fire coroutine."""
# pylint: disable=deprecated-method
ensure_future(coro, loop=loop)
loop.call_soon_threadsafe(callback)
return
def run_callback_threadsafe(loop, callback, *args):
"""Submit a callback object to a given event loop.
Return a concurrent.futures.Future to access the result.
"""
future = concurrent.futures.Future()
def run_callback():
"""Run callback and store result."""
try:
future.set_result(callback(*args))
except Exception as exc:
if future.set_running_or_notify_cancel():
future.set_exception(exc)
raise
loop.call_soon_threadsafe(run_callback)
return future

View file

@ -1,10 +1,12 @@
"""Test the helper method for writing tests.""" """Test the helper method for writing tests."""
import asyncio
import os import os
from datetime import timedelta from datetime import timedelta
from unittest import mock from unittest import mock
from unittest.mock import patch from unittest.mock import patch
from io import StringIO from io import StringIO
import logging import logging
import threading
from homeassistant import core as ha, loader from homeassistant import core as ha, loader
from homeassistant.bootstrap import setup_component from homeassistant.bootstrap import setup_component
@ -29,11 +31,13 @@ def get_test_config_dir(*add_path):
def get_test_home_assistant(num_threads=None): def get_test_home_assistant(num_threads=None):
"""Return a Home Assistant object pointing at test config dir.""" """Return a Home Assistant object pointing at test config dir."""
loop = asyncio.new_event_loop()
if num_threads: if num_threads:
orig_num_threads = ha.MIN_WORKER_THREAD orig_num_threads = ha.MIN_WORKER_THREAD
ha.MIN_WORKER_THREAD = num_threads ha.MIN_WORKER_THREAD = num_threads
hass = ha.HomeAssistant() hass = ha.HomeAssistant(loop)
if num_threads: if num_threads:
ha.MIN_WORKER_THREAD = orig_num_threads ha.MIN_WORKER_THREAD = orig_num_threads
@ -49,6 +53,26 @@ def get_test_home_assistant(num_threads=None):
if 'custom_components.test' not in loader.AVAILABLE_COMPONENTS: if 'custom_components.test' not in loader.AVAILABLE_COMPONENTS:
loader.prepare(hass) loader.prepare(hass)
# FIXME should not be a daemon. Means hass.stop() not called in teardown
threading.Thread(name="LoopThread", target=loop.run_forever,
daemon=True).start()
orig_start = hass.start
@asyncio.coroutine
def fake_stop():
yield None
def start_hass():
"""Helper to start hass."""
with patch.object(hass.loop, 'run_forever', return_value=None):
with patch.object(hass, 'async_stop', return_value=fake_stop()):
with patch.object(ha, 'create_timer', return_value=None):
orig_start()
hass.block_till_done()
hass.start = start_hass
return hass return hass

View file

@ -42,7 +42,7 @@ class TestAlarmControlPanelManual(unittest.TestCase):
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
alarm_control_panel.alarm_arm_home(self.hass, CODE) alarm_control_panel.alarm_arm_home(self.hass, CODE)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_ARMED_HOME, self.assertEqual(STATE_ALARM_ARMED_HOME,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
@ -64,7 +64,7 @@ class TestAlarmControlPanelManual(unittest.TestCase):
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
alarm_control_panel.alarm_arm_home(self.hass, CODE, entity_id) alarm_control_panel.alarm_arm_home(self.hass, CODE, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_PENDING, self.assertEqual(STATE_ALARM_PENDING,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
@ -73,7 +73,7 @@ class TestAlarmControlPanelManual(unittest.TestCase):
with patch(('homeassistant.components.alarm_control_panel.manual.' with patch(('homeassistant.components.alarm_control_panel.manual.'
'dt_util.utcnow'), return_value=future): 'dt_util.utcnow'), return_value=future):
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_ARMED_HOME, self.assertEqual(STATE_ALARM_ARMED_HOME,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
@ -95,7 +95,7 @@ class TestAlarmControlPanelManual(unittest.TestCase):
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
alarm_control_panel.alarm_arm_home(self.hass, CODE + '2') alarm_control_panel.alarm_arm_home(self.hass, CODE + '2')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_DISARMED, self.assertEqual(STATE_ALARM_DISARMED,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
@ -117,7 +117,7 @@ class TestAlarmControlPanelManual(unittest.TestCase):
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
alarm_control_panel.alarm_arm_away(self.hass, CODE, entity_id) alarm_control_panel.alarm_arm_away(self.hass, CODE, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_ARMED_AWAY, self.assertEqual(STATE_ALARM_ARMED_AWAY,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
@ -139,7 +139,7 @@ class TestAlarmControlPanelManual(unittest.TestCase):
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
alarm_control_panel.alarm_arm_away(self.hass, CODE) alarm_control_panel.alarm_arm_away(self.hass, CODE)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_PENDING, self.assertEqual(STATE_ALARM_PENDING,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
@ -148,7 +148,7 @@ class TestAlarmControlPanelManual(unittest.TestCase):
with patch(('homeassistant.components.alarm_control_panel.manual.' with patch(('homeassistant.components.alarm_control_panel.manual.'
'dt_util.utcnow'), return_value=future): 'dt_util.utcnow'), return_value=future):
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_ARMED_AWAY, self.assertEqual(STATE_ALARM_ARMED_AWAY,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
@ -170,7 +170,7 @@ class TestAlarmControlPanelManual(unittest.TestCase):
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
alarm_control_panel.alarm_arm_away(self.hass, CODE + '2') alarm_control_panel.alarm_arm_away(self.hass, CODE + '2')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_DISARMED, self.assertEqual(STATE_ALARM_DISARMED,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
@ -191,7 +191,7 @@ class TestAlarmControlPanelManual(unittest.TestCase):
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
alarm_control_panel.alarm_trigger(self.hass, entity_id=entity_id) alarm_control_panel.alarm_trigger(self.hass, entity_id=entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_TRIGGERED, self.assertEqual(STATE_ALARM_TRIGGERED,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
@ -213,7 +213,7 @@ class TestAlarmControlPanelManual(unittest.TestCase):
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
alarm_control_panel.alarm_trigger(self.hass) alarm_control_panel.alarm_trigger(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_PENDING, self.assertEqual(STATE_ALARM_PENDING,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
@ -222,7 +222,7 @@ class TestAlarmControlPanelManual(unittest.TestCase):
with patch(('homeassistant.components.alarm_control_panel.manual.' with patch(('homeassistant.components.alarm_control_panel.manual.'
'dt_util.utcnow'), return_value=future): 'dt_util.utcnow'), return_value=future):
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_TRIGGERED, self.assertEqual(STATE_ALARM_TRIGGERED,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
@ -231,7 +231,7 @@ class TestAlarmControlPanelManual(unittest.TestCase):
with patch(('homeassistant.components.alarm_control_panel.manual.' with patch(('homeassistant.components.alarm_control_panel.manual.'
'dt_util.utcnow'), return_value=future): 'dt_util.utcnow'), return_value=future):
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_DISARMED, self.assertEqual(STATE_ALARM_DISARMED,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
@ -253,7 +253,7 @@ class TestAlarmControlPanelManual(unittest.TestCase):
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
alarm_control_panel.alarm_trigger(self.hass, entity_id=entity_id) alarm_control_panel.alarm_trigger(self.hass, entity_id=entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_TRIGGERED, self.assertEqual(STATE_ALARM_TRIGGERED,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
@ -262,7 +262,7 @@ class TestAlarmControlPanelManual(unittest.TestCase):
with patch(('homeassistant.components.alarm_control_panel.manual.' with patch(('homeassistant.components.alarm_control_panel.manual.'
'dt_util.utcnow'), return_value=future): 'dt_util.utcnow'), return_value=future):
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_DISARMED, self.assertEqual(STATE_ALARM_DISARMED,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
@ -283,13 +283,13 @@ class TestAlarmControlPanelManual(unittest.TestCase):
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
alarm_control_panel.alarm_trigger(self.hass) alarm_control_panel.alarm_trigger(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_PENDING, self.assertEqual(STATE_ALARM_PENDING,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
alarm_control_panel.alarm_disarm(self.hass, entity_id=entity_id) alarm_control_panel.alarm_disarm(self.hass, entity_id=entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_DISARMED, self.assertEqual(STATE_ALARM_DISARMED,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
@ -298,7 +298,7 @@ class TestAlarmControlPanelManual(unittest.TestCase):
with patch(('homeassistant.components.alarm_control_panel.manual.' with patch(('homeassistant.components.alarm_control_panel.manual.'
'dt_util.utcnow'), return_value=future): 'dt_util.utcnow'), return_value=future):
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_DISARMED, self.assertEqual(STATE_ALARM_DISARMED,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
@ -320,13 +320,13 @@ class TestAlarmControlPanelManual(unittest.TestCase):
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
alarm_control_panel.alarm_trigger(self.hass) alarm_control_panel.alarm_trigger(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_PENDING, self.assertEqual(STATE_ALARM_PENDING,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
alarm_control_panel.alarm_disarm(self.hass, entity_id=entity_id) alarm_control_panel.alarm_disarm(self.hass, entity_id=entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_PENDING, self.assertEqual(STATE_ALARM_PENDING,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
@ -335,7 +335,7 @@ class TestAlarmControlPanelManual(unittest.TestCase):
with patch(('homeassistant.components.alarm_control_panel.manual.' with patch(('homeassistant.components.alarm_control_panel.manual.'
'dt_util.utcnow'), return_value=future): 'dt_util.utcnow'), return_value=future):
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ALARM_TRIGGERED, self.assertEqual(STATE_ALARM_TRIGGERED,
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)

View file

@ -66,7 +66,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase):
STATE_ALARM_ARMED_AWAY, STATE_ALARM_PENDING, STATE_ALARM_ARMED_AWAY, STATE_ALARM_PENDING,
STATE_ALARM_TRIGGERED): STATE_ALARM_TRIGGERED):
fire_mqtt_message(self.hass, 'alarm/state', state) fire_mqtt_message(self.hass, 'alarm/state', state)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(state, self.hass.states.get(entity_id).state) self.assertEqual(state, self.hass.states.get(entity_id).state)
def test_ignore_update_state_if_unknown_via_state_topic(self): def test_ignore_update_state_if_unknown_via_state_topic(self):
@ -87,7 +87,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase):
self.hass.states.get(entity_id).state) self.hass.states.get(entity_id).state)
fire_mqtt_message(self.hass, 'alarm/state', 'unsupported state') fire_mqtt_message(self.hass, 'alarm/state', 'unsupported state')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_UNKNOWN, self.hass.states.get(entity_id).state) self.assertEqual(STATE_UNKNOWN, self.hass.states.get(entity_id).state)
def test_arm_home_publishes_mqtt(self): def test_arm_home_publishes_mqtt(self):
@ -103,7 +103,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase):
}) })
alarm_control_panel.alarm_arm_home(self.hass) alarm_control_panel.alarm_arm_home(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('alarm/command', 'ARM_HOME', 0, False), self.assertEqual(('alarm/command', 'ARM_HOME', 0, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -122,7 +122,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase):
call_count = self.mock_publish.call_count call_count = self.mock_publish.call_count
alarm_control_panel.alarm_arm_home(self.hass, 'abcd') alarm_control_panel.alarm_arm_home(self.hass, 'abcd')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(call_count, self.mock_publish.call_count) self.assertEqual(call_count, self.mock_publish.call_count)
def test_arm_away_publishes_mqtt(self): def test_arm_away_publishes_mqtt(self):
@ -138,7 +138,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase):
}) })
alarm_control_panel.alarm_arm_away(self.hass) alarm_control_panel.alarm_arm_away(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('alarm/command', 'ARM_AWAY', 0, False), self.assertEqual(('alarm/command', 'ARM_AWAY', 0, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -157,7 +157,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase):
call_count = self.mock_publish.call_count call_count = self.mock_publish.call_count
alarm_control_panel.alarm_arm_away(self.hass, 'abcd') alarm_control_panel.alarm_arm_away(self.hass, 'abcd')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(call_count, self.mock_publish.call_count) self.assertEqual(call_count, self.mock_publish.call_count)
def test_disarm_publishes_mqtt(self): def test_disarm_publishes_mqtt(self):
@ -173,7 +173,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase):
}) })
alarm_control_panel.alarm_disarm(self.hass) alarm_control_panel.alarm_disarm(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('alarm/command', 'DISARM', 0, False), self.assertEqual(('alarm/command', 'DISARM', 0, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -192,5 +192,5 @@ class TestAlarmControlPanelMQTT(unittest.TestCase):
call_count = self.mock_publish.call_count call_count = self.mock_publish.call_count
alarm_control_panel.alarm_disarm(self.hass, 'abcd') alarm_control_panel.alarm_disarm(self.hass, 'abcd')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(call_count, self.mock_publish.call_count) self.assertEqual(call_count, self.mock_publish.call_count)

View file

@ -41,14 +41,14 @@ class TestAutomationEvent(unittest.TestCase):
}) })
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
automation.turn_off(self.hass) automation.turn_off(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_on_event_with_data(self): def test_if_fires_on_event_with_data(self):
@ -68,7 +68,7 @@ class TestAutomationEvent(unittest.TestCase):
self.hass.bus.fire('test_event', {'some_attr': 'some_value', self.hass.bus.fire('test_event', {'some_attr': 'some_value',
'another': 'value'}) 'another': 'value'})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_not_fires_if_event_data_not_matches(self): def test_if_not_fires_if_event_data_not_matches(self):
@ -87,5 +87,5 @@ class TestAutomationEvent(unittest.TestCase):
}) })
self.hass.bus.fire('test_event', {'some_attr': 'some_other_value'}) self.hass.bus.fire('test_event', {'some_attr': 'some_other_value'})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))

View file

@ -68,7 +68,7 @@ class TestAutomation(unittest.TestCase):
with patch('homeassistant.components.automation.utcnow', with patch('homeassistant.components.automation.utcnow',
return_value=time): return_value=time):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 1 assert len(self.calls) == 1
assert 'event - test_event' == self.calls[0].data['some'] assert 'event - test_event' == self.calls[0].data['some']
state = self.hass.states.get('automation.hello') state = self.hass.states.get('automation.hello')
@ -91,7 +91,7 @@ class TestAutomation(unittest.TestCase):
}) })
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.assertEqual(['hello.world'], self.assertEqual(['hello.world'],
self.calls[0].data.get(ATTR_ENTITY_ID)) self.calls[0].data.get(ATTR_ENTITY_ID))
@ -112,7 +112,7 @@ class TestAutomation(unittest.TestCase):
}) })
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.assertEqual(['hello.world', 'hello.world2'], self.assertEqual(['hello.world', 'hello.world2'],
self.calls[0].data.get(ATTR_ENTITY_ID)) self.calls[0].data.get(ATTR_ENTITY_ID))
@ -138,10 +138,10 @@ class TestAutomation(unittest.TestCase):
}) })
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.hass.states.set('test.entity', 'hello') self.hass.states.set('test.entity', 'hello')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(self.calls)) self.assertEqual(2, len(self.calls))
def test_two_conditions_with_and(self): def test_two_conditions_with_and(self):
@ -175,17 +175,17 @@ class TestAutomation(unittest.TestCase):
self.hass.states.set(entity_id, 100) self.hass.states.set(entity_id, 100)
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.hass.states.set(entity_id, 101) self.hass.states.set(entity_id, 101)
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.hass.states.set(entity_id, 151) self.hass.states.set(entity_id, 151)
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_two_conditions_with_or(self): def test_two_conditions_with_or(self):
@ -220,17 +220,17 @@ class TestAutomation(unittest.TestCase):
self.hass.states.set(entity_id, 200) self.hass.states.set(entity_id, 200)
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.hass.states.set(entity_id, 100) self.hass.states.set(entity_id, 100)
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(self.calls)) self.assertEqual(2, len(self.calls))
self.hass.states.set(entity_id, 250) self.hass.states.set(entity_id, 250)
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(self.calls)) self.assertEqual(2, len(self.calls))
def test_using_trigger_as_condition(self): def test_using_trigger_as_condition(self):
@ -259,19 +259,19 @@ class TestAutomation(unittest.TestCase):
}) })
self.hass.states.set(entity_id, 100) self.hass.states.set(entity_id, 100)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.hass.states.set(entity_id, 120) self.hass.states.set(entity_id, 120)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.hass.states.set(entity_id, 100) self.hass.states.set(entity_id, 100)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(self.calls)) self.assertEqual(2, len(self.calls))
self.hass.states.set(entity_id, 151) self.hass.states.set(entity_id, 151)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(self.calls)) self.assertEqual(2, len(self.calls))
def test_using_trigger_as_condition_with_invalid_condition(self): def test_using_trigger_as_condition_with_invalid_condition(self):
@ -299,7 +299,7 @@ class TestAutomation(unittest.TestCase):
}) })
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_automation_list_setting(self): def test_automation_list_setting(self):
@ -326,11 +326,11 @@ class TestAutomation(unittest.TestCase):
})) }))
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.hass.bus.fire('test_event_2') self.hass.bus.fire('test_event_2')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(self.calls)) self.assertEqual(2, len(self.calls))
def test_automation_calling_two_actions(self): def test_automation_calling_two_actions(self):
@ -353,7 +353,7 @@ class TestAutomation(unittest.TestCase):
})) }))
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 2 assert len(self.calls) == 2
assert self.calls[0].data['position'] == 0 assert self.calls[0].data['position'] == 0
@ -383,37 +383,37 @@ class TestAutomation(unittest.TestCase):
assert automation.is_on(self.hass, entity_id) assert automation.is_on(self.hass, entity_id)
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 1 assert len(self.calls) == 1
automation.turn_off(self.hass, entity_id) automation.turn_off(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert not automation.is_on(self.hass, entity_id) assert not automation.is_on(self.hass, entity_id)
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 1 assert len(self.calls) == 1
automation.toggle(self.hass, entity_id) automation.toggle(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert automation.is_on(self.hass, entity_id) assert automation.is_on(self.hass, entity_id)
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 2 assert len(self.calls) == 2
automation.trigger(self.hass, entity_id) automation.trigger(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 3 assert len(self.calls) == 3
automation.turn_off(self.hass, entity_id) automation.turn_off(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
automation.trigger(self.hass, entity_id) automation.trigger(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 4 assert len(self.calls) == 4
automation.turn_on(self.hass, entity_id) automation.turn_on(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert automation.is_on(self.hass, entity_id) assert automation.is_on(self.hass, entity_id)
@patch('homeassistant.config.load_yaml_config_file', return_value={ @patch('homeassistant.config.load_yaml_config_file', return_value={
@ -455,13 +455,13 @@ class TestAutomation(unittest.TestCase):
assert listeners.get('test_event2') is None assert listeners.get('test_event2') is None
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 1 assert len(self.calls) == 1
assert self.calls[0].data.get('event') == 'test_event' assert self.calls[0].data.get('event') == 'test_event'
automation.reload(self.hass) automation.reload(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert self.hass.states.get('automation.hello') is None assert self.hass.states.get('automation.hello') is None
assert self.hass.states.get('automation.bye') is not None assert self.hass.states.get('automation.bye') is not None
@ -470,11 +470,11 @@ class TestAutomation(unittest.TestCase):
assert listeners.get('test_event2') == 1 assert listeners.get('test_event2') == 1
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 1 assert len(self.calls) == 1
self.hass.bus.fire('test_event2') self.hass.bus.fire('test_event2')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 2 assert len(self.calls) == 2
assert self.calls[1].data.get('event') == 'test_event2' assert self.calls[1].data.get('event') == 'test_event2'
@ -501,18 +501,18 @@ class TestAutomation(unittest.TestCase):
assert self.hass.states.get('automation.hello') is not None assert self.hass.states.get('automation.hello') is not None
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 1 assert len(self.calls) == 1
assert self.calls[0].data.get('event') == 'test_event' assert self.calls[0].data.get('event') == 'test_event'
automation.reload(self.hass) automation.reload(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert self.hass.states.get('automation.hello') is not None assert self.hass.states.get('automation.hello') is not None
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 2 assert len(self.calls) == 2
def test_reload_config_handles_load_fails(self): def test_reload_config_handles_load_fails(self):
@ -535,7 +535,7 @@ class TestAutomation(unittest.TestCase):
assert self.hass.states.get('automation.hello') is not None assert self.hass.states.get('automation.hello') is not None
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 1 assert len(self.calls) == 1
assert self.calls[0].data.get('event') == 'test_event' assert self.calls[0].data.get('event') == 'test_event'
@ -543,10 +543,10 @@ class TestAutomation(unittest.TestCase):
with patch('homeassistant.config.load_yaml_config_file', with patch('homeassistant.config.load_yaml_config_file',
side_effect=HomeAssistantError('bla')): side_effect=HomeAssistantError('bla')):
automation.reload(self.hass) automation.reload(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert self.hass.states.get('automation.hello') is not None assert self.hass.states.get('automation.hello') is not None
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 2 assert len(self.calls) == 2

View file

@ -45,15 +45,15 @@ class TestAutomationMQTT(unittest.TestCase):
}) })
fire_mqtt_message(self.hass, 'test-topic', 'test_payload') fire_mqtt_message(self.hass, 'test-topic', 'test_payload')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.assertEqual('mqtt - test-topic - test_payload', self.assertEqual('mqtt - test-topic - test_payload',
self.calls[0].data['some']) self.calls[0].data['some'])
automation.turn_off(self.hass) automation.turn_off(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_mqtt_message(self.hass, 'test-topic', 'test_payload') fire_mqtt_message(self.hass, 'test-topic', 'test_payload')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_on_topic_and_payload_match(self): def test_if_fires_on_topic_and_payload_match(self):
@ -72,7 +72,7 @@ class TestAutomationMQTT(unittest.TestCase):
}) })
fire_mqtt_message(self.hass, 'test-topic', 'hello') fire_mqtt_message(self.hass, 'test-topic', 'hello')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_not_fires_on_topic_but_no_payload_match(self): def test_if_not_fires_on_topic_but_no_payload_match(self):
@ -91,5 +91,5 @@ class TestAutomationMQTT(unittest.TestCase):
}) })
fire_mqtt_message(self.hass, 'test-topic', 'no-hello') fire_mqtt_message(self.hass, 'test-topic', 'no-hello')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))

View file

@ -42,21 +42,21 @@ class TestAutomationNumericState(unittest.TestCase):
}) })
# 9 is below 10 # 9 is below 10
self.hass.states.set('test.entity', 9) self.hass.states.set('test.entity', 9)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
# Set above 12 so the automation will fire again # Set above 12 so the automation will fire again
self.hass.states.set('test.entity', 12) self.hass.states.set('test.entity', 12)
automation.turn_off(self.hass) automation.turn_off(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set('test.entity', 9) self.hass.states.set('test.entity', 9)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_on_entity_change_over_to_below(self): def test_if_fires_on_entity_change_over_to_below(self):
""""Test the firing with changed entity.""" """"Test the firing with changed entity."""
self.hass.states.set('test.entity', 11) self.hass.states.set('test.entity', 11)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert _setup_component(self.hass, automation.DOMAIN, { assert _setup_component(self.hass, automation.DOMAIN, {
automation.DOMAIN: { automation.DOMAIN: {
@ -73,13 +73,13 @@ class TestAutomationNumericState(unittest.TestCase):
# 9 is below 10 # 9 is below 10
self.hass.states.set('test.entity', 9) self.hass.states.set('test.entity', 9)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_not_fires_on_entity_change_below_to_below(self): def test_if_not_fires_on_entity_change_below_to_below(self):
""""Test the firing with changed entity.""" """"Test the firing with changed entity."""
self.hass.states.set('test.entity', 9) self.hass.states.set('test.entity', 9)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert _setup_component(self.hass, automation.DOMAIN, { assert _setup_component(self.hass, automation.DOMAIN, {
automation.DOMAIN: { automation.DOMAIN: {
@ -96,7 +96,7 @@ class TestAutomationNumericState(unittest.TestCase):
# 9 is below 10 so this should not fire again # 9 is below 10 so this should not fire again
self.hass.states.set('test.entity', 8) self.hass.states.set('test.entity', 8)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_fires_on_entity_change_above(self): def test_if_fires_on_entity_change_above(self):
@ -115,14 +115,14 @@ class TestAutomationNumericState(unittest.TestCase):
}) })
# 11 is above 10 # 11 is above 10
self.hass.states.set('test.entity', 11) self.hass.states.set('test.entity', 11)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_on_entity_change_below_to_above(self): def test_if_fires_on_entity_change_below_to_above(self):
""""Test the firing with changed entity.""" """"Test the firing with changed entity."""
# set initial state # set initial state
self.hass.states.set('test.entity', 9) self.hass.states.set('test.entity', 9)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert _setup_component(self.hass, automation.DOMAIN, { assert _setup_component(self.hass, automation.DOMAIN, {
automation.DOMAIN: { automation.DOMAIN: {
@ -139,14 +139,14 @@ class TestAutomationNumericState(unittest.TestCase):
# 11 is above 10 and 9 is below # 11 is above 10 and 9 is below
self.hass.states.set('test.entity', 11) self.hass.states.set('test.entity', 11)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_not_fires_on_entity_change_above_to_above(self): def test_if_not_fires_on_entity_change_above_to_above(self):
""""Test the firing with changed entity.""" """"Test the firing with changed entity."""
# set initial state # set initial state
self.hass.states.set('test.entity', 11) self.hass.states.set('test.entity', 11)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert _setup_component(self.hass, automation.DOMAIN, { assert _setup_component(self.hass, automation.DOMAIN, {
automation.DOMAIN: { automation.DOMAIN: {
@ -163,7 +163,7 @@ class TestAutomationNumericState(unittest.TestCase):
# 11 is above 10 so this should fire again # 11 is above 10 so this should fire again
self.hass.states.set('test.entity', 12) self.hass.states.set('test.entity', 12)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_fires_on_entity_change_below_range(self): def test_if_fires_on_entity_change_below_range(self):
@ -183,7 +183,7 @@ class TestAutomationNumericState(unittest.TestCase):
}) })
# 9 is below 10 # 9 is below 10
self.hass.states.set('test.entity', 9) self.hass.states.set('test.entity', 9)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_on_entity_change_below_above_range(self): def test_if_fires_on_entity_change_below_above_range(self):
@ -203,13 +203,13 @@ class TestAutomationNumericState(unittest.TestCase):
}) })
# 4 is below 5 # 4 is below 5
self.hass.states.set('test.entity', 4) self.hass.states.set('test.entity', 4)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_fires_on_entity_change_over_to_below_range(self): def test_if_fires_on_entity_change_over_to_below_range(self):
""""Test the firing with changed entity.""" """"Test the firing with changed entity."""
self.hass.states.set('test.entity', 11) self.hass.states.set('test.entity', 11)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert _setup_component(self.hass, automation.DOMAIN, { assert _setup_component(self.hass, automation.DOMAIN, {
automation.DOMAIN: { automation.DOMAIN: {
@ -227,13 +227,13 @@ class TestAutomationNumericState(unittest.TestCase):
# 9 is below 10 # 9 is below 10
self.hass.states.set('test.entity', 9) self.hass.states.set('test.entity', 9)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_on_entity_change_over_to_below_above_range(self): def test_if_fires_on_entity_change_over_to_below_above_range(self):
""""Test the firing with changed entity.""" """"Test the firing with changed entity."""
self.hass.states.set('test.entity', 11) self.hass.states.set('test.entity', 11)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert _setup_component(self.hass, automation.DOMAIN, { assert _setup_component(self.hass, automation.DOMAIN, {
automation.DOMAIN: { automation.DOMAIN: {
@ -251,7 +251,7 @@ class TestAutomationNumericState(unittest.TestCase):
# 4 is below 5 so it should not fire # 4 is below 5 so it should not fire
self.hass.states.set('test.entity', 4) self.hass.states.set('test.entity', 4)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_not_fires_if_entity_not_match(self): def test_if_not_fires_if_entity_not_match(self):
@ -270,7 +270,7 @@ class TestAutomationNumericState(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 11) self.hass.states.set('test.entity', 11)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_fires_on_entity_change_below_with_attribute(self): def test_if_fires_on_entity_change_below_with_attribute(self):
@ -289,7 +289,7 @@ class TestAutomationNumericState(unittest.TestCase):
}) })
# 9 is below 10 # 9 is below 10
self.hass.states.set('test.entity', 9, {'test_attribute': 11}) self.hass.states.set('test.entity', 9, {'test_attribute': 11})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_not_fires_on_entity_change_not_below_with_attribute(self): def test_if_not_fires_on_entity_change_not_below_with_attribute(self):
@ -308,7 +308,7 @@ class TestAutomationNumericState(unittest.TestCase):
}) })
# 11 is not below 10 # 11 is not below 10
self.hass.states.set('test.entity', 11, {'test_attribute': 9}) self.hass.states.set('test.entity', 11, {'test_attribute': 9})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_fires_on_attribute_change_with_attribute_below(self): def test_if_fires_on_attribute_change_with_attribute_below(self):
@ -328,7 +328,7 @@ class TestAutomationNumericState(unittest.TestCase):
}) })
# 9 is below 10 # 9 is below 10
self.hass.states.set('test.entity', 'entity', {'test_attribute': 9}) self.hass.states.set('test.entity', 'entity', {'test_attribute': 9})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_not_fires_on_attribute_change_with_attribute_not_below(self): def test_if_not_fires_on_attribute_change_with_attribute_not_below(self):
@ -348,7 +348,7 @@ class TestAutomationNumericState(unittest.TestCase):
}) })
# 11 is not below 10 # 11 is not below 10
self.hass.states.set('test.entity', 'entity', {'test_attribute': 11}) self.hass.states.set('test.entity', 'entity', {'test_attribute': 11})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_not_fires_on_entity_change_with_attribute_below(self): def test_if_not_fires_on_entity_change_with_attribute_below(self):
@ -368,7 +368,7 @@ class TestAutomationNumericState(unittest.TestCase):
}) })
# 11 is not below 10, entity state value should not be tested # 11 is not below 10, entity state value should not be tested
self.hass.states.set('test.entity', '9', {'test_attribute': 11}) self.hass.states.set('test.entity', '9', {'test_attribute': 11})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_not_fires_on_entity_change_with_not_attribute_below(self): def test_if_not_fires_on_entity_change_with_not_attribute_below(self):
@ -388,7 +388,7 @@ class TestAutomationNumericState(unittest.TestCase):
}) })
# 11 is not below 10, entity state value should not be tested # 11 is not below 10, entity state value should not be tested
self.hass.states.set('test.entity', 'entity') self.hass.states.set('test.entity', 'entity')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_fires_on_attr_change_with_attribute_below_and_multiple_attr(self): def test_fires_on_attr_change_with_attribute_below_and_multiple_attr(self):
@ -409,7 +409,7 @@ class TestAutomationNumericState(unittest.TestCase):
# 9 is not below 10 # 9 is not below 10
self.hass.states.set('test.entity', 'entity', self.hass.states.set('test.entity', 'entity',
{'test_attribute': 9, 'not_test_attribute': 11}) {'test_attribute': 9, 'not_test_attribute': 11})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_template_list(self): def test_template_list(self):
@ -431,7 +431,7 @@ class TestAutomationNumericState(unittest.TestCase):
# 3 is below 10 # 3 is below 10
self.hass.states.set('test.entity', 'entity', self.hass.states.set('test.entity', 'entity',
{'test_attribute': [11, 15, 3]}) {'test_attribute': [11, 15, 3]})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_template_string(self): def test_template_string(self):
@ -457,10 +457,10 @@ class TestAutomationNumericState(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'test state 1', self.hass.states.set('test.entity', 'test state 1',
{'test_attribute': '1.2'}) {'test_attribute': '1.2'})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set('test.entity', 'test state 2', self.hass.states.set('test.entity', 'test state 2',
{'test_attribute': '0.9'}) {'test_attribute': '0.9'})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.assertEqual( self.assertEqual(
'numeric_state - test.entity - 10.0 - None - test state 1 - ' 'numeric_state - test.entity - 10.0 - None - test state 1 - '
@ -485,7 +485,7 @@ class TestAutomationNumericState(unittest.TestCase):
# 11 is not below 10 # 11 is not below 10
self.hass.states.set('test.entity', 'entity', self.hass.states.set('test.entity', 'entity',
{'test_attribute': 11, 'not_test_attribute': 9}) {'test_attribute': 11, 'not_test_attribute': 9})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_action(self): def test_if_action(self):
@ -512,18 +512,18 @@ class TestAutomationNumericState(unittest.TestCase):
self.hass.states.set(entity_id, test_state) self.hass.states.set(entity_id, test_state)
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.hass.states.set(entity_id, test_state - 1) self.hass.states.set(entity_id, test_state - 1)
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.hass.states.set(entity_id, test_state + 1) self.hass.states.set(entity_id, test_state + 1)
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(self.calls)) self.assertEqual(2, len(self.calls))

View file

@ -32,7 +32,7 @@ class TestAutomationState(unittest.TestCase):
def test_if_fires_on_entity_change(self): def test_if_fires_on_entity_change(self):
"""Test for firing on entity change.""" """Test for firing on entity change."""
self.hass.states.set('test.entity', 'hello') self.hass.states.set('test.entity', 'hello')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert _setup_component(self.hass, automation.DOMAIN, { assert _setup_component(self.hass, automation.DOMAIN, {
automation.DOMAIN: { automation.DOMAIN: {
@ -53,16 +53,16 @@ class TestAutomationState(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.assertEqual( self.assertEqual(
'state - test.entity - hello - world - None', 'state - test.entity - hello - world - None',
self.calls[0].data['some']) self.calls[0].data['some'])
automation.turn_off(self.hass) automation.turn_off(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set('test.entity', 'planet') self.hass.states.set('test.entity', 'planet')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_on_entity_change_with_from_filter(self): def test_if_fires_on_entity_change_with_from_filter(self):
@ -81,7 +81,7 @@ class TestAutomationState(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_on_entity_change_with_to_filter(self): def test_if_fires_on_entity_change_with_to_filter(self):
@ -100,7 +100,7 @@ class TestAutomationState(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_on_entity_change_with_state_filter(self): def test_if_fires_on_entity_change_with_state_filter(self):
@ -119,7 +119,7 @@ class TestAutomationState(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_on_entity_change_with_both_filters(self): def test_if_fires_on_entity_change_with_both_filters(self):
@ -139,7 +139,7 @@ class TestAutomationState(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_not_fires_if_to_filter_not_match(self): def test_if_not_fires_if_to_filter_not_match(self):
@ -159,7 +159,7 @@ class TestAutomationState(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'moon') self.hass.states.set('test.entity', 'moon')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_not_fires_if_from_filter_not_match(self): def test_if_not_fires_if_from_filter_not_match(self):
@ -181,7 +181,7 @@ class TestAutomationState(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_not_fires_if_entity_not_match(self): def test_if_not_fires_if_entity_not_match(self):
@ -199,7 +199,7 @@ class TestAutomationState(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_action(self): def test_if_action(self):
@ -225,13 +225,13 @@ class TestAutomationState(unittest.TestCase):
self.hass.states.set(entity_id, test_state) self.hass.states.set(entity_id, test_state)
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.hass.states.set(entity_id, test_state + 'something') self.hass.states.set(entity_id, test_state + 'something')
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
@ -315,11 +315,11 @@ class TestAutomationState(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set('test.entity', 'not_world') self.hass.states.set('test.entity', 'not_world')
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=10)) fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=10))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_fires_on_entity_change_with_for(self): def test_if_fires_on_entity_change_with_for(self):
@ -341,9 +341,9 @@ class TestAutomationState(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=10)) fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=10))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_on_for_condition(self): def test_if_fires_on_for_condition(self):
@ -373,13 +373,13 @@ class TestAutomationState(unittest.TestCase):
# not enough time has passed # not enough time has passed
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
# Time travel 10 secs into the future # Time travel 10 secs into the future
mock_utcnow.return_value = point2 mock_utcnow.return_value = point2
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fails_setup_for_without_time(self): def test_if_fails_setup_for_without_time(self):

View file

@ -55,19 +55,19 @@ class TestAutomationSun(unittest.TestCase):
}) })
automation.turn_off(self.hass) automation.turn_off(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_time_changed(self.hass, trigger_time) fire_time_changed(self.hass, trigger_time)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
with patch('homeassistant.util.dt.utcnow', with patch('homeassistant.util.dt.utcnow',
return_value=now): return_value=now):
automation.turn_on(self.hass) automation.turn_on(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_time_changed(self.hass, trigger_time) fire_time_changed(self.hass, trigger_time)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_sunrise_trigger(self): def test_sunrise_trigger(self):
@ -94,7 +94,7 @@ class TestAutomationSun(unittest.TestCase):
}) })
fire_time_changed(self.hass, trigger_time) fire_time_changed(self.hass, trigger_time)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_sunset_trigger_with_offset(self): def test_sunset_trigger_with_offset(self):
@ -127,7 +127,7 @@ class TestAutomationSun(unittest.TestCase):
}) })
fire_time_changed(self.hass, trigger_time) fire_time_changed(self.hass, trigger_time)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.assertEqual('sun - sunset - 0:30:00', self.calls[0].data['some']) self.assertEqual('sun - sunset - 0:30:00', self.calls[0].data['some'])
@ -156,7 +156,7 @@ class TestAutomationSun(unittest.TestCase):
}) })
fire_time_changed(self.hass, trigger_time) fire_time_changed(self.hass, trigger_time)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_action_before(self): def test_if_action_before(self):
@ -185,14 +185,14 @@ class TestAutomationSun(unittest.TestCase):
with patch('homeassistant.util.dt.now', with patch('homeassistant.util.dt.now',
return_value=now): return_value=now):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
now = datetime(2015, 9, 16, 10, tzinfo=dt_util.UTC) now = datetime(2015, 9, 16, 10, tzinfo=dt_util.UTC)
with patch('homeassistant.util.dt.now', with patch('homeassistant.util.dt.now',
return_value=now): return_value=now):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_action_after(self): def test_if_action_after(self):
@ -221,14 +221,14 @@ class TestAutomationSun(unittest.TestCase):
with patch('homeassistant.util.dt.now', with patch('homeassistant.util.dt.now',
return_value=now): return_value=now):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
now = datetime(2015, 9, 16, 15, tzinfo=dt_util.UTC) now = datetime(2015, 9, 16, 15, tzinfo=dt_util.UTC)
with patch('homeassistant.util.dt.now', with patch('homeassistant.util.dt.now',
return_value=now): return_value=now):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_action_before_with_offset(self): def test_if_action_before_with_offset(self):
@ -258,14 +258,14 @@ class TestAutomationSun(unittest.TestCase):
with patch('homeassistant.util.dt.now', with patch('homeassistant.util.dt.now',
return_value=now): return_value=now):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
now = datetime(2015, 9, 16, 15, tzinfo=dt_util.UTC) now = datetime(2015, 9, 16, 15, tzinfo=dt_util.UTC)
with patch('homeassistant.util.dt.now', with patch('homeassistant.util.dt.now',
return_value=now): return_value=now):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_action_after_with_offset(self): def test_if_action_after_with_offset(self):
@ -295,14 +295,14 @@ class TestAutomationSun(unittest.TestCase):
with patch('homeassistant.util.dt.now', with patch('homeassistant.util.dt.now',
return_value=now): return_value=now):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
now = datetime(2015, 9, 16, 15, tzinfo=dt_util.UTC) now = datetime(2015, 9, 16, 15, tzinfo=dt_util.UTC)
with patch('homeassistant.util.dt.now', with patch('homeassistant.util.dt.now',
return_value=now): return_value=now):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_action_before_and_after_during(self): def test_if_action_before_and_after_during(self):
@ -333,21 +333,21 @@ class TestAutomationSun(unittest.TestCase):
with patch('homeassistant.util.dt.now', with patch('homeassistant.util.dt.now',
return_value=now): return_value=now):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
now = datetime(2015, 9, 16, 15, 1, tzinfo=dt_util.UTC) now = datetime(2015, 9, 16, 15, 1, tzinfo=dt_util.UTC)
with patch('homeassistant.util.dt.now', with patch('homeassistant.util.dt.now',
return_value=now): return_value=now):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
now = datetime(2015, 9, 16, 12, tzinfo=dt_util.UTC) now = datetime(2015, 9, 16, 12, tzinfo=dt_util.UTC)
with patch('homeassistant.util.dt.now', with patch('homeassistant.util.dt.now',
return_value=now): return_value=now):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_action_after_different_tz(self): def test_if_action_after_different_tz(self):
@ -379,7 +379,7 @@ class TestAutomationSun(unittest.TestCase):
with patch('homeassistant.util.dt.now', with patch('homeassistant.util.dt.now',
return_value=now): return_value=now):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
# After # After
@ -387,5 +387,5 @@ class TestAutomationSun(unittest.TestCase):
with patch('homeassistant.util.dt.now', with patch('homeassistant.util.dt.now',
return_value=now): return_value=now):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))

View file

@ -42,14 +42,14 @@ class TestAutomationTemplate(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
automation.turn_off(self.hass) automation.turn_off(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set('test.entity', 'planet') self.hass.states.set('test.entity', 'planet')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_on_change_str(self): def test_if_fires_on_change_str(self):
@ -67,7 +67,7 @@ class TestAutomationTemplate(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_on_change_str_crazy(self): def test_if_fires_on_change_str_crazy(self):
@ -85,7 +85,7 @@ class TestAutomationTemplate(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_not_fires_on_change_bool(self): def test_if_not_fires_on_change_bool(self):
@ -103,7 +103,7 @@ class TestAutomationTemplate(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_not_fires_on_change_str(self): def test_if_not_fires_on_change_str(self):
@ -121,7 +121,7 @@ class TestAutomationTemplate(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_not_fires_on_change_str_crazy(self): def test_if_not_fires_on_change_str_crazy(self):
@ -139,7 +139,7 @@ class TestAutomationTemplate(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_fires_on_no_change(self): def test_if_fires_on_no_change(self):
@ -156,11 +156,11 @@ class TestAutomationTemplate(unittest.TestCase):
} }
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.calls = [] self.calls = []
self.hass.states.set('test.entity', 'hello') self.hass.states.set('test.entity', 'hello')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_fires_on_two_change(self): def test_if_fires_on_two_change(self):
@ -179,12 +179,12 @@ class TestAutomationTemplate(unittest.TestCase):
# Trigger once # Trigger once
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
# Trigger again # Trigger again
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_on_change_with_template(self): def test_if_fires_on_change_with_template(self):
@ -202,7 +202,7 @@ class TestAutomationTemplate(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_not_fires_on_change_with_template(self): def test_if_not_fires_on_change_with_template(self):
@ -219,11 +219,11 @@ class TestAutomationTemplate(unittest.TestCase):
} }
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.calls = [] self.calls = []
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 0 assert len(self.calls) == 0
def test_if_fires_on_change_with_template_advanced(self): def test_if_fires_on_change_with_template_advanced(self):
@ -250,11 +250,11 @@ class TestAutomationTemplate(unittest.TestCase):
} }
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.calls = [] self.calls = []
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.assertEqual( self.assertEqual(
'template - test.entity - hello - world', 'template - test.entity - hello - world',
@ -280,12 +280,12 @@ class TestAutomationTemplate(unittest.TestCase):
# Different state # Different state
self.hass.states.set('test.entity', 'worldz') self.hass.states.set('test.entity', 'worldz')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
# Different state # Different state
self.hass.states.set('test.entity', 'hello') self.hass.states.set('test.entity', 'hello')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_fires_on_change_with_template_2(self): def test_if_fires_on_change_with_template_2(self):
@ -303,31 +303,31 @@ class TestAutomationTemplate(unittest.TestCase):
} }
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.calls = [] self.calls = []
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 0 assert len(self.calls) == 0
self.hass.states.set('test.entity', 'home') self.hass.states.set('test.entity', 'home')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 1 assert len(self.calls) == 1
self.hass.states.set('test.entity', 'work') self.hass.states.set('test.entity', 'work')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 1 assert len(self.calls) == 1
self.hass.states.set('test.entity', 'not_home') self.hass.states.set('test.entity', 'not_home')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 1 assert len(self.calls) == 1
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 1 assert len(self.calls) == 1
self.hass.states.set('test.entity', 'home') self.hass.states.set('test.entity', 'home')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 2 assert len(self.calls) == 2
def test_if_action(self): def test_if_action(self):
@ -350,17 +350,17 @@ class TestAutomationTemplate(unittest.TestCase):
# Condition is not true yet # Condition is not true yet
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
# Change condition to true, but it shouldn't be triggered yet # Change condition to true, but it shouldn't be triggered yet
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
# Condition is true and event is triggered # Condition is true and event is triggered
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_on_change_with_bad_template(self): def test_if_fires_on_change_with_bad_template(self):
@ -392,5 +392,5 @@ class TestAutomationTemplate(unittest.TestCase):
}) })
self.hass.states.set('test.entity', 'world') self.hass.states.set('test.entity', 'world')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))

View file

@ -43,14 +43,14 @@ class TestAutomationTime(unittest.TestCase):
}) })
fire_time_changed(self.hass, dt_util.utcnow().replace(hour=0)) fire_time_changed(self.hass, dt_util.utcnow().replace(hour=0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
automation.turn_off(self.hass) automation.turn_off(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_time_changed(self.hass, dt_util.utcnow().replace(hour=0)) fire_time_changed(self.hass, dt_util.utcnow().replace(hour=0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_when_minute_matches(self): def test_if_fires_when_minute_matches(self):
@ -69,7 +69,7 @@ class TestAutomationTime(unittest.TestCase):
fire_time_changed(self.hass, dt_util.utcnow().replace(minute=0)) fire_time_changed(self.hass, dt_util.utcnow().replace(minute=0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_when_second_matches(self): def test_if_fires_when_second_matches(self):
@ -88,7 +88,7 @@ class TestAutomationTime(unittest.TestCase):
fire_time_changed(self.hass, dt_util.utcnow().replace(second=0)) fire_time_changed(self.hass, dt_util.utcnow().replace(second=0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_when_all_matches(self): def test_if_fires_when_all_matches(self):
@ -110,7 +110,7 @@ class TestAutomationTime(unittest.TestCase):
fire_time_changed(self.hass, dt_util.utcnow().replace( fire_time_changed(self.hass, dt_util.utcnow().replace(
hour=1, minute=2, second=3)) hour=1, minute=2, second=3))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_periodic_seconds(self): def test_if_fires_periodic_seconds(self):
@ -130,7 +130,7 @@ class TestAutomationTime(unittest.TestCase):
fire_time_changed(self.hass, dt_util.utcnow().replace( fire_time_changed(self.hass, dt_util.utcnow().replace(
hour=0, minute=0, second=2)) hour=0, minute=0, second=2))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_periodic_minutes(self): def test_if_fires_periodic_minutes(self):
@ -150,7 +150,7 @@ class TestAutomationTime(unittest.TestCase):
fire_time_changed(self.hass, dt_util.utcnow().replace( fire_time_changed(self.hass, dt_util.utcnow().replace(
hour=0, minute=2, second=0)) hour=0, minute=2, second=0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_periodic_hours(self): def test_if_fires_periodic_hours(self):
@ -170,7 +170,7 @@ class TestAutomationTime(unittest.TestCase):
fire_time_changed(self.hass, dt_util.utcnow().replace( fire_time_changed(self.hass, dt_util.utcnow().replace(
hour=2, minute=0, second=0)) hour=2, minute=0, second=0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_using_after(self): def test_if_fires_using_after(self):
@ -194,7 +194,7 @@ class TestAutomationTime(unittest.TestCase):
fire_time_changed(self.hass, dt_util.utcnow().replace( fire_time_changed(self.hass, dt_util.utcnow().replace(
hour=5, minute=0, second=0)) hour=5, minute=0, second=0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.assertEqual('time - 5', self.calls[0].data['some']) self.assertEqual('time - 5', self.calls[0].data['some'])
@ -214,7 +214,7 @@ class TestAutomationTime(unittest.TestCase):
fire_time_changed(self.hass, dt_util.utcnow().replace( fire_time_changed(self.hass, dt_util.utcnow().replace(
hour=5, minute=0, second=0)) hour=5, minute=0, second=0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_not_fires_using_wrong_after(self): def test_if_not_fires_using_wrong_after(self):
@ -238,7 +238,7 @@ class TestAutomationTime(unittest.TestCase):
fire_time_changed(self.hass, dt_util.utcnow().replace( fire_time_changed(self.hass, dt_util.utcnow().replace(
hour=1, minute=0, second=5)) hour=1, minute=0, second=5))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_if_action_before(self): def test_if_action_before(self):
@ -265,14 +265,14 @@ class TestAutomationTime(unittest.TestCase):
with patch('homeassistant.helpers.condition.dt_util.now', with patch('homeassistant.helpers.condition.dt_util.now',
return_value=before_10): return_value=before_10):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
with patch('homeassistant.helpers.condition.dt_util.now', with patch('homeassistant.helpers.condition.dt_util.now',
return_value=after_10): return_value=after_10):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
@ -300,14 +300,14 @@ class TestAutomationTime(unittest.TestCase):
with patch('homeassistant.helpers.condition.dt_util.now', with patch('homeassistant.helpers.condition.dt_util.now',
return_value=before_10): return_value=before_10):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
with patch('homeassistant.helpers.condition.dt_util.now', with patch('homeassistant.helpers.condition.dt_util.now',
return_value=after_10): return_value=after_10):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
@ -336,14 +336,14 @@ class TestAutomationTime(unittest.TestCase):
with patch('homeassistant.helpers.condition.dt_util.now', with patch('homeassistant.helpers.condition.dt_util.now',
return_value=monday): return_value=monday):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
with patch('homeassistant.helpers.condition.dt_util.now', with patch('homeassistant.helpers.condition.dt_util.now',
return_value=tuesday): return_value=tuesday):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
@ -373,20 +373,20 @@ class TestAutomationTime(unittest.TestCase):
with patch('homeassistant.helpers.condition.dt_util.now', with patch('homeassistant.helpers.condition.dt_util.now',
return_value=monday): return_value=monday):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
with patch('homeassistant.helpers.condition.dt_util.now', with patch('homeassistant.helpers.condition.dt_util.now',
return_value=tuesday): return_value=tuesday):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(self.calls)) self.assertEqual(2, len(self.calls))
with patch('homeassistant.helpers.condition.dt_util.now', with patch('homeassistant.helpers.condition.dt_util.now',
return_value=wednesday): return_value=wednesday):
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(self.calls)) self.assertEqual(2, len(self.calls))

View file

@ -40,7 +40,7 @@ class TestAutomationZone(unittest.TestCase):
'latitude': 32.881011, 'latitude': 32.881011,
'longitude': -117.234758 'longitude': -117.234758
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
assert _setup_component(self.hass, automation.DOMAIN, { assert _setup_component(self.hass, automation.DOMAIN, {
automation.DOMAIN: { automation.DOMAIN: {
@ -67,7 +67,7 @@ class TestAutomationZone(unittest.TestCase):
'latitude': 32.880586, 'latitude': 32.880586,
'longitude': -117.237564 'longitude': -117.237564
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.assertEqual( self.assertEqual(
@ -79,16 +79,16 @@ class TestAutomationZone(unittest.TestCase):
'latitude': 32.881011, 'latitude': 32.881011,
'longitude': -117.234758 'longitude': -117.234758
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
automation.turn_off(self.hass) automation.turn_off(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set('test.entity', 'hello', { self.hass.states.set('test.entity', 'hello', {
'latitude': 32.880586, 'latitude': 32.880586,
'longitude': -117.237564 'longitude': -117.237564
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
@ -98,7 +98,7 @@ class TestAutomationZone(unittest.TestCase):
'latitude': 32.880586, 'latitude': 32.880586,
'longitude': -117.237564 'longitude': -117.237564
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
assert _setup_component(self.hass, automation.DOMAIN, { assert _setup_component(self.hass, automation.DOMAIN, {
automation.DOMAIN: { automation.DOMAIN: {
@ -118,7 +118,7 @@ class TestAutomationZone(unittest.TestCase):
'latitude': 32.881011, 'latitude': 32.881011,
'longitude': -117.234758 'longitude': -117.234758
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
@ -128,7 +128,7 @@ class TestAutomationZone(unittest.TestCase):
'latitude': 32.880586, 'latitude': 32.880586,
'longitude': -117.237564 'longitude': -117.237564
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
assert _setup_component(self.hass, automation.DOMAIN, { assert _setup_component(self.hass, automation.DOMAIN, {
automation.DOMAIN: { automation.DOMAIN: {
@ -148,7 +148,7 @@ class TestAutomationZone(unittest.TestCase):
'latitude': 32.881011, 'latitude': 32.881011,
'longitude': -117.234758 'longitude': -117.234758
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
@ -158,7 +158,7 @@ class TestAutomationZone(unittest.TestCase):
'latitude': 32.881011, 'latitude': 32.881011,
'longitude': -117.234758 'longitude': -117.234758
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
assert _setup_component(self.hass, automation.DOMAIN, { assert _setup_component(self.hass, automation.DOMAIN, {
automation.DOMAIN: { automation.DOMAIN: {
@ -178,7 +178,7 @@ class TestAutomationZone(unittest.TestCase):
'latitude': 32.880586, 'latitude': 32.880586,
'longitude': -117.237564 'longitude': -117.237564
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
@ -188,7 +188,7 @@ class TestAutomationZone(unittest.TestCase):
'latitude': 32.880586, 'latitude': 32.880586,
'longitude': -117.237564 'longitude': -117.237564
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
assert _setup_component(self.hass, automation.DOMAIN, { assert _setup_component(self.hass, automation.DOMAIN, {
automation.DOMAIN: { automation.DOMAIN: {
@ -208,5 +208,5 @@ class TestAutomationZone(unittest.TestCase):
}) })
self.hass.bus.fire('test_event') self.hass.bus.fire('test_event')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))

View file

@ -38,12 +38,12 @@ class TestSensorMQTT(unittest.TestCase):
self.assertEqual(STATE_OFF, state.state) self.assertEqual(STATE_OFF, state.state)
fire_mqtt_message(self.hass, 'test-topic', 'ON') fire_mqtt_message(self.hass, 'test-topic', 'ON')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test') state = self.hass.states.get('binary_sensor.test')
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)
fire_mqtt_message(self.hass, 'test-topic', 'OFF') fire_mqtt_message(self.hass, 'test-topic', 'OFF')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test') state = self.hass.states.get('binary_sensor.test')
self.assertEqual(STATE_OFF, state.state) self.assertEqual(STATE_OFF, state.state)

View file

@ -110,11 +110,11 @@ class TestBinarySensorTemplate(unittest.TestCase):
vs = template.BinarySensorTemplate(hass, 'parent', 'Parent', vs = template.BinarySensorTemplate(hass, 'parent', 'Parent',
'motion', '{{ 1 > 1 }}', MATCH_ALL) 'motion', '{{ 1 > 1 }}', MATCH_ALL)
vs.update_ha_state() vs.update_ha_state()
hass.pool.block_till_done() hass.block_till_done()
with mock.patch.object(vs, 'update') as mock_update: with mock.patch.object(vs, 'update') as mock_update:
hass.bus.fire(EVENT_STATE_CHANGED) hass.bus.fire(EVENT_STATE_CHANGED)
hass.pool.block_till_done() hass.block_till_done()
try: try:
assert mock_update.call_count == 1 assert mock_update.call_count == 1
finally: finally:

View file

@ -30,9 +30,9 @@ class TestTrendBinarySensor:
}) })
self.hass.states.set('sensor.test_state', '1') self.hass.states.set('sensor.test_state', '1')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set('sensor.test_state', '2') self.hass.states.set('sensor.test_state', '2')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor') state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'on' assert state.state == 'on'
@ -51,9 +51,9 @@ class TestTrendBinarySensor:
}) })
self.hass.states.set('sensor.test_state', '2') self.hass.states.set('sensor.test_state', '2')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set('sensor.test_state', '1') self.hass.states.set('sensor.test_state', '1')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor') state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'off' assert state.state == 'off'
@ -73,9 +73,9 @@ class TestTrendBinarySensor:
}) })
self.hass.states.set('sensor.test_state', '1') self.hass.states.set('sensor.test_state', '1')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set('sensor.test_state', '2') self.hass.states.set('sensor.test_state', '2')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor') state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'off' assert state.state == 'off'
@ -95,9 +95,9 @@ class TestTrendBinarySensor:
}) })
self.hass.states.set('sensor.test_state', '2') self.hass.states.set('sensor.test_state', '2')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set('sensor.test_state', '1') self.hass.states.set('sensor.test_state', '1')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor') state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'on' assert state.state == 'on'
@ -116,9 +116,9 @@ class TestTrendBinarySensor:
} }
}) })
self.hass.states.set('sensor.test_state', 'State', {'attr': '1'}) self.hass.states.set('sensor.test_state', 'State', {'attr': '1'})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set('sensor.test_state', 'State', {'attr': '2'}) self.hass.states.set('sensor.test_state', 'State', {'attr': '2'})
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor') state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'on' assert state.state == 'on'
@ -138,10 +138,10 @@ class TestTrendBinarySensor:
}) })
self.hass.states.set('sensor.test_state', 'State', {'attr': '2'}) self.hass.states.set('sensor.test_state', 'State', {'attr': '2'})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set('sensor.test_state', 'State', {'attr': '1'}) self.hass.states.set('sensor.test_state', 'State', {'attr': '1'})
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor') state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'off' assert state.state == 'off'
@ -160,9 +160,9 @@ class TestTrendBinarySensor:
}) })
self.hass.states.set('sensor.test_state', 'Non') self.hass.states.set('sensor.test_state', 'Non')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set('sensor.test_state', 'Numeric') self.hass.states.set('sensor.test_state', 'Numeric')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor') state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'off' assert state.state == 'off'
@ -182,10 +182,10 @@ class TestTrendBinarySensor:
}) })
self.hass.states.set('sensor.test_state', 'State', {'attr': '2'}) self.hass.states.set('sensor.test_state', 'State', {'attr': '2'})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set('sensor.test_state', 'State', {'attr': '1'}) self.hass.states.set('sensor.test_state', 'State', {'attr': '1'})
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor') state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'off' assert state.state == 'off'

View file

@ -54,7 +54,7 @@ class TestDemoClimate(unittest.TestCase):
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual(21, state.attributes.get('temperature')) self.assertEqual(21, state.attributes.get('temperature'))
climate.set_temperature(self.hass, None, ENTITY_CLIMATE) climate.set_temperature(self.hass, None, ENTITY_CLIMATE)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(21, state.attributes.get('temperature')) self.assertEqual(21, state.attributes.get('temperature'))
def test_set_only_target_temp(self): def test_set_only_target_temp(self):
@ -62,7 +62,7 @@ class TestDemoClimate(unittest.TestCase):
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual(21, state.attributes.get('temperature')) self.assertEqual(21, state.attributes.get('temperature'))
climate.set_temperature(self.hass, 30, ENTITY_CLIMATE) climate.set_temperature(self.hass, 30, ENTITY_CLIMATE)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual(30.0, state.attributes.get('temperature')) self.assertEqual(30.0, state.attributes.get('temperature'))
@ -98,7 +98,7 @@ class TestDemoClimate(unittest.TestCase):
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual(67, state.attributes.get('humidity')) self.assertEqual(67, state.attributes.get('humidity'))
climate.set_humidity(self.hass, None, ENTITY_CLIMATE) climate.set_humidity(self.hass, None, ENTITY_CLIMATE)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual(67, state.attributes.get('humidity')) self.assertEqual(67, state.attributes.get('humidity'))
@ -107,7 +107,7 @@ class TestDemoClimate(unittest.TestCase):
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual(67, state.attributes.get('humidity')) self.assertEqual(67, state.attributes.get('humidity'))
climate.set_humidity(self.hass, 64, ENTITY_CLIMATE) climate.set_humidity(self.hass, 64, ENTITY_CLIMATE)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual(64.0, state.attributes.get('humidity')) self.assertEqual(64.0, state.attributes.get('humidity'))
@ -116,7 +116,7 @@ class TestDemoClimate(unittest.TestCase):
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("On High", state.attributes.get('fan_mode')) self.assertEqual("On High", state.attributes.get('fan_mode'))
climate.set_fan_mode(self.hass, None, ENTITY_CLIMATE) climate.set_fan_mode(self.hass, None, ENTITY_CLIMATE)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("On High", state.attributes.get('fan_mode')) self.assertEqual("On High", state.attributes.get('fan_mode'))
@ -125,7 +125,7 @@ class TestDemoClimate(unittest.TestCase):
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("On High", state.attributes.get('fan_mode')) self.assertEqual("On High", state.attributes.get('fan_mode'))
climate.set_fan_mode(self.hass, "On Low", ENTITY_CLIMATE) climate.set_fan_mode(self.hass, "On Low", ENTITY_CLIMATE)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("On Low", state.attributes.get('fan_mode')) self.assertEqual("On Low", state.attributes.get('fan_mode'))
@ -134,7 +134,7 @@ class TestDemoClimate(unittest.TestCase):
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("Off", state.attributes.get('swing_mode')) self.assertEqual("Off", state.attributes.get('swing_mode'))
climate.set_swing_mode(self.hass, None, ENTITY_CLIMATE) climate.set_swing_mode(self.hass, None, ENTITY_CLIMATE)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("Off", state.attributes.get('swing_mode')) self.assertEqual("Off", state.attributes.get('swing_mode'))
@ -143,7 +143,7 @@ class TestDemoClimate(unittest.TestCase):
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("Off", state.attributes.get('swing_mode')) self.assertEqual("Off", state.attributes.get('swing_mode'))
climate.set_swing_mode(self.hass, "Auto", ENTITY_CLIMATE) climate.set_swing_mode(self.hass, "Auto", ENTITY_CLIMATE)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("Auto", state.attributes.get('swing_mode')) self.assertEqual("Auto", state.attributes.get('swing_mode'))
@ -154,7 +154,7 @@ class TestDemoClimate(unittest.TestCase):
self.assertEqual("cool", state.attributes.get('operation_mode')) self.assertEqual("cool", state.attributes.get('operation_mode'))
self.assertEqual("cool", state.state) self.assertEqual("cool", state.state)
climate.set_operation_mode(self.hass, None, ENTITY_CLIMATE) climate.set_operation_mode(self.hass, None, ENTITY_CLIMATE)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("cool", state.attributes.get('operation_mode')) self.assertEqual("cool", state.attributes.get('operation_mode'))
self.assertEqual("cool", state.state) self.assertEqual("cool", state.state)
@ -165,7 +165,7 @@ class TestDemoClimate(unittest.TestCase):
self.assertEqual("cool", state.attributes.get('operation_mode')) self.assertEqual("cool", state.attributes.get('operation_mode'))
self.assertEqual("cool", state.state) self.assertEqual("cool", state.state)
climate.set_operation_mode(self.hass, "heat", ENTITY_CLIMATE) climate.set_operation_mode(self.hass, "heat", ENTITY_CLIMATE)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("heat", state.attributes.get('operation_mode')) self.assertEqual("heat", state.attributes.get('operation_mode'))
self.assertEqual("heat", state.state) self.assertEqual("heat", state.state)
@ -175,20 +175,20 @@ class TestDemoClimate(unittest.TestCase):
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual('on', state.attributes.get('away_mode')) self.assertEqual('on', state.attributes.get('away_mode'))
climate.set_away_mode(self.hass, None, ENTITY_CLIMATE) climate.set_away_mode(self.hass, None, ENTITY_CLIMATE)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual('on', state.attributes.get('away_mode')) self.assertEqual('on', state.attributes.get('away_mode'))
def test_set_away_mode_on(self): def test_set_away_mode_on(self):
"""Test setting the away mode on/true.""" """Test setting the away mode on/true."""
climate.set_away_mode(self.hass, True, ENTITY_CLIMATE) climate.set_away_mode(self.hass, True, ENTITY_CLIMATE)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual('on', state.attributes.get('away_mode')) self.assertEqual('on', state.attributes.get('away_mode'))
def test_set_away_mode_off(self): def test_set_away_mode_off(self):
"""Test setting the away mode off/false.""" """Test setting the away mode off/false."""
climate.set_away_mode(self.hass, False, ENTITY_CLIMATE) climate.set_away_mode(self.hass, False, ENTITY_CLIMATE)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual('off', state.attributes.get('away_mode')) self.assertEqual('off', state.attributes.get('away_mode'))
@ -197,19 +197,19 @@ class TestDemoClimate(unittest.TestCase):
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual('off', state.attributes.get('aux_heat')) self.assertEqual('off', state.attributes.get('aux_heat'))
climate.set_aux_heat(self.hass, None, ENTITY_CLIMATE) climate.set_aux_heat(self.hass, None, ENTITY_CLIMATE)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual('off', state.attributes.get('aux_heat')) self.assertEqual('off', state.attributes.get('aux_heat'))
def test_set_aux_heat_on(self): def test_set_aux_heat_on(self):
"""Test setting the axillary heater on/true.""" """Test setting the axillary heater on/true."""
climate.set_aux_heat(self.hass, True, ENTITY_CLIMATE) climate.set_aux_heat(self.hass, True, ENTITY_CLIMATE)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual('on', state.attributes.get('aux_heat')) self.assertEqual('on', state.attributes.get('aux_heat'))
def test_set_aux_heat_off(self): def test_set_aux_heat_off(self):
"""Test setting the auxillary heater off/false.""" """Test setting the auxillary heater off/false."""
climate.set_aux_heat(self.hass, False, ENTITY_CLIMATE) climate.set_aux_heat(self.hass, False, ENTITY_CLIMATE)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE) state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual('off', state.attributes.get('aux_heat')) self.assertEqual('off', state.attributes.get('aux_heat'))

View file

@ -121,7 +121,7 @@ class TestClimateGenericThermostat(unittest.TestCase):
def test_set_target_temp(self): def test_set_target_temp(self):
"""Test the setting of the target temperature.""" """Test the setting of the target temperature."""
climate.set_temperature(self.hass, 30) climate.set_temperature(self.hass, 30)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY) state = self.hass.states.get(ENTITY)
self.assertEqual(30.0, state.attributes.get('temperature')) self.assertEqual(30.0, state.attributes.get('temperature'))
@ -132,7 +132,7 @@ class TestClimateGenericThermostat(unittest.TestCase):
unit = state.attributes.get('unit_of_measurement') unit = state.attributes.get('unit_of_measurement')
self._setup_sensor(22.0, unit='bad_unit') self._setup_sensor(22.0, unit='bad_unit')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY) state = self.hass.states.get(ENTITY)
self.assertEqual(unit, state.attributes.get('unit_of_measurement')) self.assertEqual(unit, state.attributes.get('unit_of_measurement'))
@ -145,7 +145,7 @@ class TestClimateGenericThermostat(unittest.TestCase):
unit = state.attributes.get('unit_of_measurement') unit = state.attributes.get('unit_of_measurement')
self._setup_sensor(None) self._setup_sensor(None)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY) state = self.hass.states.get(ENTITY)
self.assertEqual(unit, state.attributes.get('unit_of_measurement')) self.assertEqual(unit, state.attributes.get('unit_of_measurement'))
@ -155,9 +155,9 @@ class TestClimateGenericThermostat(unittest.TestCase):
"""Test if target temperature turn heater on.""" """Test if target temperature turn heater on."""
self._setup_switch(False) self._setup_switch(False)
self._setup_sensor(25) self._setup_sensor(25)
self.hass.pool.block_till_done() self.hass.block_till_done()
climate.set_temperature(self.hass, 30) climate.set_temperature(self.hass, 30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -168,9 +168,9 @@ class TestClimateGenericThermostat(unittest.TestCase):
"""Test if target temperature turn heater off.""" """Test if target temperature turn heater off."""
self._setup_switch(True) self._setup_switch(True)
self._setup_sensor(30) self._setup_sensor(30)
self.hass.pool.block_till_done() self.hass.block_till_done()
climate.set_temperature(self.hass, 25) climate.set_temperature(self.hass, 25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -181,9 +181,9 @@ class TestClimateGenericThermostat(unittest.TestCase):
"""Test if temperature change turn heater on.""" """Test if temperature change turn heater on."""
self._setup_switch(False) self._setup_switch(False)
climate.set_temperature(self.hass, 30) climate.set_temperature(self.hass, 30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(25) self._setup_sensor(25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -194,9 +194,9 @@ class TestClimateGenericThermostat(unittest.TestCase):
"""Test if temperature change turn heater off.""" """Test if temperature change turn heater off."""
self._setup_switch(True) self._setup_switch(True)
climate.set_temperature(self.hass, 25) climate.set_temperature(self.hass, 25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(30) self._setup_sensor(30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -245,9 +245,9 @@ class TestClimateGenericThermostatACMode(unittest.TestCase):
"""Test if target temperature turn ac off.""" """Test if target temperature turn ac off."""
self._setup_switch(True) self._setup_switch(True)
self._setup_sensor(25) self._setup_sensor(25)
self.hass.pool.block_till_done() self.hass.block_till_done()
climate.set_temperature(self.hass, 30) climate.set_temperature(self.hass, 30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -258,9 +258,9 @@ class TestClimateGenericThermostatACMode(unittest.TestCase):
"""Test if target temperature turn ac on.""" """Test if target temperature turn ac on."""
self._setup_switch(False) self._setup_switch(False)
self._setup_sensor(30) self._setup_sensor(30)
self.hass.pool.block_till_done() self.hass.block_till_done()
climate.set_temperature(self.hass, 25) climate.set_temperature(self.hass, 25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -271,9 +271,9 @@ class TestClimateGenericThermostatACMode(unittest.TestCase):
"""Test if temperature change turn ac off.""" """Test if temperature change turn ac off."""
self._setup_switch(True) self._setup_switch(True)
climate.set_temperature(self.hass, 30) climate.set_temperature(self.hass, 30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(25) self._setup_sensor(25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -284,9 +284,9 @@ class TestClimateGenericThermostatACMode(unittest.TestCase):
"""Test if temperature change turn ac on.""" """Test if temperature change turn ac on."""
self._setup_switch(False) self._setup_switch(False)
climate.set_temperature(self.hass, 25) climate.set_temperature(self.hass, 25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(30) self._setup_sensor(30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -336,9 +336,9 @@ class TestClimateGenericThermostatACModeMinCycle(unittest.TestCase):
"""Test if temperature change turn ac on.""" """Test if temperature change turn ac on."""
self._setup_switch(False) self._setup_switch(False)
climate.set_temperature(self.hass, 25) climate.set_temperature(self.hass, 25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(30) self._setup_sensor(30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_temp_change_ac_trigger_on_long_enough(self): def test_temp_change_ac_trigger_on_long_enough(self):
@ -349,9 +349,9 @@ class TestClimateGenericThermostatACModeMinCycle(unittest.TestCase):
return_value=fake_changed): return_value=fake_changed):
self._setup_switch(False) self._setup_switch(False)
climate.set_temperature(self.hass, 25) climate.set_temperature(self.hass, 25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(30) self._setup_sensor(30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -362,9 +362,9 @@ class TestClimateGenericThermostatACModeMinCycle(unittest.TestCase):
"""Test if temperature change turn ac on.""" """Test if temperature change turn ac on."""
self._setup_switch(True) self._setup_switch(True)
climate.set_temperature(self.hass, 30) climate.set_temperature(self.hass, 30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(25) self._setup_sensor(25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_temp_change_ac_trigger_off_long_enough(self): def test_temp_change_ac_trigger_off_long_enough(self):
@ -375,9 +375,9 @@ class TestClimateGenericThermostatACModeMinCycle(unittest.TestCase):
return_value=fake_changed): return_value=fake_changed):
self._setup_switch(True) self._setup_switch(True)
climate.set_temperature(self.hass, 30) climate.set_temperature(self.hass, 30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(25) self._setup_sensor(25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -426,18 +426,18 @@ class TestClimateGenericThermostatMinCycle(unittest.TestCase):
"""Test if temp change doesn't turn heater off because of time.""" """Test if temp change doesn't turn heater off because of time."""
self._setup_switch(True) self._setup_switch(True)
climate.set_temperature(self.hass, 25) climate.set_temperature(self.hass, 25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(30) self._setup_sensor(30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_temp_change_heater_trigger_on_not_long_enough(self): def test_temp_change_heater_trigger_on_not_long_enough(self):
"""Test if temp change doesn't turn heater on because of time.""" """Test if temp change doesn't turn heater on because of time."""
self._setup_switch(False) self._setup_switch(False)
climate.set_temperature(self.hass, 30) climate.set_temperature(self.hass, 30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(25) self._setup_sensor(25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_temp_change_heater_trigger_on_long_enough(self): def test_temp_change_heater_trigger_on_long_enough(self):
@ -448,9 +448,9 @@ class TestClimateGenericThermostatMinCycle(unittest.TestCase):
return_value=fake_changed): return_value=fake_changed):
self._setup_switch(False) self._setup_switch(False)
climate.set_temperature(self.hass, 30) climate.set_temperature(self.hass, 30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(25) self._setup_sensor(25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -465,9 +465,9 @@ class TestClimateGenericThermostatMinCycle(unittest.TestCase):
return_value=fake_changed): return_value=fake_changed):
self._setup_switch(True) self._setup_switch(True)
climate.set_temperature(self.hass, 25) climate.set_temperature(self.hass, 25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(30) self._setup_sensor(30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)

View file

@ -5,18 +5,19 @@ import tempfile
import unittest import unittest
from unittest import mock from unittest import mock
import homeassistant.core as ha
import homeassistant.components.cover as cover import homeassistant.components.cover as cover
from homeassistant.components.cover import ( from homeassistant.components.cover import (
command_line as cmd_rs) command_line as cmd_rs)
from tests.common import get_test_home_assistant
class TestCommandCover(unittest.TestCase): class TestCommandCover(unittest.TestCase):
"""Test the cover command line platform.""" """Test the cover command line platform."""
def setup_method(self, method): def setup_method(self, method):
"""Setup things to be run when tests are started.""" """Setup things to be run when tests are started."""
self.hass = ha.HomeAssistant() self.hass = get_test_home_assistant()
self.rs = cmd_rs.CommandCover(self.hass, 'foo', self.rs = cmd_rs.CommandCover(self.hass, 'foo',
'command_open', 'command_close', 'command_open', 'command_close',
'command_stop', 'command_state', 'command_stop', 'command_state',
@ -64,19 +65,19 @@ class TestCommandCover(unittest.TestCase):
self.assertEqual('unknown', state.state) self.assertEqual('unknown', state.state)
cover.open_cover(self.hass, 'cover.test') cover.open_cover(self.hass, 'cover.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('cover.test') state = self.hass.states.get('cover.test')
self.assertEqual('open', state.state) self.assertEqual('open', state.state)
cover.close_cover(self.hass, 'cover.test') cover.close_cover(self.hass, 'cover.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('cover.test') state = self.hass.states.get('cover.test')
self.assertEqual('open', state.state) self.assertEqual('open', state.state)
cover.stop_cover(self.hass, 'cover.test') cover.stop_cover(self.hass, 'cover.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('cover.test') state = self.hass.states.get('cover.test')
self.assertEqual('closed', state.state) self.assertEqual('closed', state.state)

View file

@ -28,11 +28,11 @@ class TestCoverDemo(unittest.TestCase):
state = self.hass.states.get(ENTITY_COVER) state = self.hass.states.get(ENTITY_COVER)
self.assertEqual(70, state.attributes.get('current_position')) self.assertEqual(70, state.attributes.get('current_position'))
cover.close_cover(self.hass, ENTITY_COVER) cover.close_cover(self.hass, ENTITY_COVER)
self.hass.pool.block_till_done() self.hass.block_till_done()
for _ in range(7): for _ in range(7):
future = dt_util.utcnow() + timedelta(seconds=1) future = dt_util.utcnow() + timedelta(seconds=1)
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_COVER) state = self.hass.states.get(ENTITY_COVER)
self.assertEqual(0, state.attributes.get('current_position')) self.assertEqual(0, state.attributes.get('current_position'))
@ -42,11 +42,11 @@ class TestCoverDemo(unittest.TestCase):
state = self.hass.states.get(ENTITY_COVER) state = self.hass.states.get(ENTITY_COVER)
self.assertEqual(70, state.attributes.get('current_position')) self.assertEqual(70, state.attributes.get('current_position'))
cover.open_cover(self.hass, ENTITY_COVER) cover.open_cover(self.hass, ENTITY_COVER)
self.hass.pool.block_till_done() self.hass.block_till_done()
for _ in range(7): for _ in range(7):
future = dt_util.utcnow() + timedelta(seconds=1) future = dt_util.utcnow() + timedelta(seconds=1)
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_COVER) state = self.hass.states.get(ENTITY_COVER)
self.assertEqual(100, state.attributes.get('current_position')) self.assertEqual(100, state.attributes.get('current_position'))
@ -56,11 +56,11 @@ class TestCoverDemo(unittest.TestCase):
state = self.hass.states.get(ENTITY_COVER) state = self.hass.states.get(ENTITY_COVER)
self.assertEqual(70, state.attributes.get('current_position')) self.assertEqual(70, state.attributes.get('current_position'))
cover.set_cover_position(self.hass, 10, ENTITY_COVER) cover.set_cover_position(self.hass, 10, ENTITY_COVER)
self.hass.pool.block_till_done() self.hass.block_till_done()
for _ in range(6): for _ in range(6):
future = dt_util.utcnow() + timedelta(seconds=1) future = dt_util.utcnow() + timedelta(seconds=1)
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_COVER) state = self.hass.states.get(ENTITY_COVER)
self.assertEqual(10, state.attributes.get('current_position')) self.assertEqual(10, state.attributes.get('current_position'))
@ -70,12 +70,12 @@ class TestCoverDemo(unittest.TestCase):
state = self.hass.states.get(ENTITY_COVER) state = self.hass.states.get(ENTITY_COVER)
self.assertEqual(70, state.attributes.get('current_position')) self.assertEqual(70, state.attributes.get('current_position'))
cover.open_cover(self.hass, ENTITY_COVER) cover.open_cover(self.hass, ENTITY_COVER)
self.hass.pool.block_till_done() self.hass.block_till_done()
future = dt_util.utcnow() + timedelta(seconds=1) future = dt_util.utcnow() + timedelta(seconds=1)
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
cover.stop_cover(self.hass, ENTITY_COVER) cover.stop_cover(self.hass, ENTITY_COVER)
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
state = self.hass.states.get(ENTITY_COVER) state = self.hass.states.get(ENTITY_COVER)
self.assertEqual(80, state.attributes.get('current_position')) self.assertEqual(80, state.attributes.get('current_position'))
@ -85,11 +85,11 @@ class TestCoverDemo(unittest.TestCase):
state = self.hass.states.get(ENTITY_COVER) state = self.hass.states.get(ENTITY_COVER)
self.assertEqual(50, state.attributes.get('current_tilt_position')) self.assertEqual(50, state.attributes.get('current_tilt_position'))
cover.close_cover_tilt(self.hass, ENTITY_COVER) cover.close_cover_tilt(self.hass, ENTITY_COVER)
self.hass.pool.block_till_done() self.hass.block_till_done()
for _ in range(7): for _ in range(7):
future = dt_util.utcnow() + timedelta(seconds=1) future = dt_util.utcnow() + timedelta(seconds=1)
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_COVER) state = self.hass.states.get(ENTITY_COVER)
self.assertEqual(0, state.attributes.get('current_tilt_position')) self.assertEqual(0, state.attributes.get('current_tilt_position'))
@ -99,11 +99,11 @@ class TestCoverDemo(unittest.TestCase):
state = self.hass.states.get(ENTITY_COVER) state = self.hass.states.get(ENTITY_COVER)
self.assertEqual(50, state.attributes.get('current_tilt_position')) self.assertEqual(50, state.attributes.get('current_tilt_position'))
cover.open_cover_tilt(self.hass, ENTITY_COVER) cover.open_cover_tilt(self.hass, ENTITY_COVER)
self.hass.pool.block_till_done() self.hass.block_till_done()
for _ in range(7): for _ in range(7):
future = dt_util.utcnow() + timedelta(seconds=1) future = dt_util.utcnow() + timedelta(seconds=1)
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_COVER) state = self.hass.states.get(ENTITY_COVER)
self.assertEqual(100, state.attributes.get('current_tilt_position')) self.assertEqual(100, state.attributes.get('current_tilt_position'))
@ -113,11 +113,11 @@ class TestCoverDemo(unittest.TestCase):
state = self.hass.states.get(ENTITY_COVER) state = self.hass.states.get(ENTITY_COVER)
self.assertEqual(50, state.attributes.get('current_tilt_position')) self.assertEqual(50, state.attributes.get('current_tilt_position'))
cover.set_cover_tilt_position(self.hass, 90, ENTITY_COVER) cover.set_cover_tilt_position(self.hass, 90, ENTITY_COVER)
self.hass.pool.block_till_done() self.hass.block_till_done()
for _ in range(7): for _ in range(7):
future = dt_util.utcnow() + timedelta(seconds=1) future = dt_util.utcnow() + timedelta(seconds=1)
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_COVER) state = self.hass.states.get(ENTITY_COVER)
self.assertEqual(90, state.attributes.get('current_tilt_position')) self.assertEqual(90, state.attributes.get('current_tilt_position'))
@ -127,12 +127,12 @@ class TestCoverDemo(unittest.TestCase):
state = self.hass.states.get(ENTITY_COVER) state = self.hass.states.get(ENTITY_COVER)
self.assertEqual(50, state.attributes.get('current_tilt_position')) self.assertEqual(50, state.attributes.get('current_tilt_position'))
cover.close_cover_tilt(self.hass, ENTITY_COVER) cover.close_cover_tilt(self.hass, ENTITY_COVER)
self.hass.pool.block_till_done() self.hass.block_till_done()
future = dt_util.utcnow() + timedelta(seconds=1) future = dt_util.utcnow() + timedelta(seconds=1)
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
cover.stop_cover_tilt(self.hass, ENTITY_COVER) cover.stop_cover_tilt(self.hass, ENTITY_COVER)
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
state = self.hass.states.get(ENTITY_COVER) state = self.hass.states.get(ENTITY_COVER)
self.assertEqual(40, state.attributes.get('current_tilt_position')) self.assertEqual(40, state.attributes.get('current_tilt_position'))

View file

@ -41,19 +41,19 @@ class TestCoverMQTT(unittest.TestCase):
self.assertEqual(STATE_UNKNOWN, state.state) self.assertEqual(STATE_UNKNOWN, state.state)
fire_mqtt_message(self.hass, 'state-topic', '0') fire_mqtt_message(self.hass, 'state-topic', '0')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('cover.test') state = self.hass.states.get('cover.test')
self.assertEqual(STATE_CLOSED, state.state) self.assertEqual(STATE_CLOSED, state.state)
fire_mqtt_message(self.hass, 'state-topic', '50') fire_mqtt_message(self.hass, 'state-topic', '50')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('cover.test') state = self.hass.states.get('cover.test')
self.assertEqual(STATE_OPEN, state.state) self.assertEqual(STATE_OPEN, state.state)
fire_mqtt_message(self.hass, 'state-topic', '100') fire_mqtt_message(self.hass, 'state-topic', '100')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('cover.test') state = self.hass.states.get('cover.test')
self.assertEqual(STATE_OPEN, state.state) self.assertEqual(STATE_OPEN, state.state)
@ -75,7 +75,7 @@ class TestCoverMQTT(unittest.TestCase):
self.assertEqual(STATE_UNKNOWN, state.state) self.assertEqual(STATE_UNKNOWN, state.state)
cover.open_cover(self.hass, 'cover.test') cover.open_cover(self.hass, 'cover.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('command-topic', 'OPEN', 2, False), self.assertEqual(('command-topic', 'OPEN', 2, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -99,7 +99,7 @@ class TestCoverMQTT(unittest.TestCase):
self.assertEqual(STATE_UNKNOWN, state.state) self.assertEqual(STATE_UNKNOWN, state.state)
cover.close_cover(self.hass, 'cover.test') cover.close_cover(self.hass, 'cover.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('command-topic', 'CLOSE', 2, False), self.assertEqual(('command-topic', 'CLOSE', 2, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -123,7 +123,7 @@ class TestCoverMQTT(unittest.TestCase):
self.assertEqual(STATE_UNKNOWN, state.state) self.assertEqual(STATE_UNKNOWN, state.state)
cover.stop_cover(self.hass, 'cover.test') cover.stop_cover(self.hass, 'cover.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('command-topic', 'STOP', 2, False), self.assertEqual(('command-topic', 'STOP', 2, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -150,25 +150,25 @@ class TestCoverMQTT(unittest.TestCase):
self.assertFalse('current_position' in state_attributes_dict) self.assertFalse('current_position' in state_attributes_dict)
fire_mqtt_message(self.hass, 'state-topic', '0') fire_mqtt_message(self.hass, 'state-topic', '0')
self.hass.pool.block_till_done() self.hass.block_till_done()
current_cover_position = self.hass.states.get( current_cover_position = self.hass.states.get(
'cover.test').attributes['current_position'] 'cover.test').attributes['current_position']
self.assertEqual(0, current_cover_position) self.assertEqual(0, current_cover_position)
fire_mqtt_message(self.hass, 'state-topic', '50') fire_mqtt_message(self.hass, 'state-topic', '50')
self.hass.pool.block_till_done() self.hass.block_till_done()
current_cover_position = self.hass.states.get( current_cover_position = self.hass.states.get(
'cover.test').attributes['current_position'] 'cover.test').attributes['current_position']
self.assertEqual(50, current_cover_position) self.assertEqual(50, current_cover_position)
fire_mqtt_message(self.hass, 'state-topic', '101') fire_mqtt_message(self.hass, 'state-topic', '101')
self.hass.pool.block_till_done() self.hass.block_till_done()
current_cover_position = self.hass.states.get( current_cover_position = self.hass.states.get(
'cover.test').attributes['current_position'] 'cover.test').attributes['current_position']
self.assertEqual(50, current_cover_position) self.assertEqual(50, current_cover_position)
fire_mqtt_message(self.hass, 'state-topic', 'non-numeric') fire_mqtt_message(self.hass, 'state-topic', 'non-numeric')
self.hass.pool.block_till_done() self.hass.block_till_done()
current_cover_position = self.hass.states.get( current_cover_position = self.hass.states.get(
'cover.test').attributes['current_position'] 'cover.test').attributes['current_position']
self.assertEqual(50, current_cover_position) self.assertEqual(50, current_cover_position)

View file

@ -194,7 +194,7 @@ 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) fire_time_changed(self.hass, scan_time)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_NOT_HOME, self.assertEqual(STATE_NOT_HOME,
self.hass.states.get('device_tracker.dev1').state) self.hass.states.get('device_tracker.dev1').state)
@ -266,7 +266,7 @@ class TestComponentsDeviceTracker(unittest.TestCase):
'gps': [.3, .8] 'gps': [.3, .8]
} }
device_tracker.see(self.hass, **params) device_tracker.see(self.hass, **params)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert mock_see.call_count == 1 assert mock_see.call_count == 1
mock_see.assert_called_once_with(**params) mock_see.assert_called_once_with(**params)
@ -274,7 +274,7 @@ class TestComponentsDeviceTracker(unittest.TestCase):
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) device_tracker.see(self.hass, **params)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert mock_see.call_count == 1 assert mock_see.call_count == 1
mock_see.assert_called_once_with(**params) mock_see.assert_called_once_with(**params)
@ -286,7 +286,7 @@ class TestComponentsDeviceTracker(unittest.TestCase):
device_tracker.see(self.hass, 'mac_1', host_name='hello') device_tracker.see(self.hass, 'mac_1', host_name='hello')
device_tracker.see(self.hass, 'mac_2', host_name='hello') device_tracker.see(self.hass, 'mac_2', host_name='hello')
self.hass.pool.block_till_done() self.hass.block_till_done()
config = device_tracker.load_config(self.yaml_devices, self.hass, config = device_tracker.load_config(self.yaml_devices, self.hass,
timedelta(seconds=0)) timedelta(seconds=0))

View file

@ -60,7 +60,7 @@ class TestLocative(unittest.TestCase):
def tearDown(self): def tearDown(self):
"""Stop everything that was started.""" """Stop everything that was started."""
hass.pool.block_till_done() hass.block_till_done()
def test_missing_data(self, update_config): def test_missing_data(self, update_config):
"""Test missing data.""" """Test missing data."""

View file

@ -65,5 +65,5 @@ class TestComponentsDeviceTrackerMQTT(unittest.TestCase):
} }
}) })
fire_mqtt_message(self.hass, topic, location) fire_mqtt_message(self.hass, topic, location)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(location, self.hass.states.get(enttiy_id).state) self.assertEqual(location, self.hass.states.get(enttiy_id).state)

View file

@ -252,7 +252,7 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase):
else: else:
mod_message = str_message mod_message = str_message
fire_mqtt_message(self.hass, topic, mod_message) fire_mqtt_message(self.hass, topic, mod_message)
self.hass.pool.block_till_done() self.hass.block_till_done()
def assert_location_state(self, location): def assert_location_state(self, location):
"""Test the assertion of a location state.""" """Test the assertion of a location state."""
@ -574,7 +574,7 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase):
fire_mqtt_message( fire_mqtt_message(
self.hass, EVENT_TOPIC, json.dumps(enter_message)) self.hass, EVENT_TOPIC, json.dumps(enter_message))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.send_message(EVENT_TOPIC, exit_message) self.send_message(EVENT_TOPIC, exit_message)
self.assertEqual(owntracks.MOBILE_BEACONS_ACTIVE['greg_phone'], []) self.assertEqual(owntracks.MOBILE_BEACONS_ACTIVE['greg_phone'], [])

View file

@ -22,7 +22,7 @@ class TestDemoFan(unittest.TestCase):
self.assertTrue(fan.setup(self.hass, {'fan': { self.assertTrue(fan.setup(self.hass, {'fan': {
'platform': 'demo', 'platform': 'demo',
}})) }}))
self.hass.pool.block_till_done() self.hass.block_till_done()
def tearDown(self): def tearDown(self):
"""Tear down unit test data.""" """Tear down unit test data."""
@ -33,11 +33,11 @@ class TestDemoFan(unittest.TestCase):
self.assertEqual(STATE_OFF, self.get_entity().state) self.assertEqual(STATE_OFF, self.get_entity().state)
fan.turn_on(self.hass, FAN_ENTITY_ID) fan.turn_on(self.hass, FAN_ENTITY_ID)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertNotEqual(STATE_OFF, self.get_entity().state) self.assertNotEqual(STATE_OFF, self.get_entity().state)
fan.turn_on(self.hass, FAN_ENTITY_ID, fan.SPEED_HIGH) fan.turn_on(self.hass, FAN_ENTITY_ID, fan.SPEED_HIGH)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_ON, self.get_entity().state) self.assertEqual(STATE_ON, self.get_entity().state)
self.assertEqual(fan.SPEED_HIGH, self.assertEqual(fan.SPEED_HIGH,
self.get_entity().attributes[fan.ATTR_SPEED]) self.get_entity().attributes[fan.ATTR_SPEED])
@ -47,11 +47,11 @@ class TestDemoFan(unittest.TestCase):
self.assertEqual(STATE_OFF, self.get_entity().state) self.assertEqual(STATE_OFF, self.get_entity().state)
fan.turn_on(self.hass, FAN_ENTITY_ID) fan.turn_on(self.hass, FAN_ENTITY_ID)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertNotEqual(STATE_OFF, self.get_entity().state) self.assertNotEqual(STATE_OFF, self.get_entity().state)
fan.turn_off(self.hass, FAN_ENTITY_ID) fan.turn_off(self.hass, FAN_ENTITY_ID)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_OFF, self.get_entity().state) self.assertEqual(STATE_OFF, self.get_entity().state)
def test_set_speed(self): def test_set_speed(self):
@ -59,7 +59,7 @@ class TestDemoFan(unittest.TestCase):
self.assertEqual(STATE_OFF, self.get_entity().state) self.assertEqual(STATE_OFF, self.get_entity().state)
fan.set_speed(self.hass, FAN_ENTITY_ID, fan.SPEED_LOW) fan.set_speed(self.hass, FAN_ENTITY_ID, fan.SPEED_LOW)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(fan.SPEED_LOW, self.assertEqual(fan.SPEED_LOW,
self.get_entity().attributes.get('speed')) self.get_entity().attributes.get('speed'))
@ -68,11 +68,11 @@ class TestDemoFan(unittest.TestCase):
self.assertFalse(self.get_entity().attributes.get('oscillating')) self.assertFalse(self.get_entity().attributes.get('oscillating'))
fan.oscillate(self.hass, FAN_ENTITY_ID, True) fan.oscillate(self.hass, FAN_ENTITY_ID, True)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(self.get_entity().attributes.get('oscillating')) self.assertTrue(self.get_entity().attributes.get('oscillating'))
fan.oscillate(self.hass, FAN_ENTITY_ID, False) fan.oscillate(self.hass, FAN_ENTITY_ID, False)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertFalse(self.get_entity().attributes.get('oscillating')) self.assertFalse(self.get_entity().attributes.get('oscillating'))
def test_is_on(self): def test_is_on(self):
@ -80,5 +80,5 @@ class TestDemoFan(unittest.TestCase):
self.assertFalse(fan.is_on(self.hass, FAN_ENTITY_ID)) self.assertFalse(fan.is_on(self.hass, FAN_ENTITY_ID))
fan.turn_on(self.hass, FAN_ENTITY_ID) fan.turn_on(self.hass, FAN_ENTITY_ID)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(fan.is_on(self.hass, FAN_ENTITY_ID)) self.assertTrue(fan.is_on(self.hass, FAN_ENTITY_ID))

View file

@ -37,13 +37,13 @@ class TestGarageDoorDemo(unittest.TestCase):
def test_open_door(self): def test_open_door(self):
"""Test opeing of the door.""" """Test opeing of the door."""
gd.open_door(self.hass, LEFT) gd.open_door(self.hass, LEFT)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertFalse(gd.is_closed(self.hass, LEFT)) self.assertFalse(gd.is_closed(self.hass, LEFT))
def test_close_door(self): def test_close_door(self):
"""Test closing ot the door.""" """Test closing ot the door."""
gd.close_door(self.hass, RIGHT) gd.close_door(self.hass, RIGHT)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(gd.is_closed(self.hass, RIGHT)) self.assertTrue(gd.is_closed(self.hass, RIGHT))

View file

@ -53,13 +53,13 @@ class TestGarageDoorMQTT(unittest.TestCase):
self.assertIsNone(state.attributes.get(ATTR_ASSUMED_STATE)) self.assertIsNone(state.attributes.get(ATTR_ASSUMED_STATE))
fire_mqtt_message(self.hass, 'state-topic', '1') fire_mqtt_message(self.hass, 'state-topic', '1')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('garage_door.test') state = self.hass.states.get('garage_door.test')
self.assertEqual(STATE_OPEN, state.state) self.assertEqual(STATE_OPEN, state.state)
fire_mqtt_message(self.hass, 'state-topic', '0') fire_mqtt_message(self.hass, 'state-topic', '0')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('garage_door.test') state = self.hass.states.get('garage_door.test')
self.assertEqual(STATE_CLOSED, state.state) self.assertEqual(STATE_CLOSED, state.state)
@ -84,7 +84,7 @@ class TestGarageDoorMQTT(unittest.TestCase):
self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE)) self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE))
garage_door.open_door(self.hass, 'garage_door.test') garage_door.open_door(self.hass, 'garage_door.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('command-topic', 'beer open', 2, False), self.assertEqual(('command-topic', 'beer open', 2, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -92,7 +92,7 @@ class TestGarageDoorMQTT(unittest.TestCase):
self.assertEqual(STATE_OPEN, state.state) self.assertEqual(STATE_OPEN, state.state)
garage_door.close_door(self.hass, 'garage_door.test') garage_door.close_door(self.hass, 'garage_door.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('command-topic', 'beer close', 2, False), self.assertEqual(('command-topic', 'beer close', 2, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -119,13 +119,13 @@ class TestGarageDoorMQTT(unittest.TestCase):
self.assertEqual(STATE_CLOSED, state.state) self.assertEqual(STATE_CLOSED, state.state)
fire_mqtt_message(self.hass, 'state-topic', '{"val":"beer open"}') fire_mqtt_message(self.hass, 'state-topic', '{"val":"beer open"}')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('garage_door.test') state = self.hass.states.get('garage_door.test')
self.assertEqual(STATE_OPEN, state.state) self.assertEqual(STATE_OPEN, state.state)
fire_mqtt_message(self.hass, 'state-topic', '{"val":"beer closed"}') fire_mqtt_message(self.hass, 'state-topic', '{"val":"beer closed"}')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('garage_door.test') state = self.hass.states.get('garage_door.test')
self.assertEqual(STATE_CLOSED, state.state) self.assertEqual(STATE_CLOSED, state.state)

View file

@ -53,13 +53,13 @@ class TestDemoHvac(unittest.TestCase):
state = self.hass.states.get(ENTITY_HVAC) state = self.hass.states.get(ENTITY_HVAC)
self.assertEqual(21, state.attributes.get('temperature')) self.assertEqual(21, state.attributes.get('temperature'))
hvac.set_temperature(self.hass, None, ENTITY_HVAC) hvac.set_temperature(self.hass, None, ENTITY_HVAC)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(21, state.attributes.get('temperature')) self.assertEqual(21, state.attributes.get('temperature'))
def test_set_target_temp(self): def test_set_target_temp(self):
"""Test the setting of the target temperature.""" """Test the setting of the target temperature."""
hvac.set_temperature(self.hass, 30, ENTITY_HVAC) hvac.set_temperature(self.hass, 30, ENTITY_HVAC)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_HVAC) state = self.hass.states.get(ENTITY_HVAC)
self.assertEqual(30.0, state.attributes.get('temperature')) self.assertEqual(30.0, state.attributes.get('temperature'))
@ -68,13 +68,13 @@ class TestDemoHvac(unittest.TestCase):
state = self.hass.states.get(ENTITY_HVAC) state = self.hass.states.get(ENTITY_HVAC)
self.assertEqual(67, state.attributes.get('humidity')) self.assertEqual(67, state.attributes.get('humidity'))
hvac.set_humidity(self.hass, None, ENTITY_HVAC) hvac.set_humidity(self.hass, None, ENTITY_HVAC)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(67, state.attributes.get('humidity')) self.assertEqual(67, state.attributes.get('humidity'))
def test_set_target_humidity(self): def test_set_target_humidity(self):
"""Test the setting of the target humidity.""" """Test the setting of the target humidity."""
hvac.set_humidity(self.hass, 64, ENTITY_HVAC) hvac.set_humidity(self.hass, 64, ENTITY_HVAC)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_HVAC) state = self.hass.states.get(ENTITY_HVAC)
self.assertEqual(64.0, state.attributes.get('humidity')) self.assertEqual(64.0, state.attributes.get('humidity'))
@ -83,13 +83,13 @@ class TestDemoHvac(unittest.TestCase):
state = self.hass.states.get(ENTITY_HVAC) state = self.hass.states.get(ENTITY_HVAC)
self.assertEqual("On High", state.attributes.get('fan_mode')) self.assertEqual("On High", state.attributes.get('fan_mode'))
hvac.set_fan_mode(self.hass, None, ENTITY_HVAC) hvac.set_fan_mode(self.hass, None, ENTITY_HVAC)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual("On High", state.attributes.get('fan_mode')) self.assertEqual("On High", state.attributes.get('fan_mode'))
def test_set_fan_mode(self): def test_set_fan_mode(self):
"""Test setting of new fan mode.""" """Test setting of new fan mode."""
hvac.set_fan_mode(self.hass, "On Low", ENTITY_HVAC) hvac.set_fan_mode(self.hass, "On Low", ENTITY_HVAC)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_HVAC) state = self.hass.states.get(ENTITY_HVAC)
self.assertEqual("On Low", state.attributes.get('fan_mode')) self.assertEqual("On Low", state.attributes.get('fan_mode'))
@ -98,13 +98,13 @@ class TestDemoHvac(unittest.TestCase):
state = self.hass.states.get(ENTITY_HVAC) state = self.hass.states.get(ENTITY_HVAC)
self.assertEqual("Off", state.attributes.get('swing_mode')) self.assertEqual("Off", state.attributes.get('swing_mode'))
hvac.set_swing_mode(self.hass, None, ENTITY_HVAC) hvac.set_swing_mode(self.hass, None, ENTITY_HVAC)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual("Off", state.attributes.get('swing_mode')) self.assertEqual("Off", state.attributes.get('swing_mode'))
def test_set_swing(self): def test_set_swing(self):
"""Test setting of new swing mode.""" """Test setting of new swing mode."""
hvac.set_swing_mode(self.hass, "Auto", ENTITY_HVAC) hvac.set_swing_mode(self.hass, "Auto", ENTITY_HVAC)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_HVAC) state = self.hass.states.get(ENTITY_HVAC)
self.assertEqual("Auto", state.attributes.get('swing_mode')) self.assertEqual("Auto", state.attributes.get('swing_mode'))
@ -112,13 +112,13 @@ class TestDemoHvac(unittest.TestCase):
"""Test setting operation mode without required attribute.""" """Test setting operation mode without required attribute."""
self.assertEqual("Cool", self.hass.states.get(ENTITY_HVAC).state) self.assertEqual("Cool", self.hass.states.get(ENTITY_HVAC).state)
hvac.set_operation_mode(self.hass, None, ENTITY_HVAC) hvac.set_operation_mode(self.hass, None, ENTITY_HVAC)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual("Cool", self.hass.states.get(ENTITY_HVAC).state) self.assertEqual("Cool", self.hass.states.get(ENTITY_HVAC).state)
def test_set_operation(self): def test_set_operation(self):
"""Test setting of new operation mode.""" """Test setting of new operation mode."""
hvac.set_operation_mode(self.hass, "Heat", ENTITY_HVAC) hvac.set_operation_mode(self.hass, "Heat", ENTITY_HVAC)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual("Heat", self.hass.states.get(ENTITY_HVAC).state) self.assertEqual("Heat", self.hass.states.get(ENTITY_HVAC).state)
def test_set_away_mode_bad_attr(self): def test_set_away_mode_bad_attr(self):
@ -126,20 +126,20 @@ class TestDemoHvac(unittest.TestCase):
state = self.hass.states.get(ENTITY_HVAC) state = self.hass.states.get(ENTITY_HVAC)
self.assertEqual('on', state.attributes.get('away_mode')) self.assertEqual('on', state.attributes.get('away_mode'))
hvac.set_away_mode(self.hass, None, ENTITY_HVAC) hvac.set_away_mode(self.hass, None, ENTITY_HVAC)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual('on', state.attributes.get('away_mode')) self.assertEqual('on', state.attributes.get('away_mode'))
def test_set_away_mode_on(self): def test_set_away_mode_on(self):
"""Test setting the away mode on/true.""" """Test setting the away mode on/true."""
hvac.set_away_mode(self.hass, True, ENTITY_HVAC) hvac.set_away_mode(self.hass, True, ENTITY_HVAC)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_HVAC) state = self.hass.states.get(ENTITY_HVAC)
self.assertEqual('on', state.attributes.get('away_mode')) self.assertEqual('on', state.attributes.get('away_mode'))
def test_set_away_mode_off(self): def test_set_away_mode_off(self):
"""Test setting the away mode off/false.""" """Test setting the away mode off/false."""
hvac.set_away_mode(self.hass, False, ENTITY_HVAC) hvac.set_away_mode(self.hass, False, ENTITY_HVAC)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_HVAC) state = self.hass.states.get(ENTITY_HVAC)
self.assertEqual('off', state.attributes.get('away_mode')) self.assertEqual('off', state.attributes.get('away_mode'))
@ -148,19 +148,19 @@ class TestDemoHvac(unittest.TestCase):
state = self.hass.states.get(ENTITY_HVAC) state = self.hass.states.get(ENTITY_HVAC)
self.assertEqual('off', state.attributes.get('aux_heat')) self.assertEqual('off', state.attributes.get('aux_heat'))
hvac.set_aux_heat(self.hass, None, ENTITY_HVAC) hvac.set_aux_heat(self.hass, None, ENTITY_HVAC)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual('off', state.attributes.get('aux_heat')) self.assertEqual('off', state.attributes.get('aux_heat'))
def test_set_aux_heat_on(self): def test_set_aux_heat_on(self):
"""Test setting the axillary heater on/true.""" """Test setting the axillary heater on/true."""
hvac.set_aux_heat(self.hass, True, ENTITY_HVAC) hvac.set_aux_heat(self.hass, True, ENTITY_HVAC)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_HVAC) state = self.hass.states.get(ENTITY_HVAC)
self.assertEqual('on', state.attributes.get('aux_heat')) self.assertEqual('on', state.attributes.get('aux_heat'))
def test_set_aux_heat_off(self): def test_set_aux_heat_off(self):
"""Test setting the auxillary heater off/false.""" """Test setting the auxillary heater off/false."""
hvac.set_aux_heat(self.hass, False, ENTITY_HVAC) hvac.set_aux_heat(self.hass, False, ENTITY_HVAC)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_HVAC) state = self.hass.states.get(ENTITY_HVAC)
self.assertEqual('off', state.attributes.get('aux_heat')) self.assertEqual('off', state.attributes.get('aux_heat'))

View file

@ -56,7 +56,7 @@ class TestLight(unittest.TestCase):
xy_color='xy_color_val', xy_color='xy_color_val',
profile='profile_val') profile='profile_val')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(turn_on_calls)) self.assertEqual(1, len(turn_on_calls))
call = turn_on_calls[-1] call = turn_on_calls[-1]
@ -79,7 +79,7 @@ class TestLight(unittest.TestCase):
light.turn_off( light.turn_off(
self.hass, entity_id='entity_id_val', transition='transition_val') self.hass, entity_id='entity_id_val', transition='transition_val')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(turn_off_calls)) self.assertEqual(1, len(turn_off_calls))
call = turn_off_calls[-1] call = turn_off_calls[-1]
@ -96,7 +96,7 @@ class TestLight(unittest.TestCase):
light.toggle( light.toggle(
self.hass, entity_id='entity_id_val', transition='transition_val') self.hass, entity_id='entity_id_val', transition='transition_val')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(toggle_calls)) self.assertEqual(1, len(toggle_calls))
call = toggle_calls[-1] call = toggle_calls[-1]
@ -125,7 +125,7 @@ class TestLight(unittest.TestCase):
light.turn_off(self.hass, entity_id=dev1.entity_id) light.turn_off(self.hass, entity_id=dev1.entity_id)
light.turn_on(self.hass, entity_id=dev2.entity_id) light.turn_on(self.hass, entity_id=dev2.entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertFalse(light.is_on(self.hass, dev1.entity_id)) self.assertFalse(light.is_on(self.hass, dev1.entity_id))
self.assertTrue(light.is_on(self.hass, dev2.entity_id)) self.assertTrue(light.is_on(self.hass, dev2.entity_id))
@ -133,7 +133,7 @@ class TestLight(unittest.TestCase):
# turn on all lights # turn on all lights
light.turn_on(self.hass) light.turn_on(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(light.is_on(self.hass, dev1.entity_id)) self.assertTrue(light.is_on(self.hass, dev1.entity_id))
self.assertTrue(light.is_on(self.hass, dev2.entity_id)) self.assertTrue(light.is_on(self.hass, dev2.entity_id))
@ -142,7 +142,7 @@ class TestLight(unittest.TestCase):
# turn off all lights # turn off all lights
light.turn_off(self.hass) light.turn_off(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertFalse(light.is_on(self.hass, dev1.entity_id)) self.assertFalse(light.is_on(self.hass, dev1.entity_id))
self.assertFalse(light.is_on(self.hass, dev2.entity_id)) self.assertFalse(light.is_on(self.hass, dev2.entity_id))
@ -151,7 +151,7 @@ class TestLight(unittest.TestCase):
# toggle all lights # toggle all lights
light.toggle(self.hass) light.toggle(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(light.is_on(self.hass, dev1.entity_id)) self.assertTrue(light.is_on(self.hass, dev1.entity_id))
self.assertTrue(light.is_on(self.hass, dev2.entity_id)) self.assertTrue(light.is_on(self.hass, dev2.entity_id))
@ -160,7 +160,7 @@ class TestLight(unittest.TestCase):
# toggle all lights # toggle all lights
light.toggle(self.hass) light.toggle(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertFalse(light.is_on(self.hass, dev1.entity_id)) self.assertFalse(light.is_on(self.hass, dev1.entity_id))
self.assertFalse(light.is_on(self.hass, dev2.entity_id)) self.assertFalse(light.is_on(self.hass, dev2.entity_id))
@ -173,7 +173,7 @@ class TestLight(unittest.TestCase):
self.hass, dev2.entity_id, rgb_color=(255, 255, 255)) self.hass, dev2.entity_id, rgb_color=(255, 255, 255))
light.turn_on(self.hass, dev3.entity_id, xy_color=(.4, .6)) light.turn_on(self.hass, dev3.entity_id, xy_color=(.4, .6))
self.hass.pool.block_till_done() self.hass.block_till_done()
method, data = dev1.last_call('turn_on') method, data = dev1.last_call('turn_on')
self.assertEqual( self.assertEqual(
@ -197,7 +197,7 @@ class TestLight(unittest.TestCase):
self.hass, dev2.entity_id, self.hass, dev2.entity_id,
profile=prof_name, brightness=100, xy_color=(.4, .6)) profile=prof_name, brightness=100, xy_color=(.4, .6))
self.hass.pool.block_till_done() self.hass.block_till_done()
method, data = dev1.last_call('turn_on') method, data = dev1.last_call('turn_on')
self.assertEqual( self.assertEqual(
@ -217,7 +217,7 @@ class TestLight(unittest.TestCase):
light.turn_on(self.hass, dev2.entity_id, xy_color=["bla-di-bla", 5]) light.turn_on(self.hass, dev2.entity_id, xy_color=["bla-di-bla", 5])
light.turn_on(self.hass, dev3.entity_id, rgb_color=[255, None, 2]) light.turn_on(self.hass, dev3.entity_id, rgb_color=[255, None, 2])
self.hass.pool.block_till_done() self.hass.block_till_done()
method, data = dev1.last_call('turn_on') method, data = dev1.last_call('turn_on')
self.assertEqual({}, data) self.assertEqual({}, data)
@ -233,7 +233,7 @@ class TestLight(unittest.TestCase):
self.hass, dev1.entity_id, self.hass, dev1.entity_id,
profile=prof_name, brightness='bright', rgb_color='yellowish') profile=prof_name, brightness='bright', rgb_color='yellowish')
self.hass.pool.block_till_done() self.hass.block_till_done()
method, data = dev1.last_call('turn_on') method, data = dev1.last_call('turn_on')
self.assertEqual({}, data) self.assertEqual({}, data)
@ -273,7 +273,7 @@ class TestLight(unittest.TestCase):
light.turn_on(self.hass, dev1.entity_id, profile='test') light.turn_on(self.hass, dev1.entity_id, profile='test')
self.hass.pool.block_till_done() self.hass.block_till_done()
method, data = dev1.last_call('turn_on') method, data = dev1.last_call('turn_on')

View file

@ -106,7 +106,7 @@ class TestLightMQTT(unittest.TestCase):
self.assertIsNone(state.attributes.get('brightness')) self.assertIsNone(state.attributes.get('brightness'))
fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON') fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('light.test') state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)
@ -139,7 +139,7 @@ class TestLightMQTT(unittest.TestCase):
self.assertIsNone(state.attributes.get(ATTR_ASSUMED_STATE)) self.assertIsNone(state.attributes.get(ATTR_ASSUMED_STATE))
fire_mqtt_message(self.hass, 'test_light_rgb/status', '1') fire_mqtt_message(self.hass, 'test_light_rgb/status', '1')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('light.test') state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)
@ -147,28 +147,28 @@ class TestLightMQTT(unittest.TestCase):
self.assertEqual(255, state.attributes.get('brightness')) self.assertEqual(255, state.attributes.get('brightness'))
fire_mqtt_message(self.hass, 'test_light_rgb/status', '0') fire_mqtt_message(self.hass, 'test_light_rgb/status', '0')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('light.test') state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state) self.assertEqual(STATE_OFF, state.state)
fire_mqtt_message(self.hass, 'test_light_rgb/status', '1') fire_mqtt_message(self.hass, 'test_light_rgb/status', '1')
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_mqtt_message(self.hass, 'test_light_rgb/brightness/status', '100') fire_mqtt_message(self.hass, 'test_light_rgb/brightness/status', '100')
self.hass.pool.block_till_done() self.hass.block_till_done()
light_state = self.hass.states.get('light.test') light_state = self.hass.states.get('light.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(100, self.assertEqual(100,
light_state.attributes['brightness']) light_state.attributes['brightness'])
fire_mqtt_message(self.hass, 'test_light_rgb/status', '1') fire_mqtt_message(self.hass, 'test_light_rgb/status', '1')
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_mqtt_message(self.hass, 'test_light_rgb/rgb/status', fire_mqtt_message(self.hass, 'test_light_rgb/rgb/status',
'125,125,125') '125,125,125')
self.hass.pool.block_till_done() self.hass.block_till_done()
light_state = self.hass.states.get('light.test') light_state = self.hass.states.get('light.test')
self.assertEqual([125, 125, 125], self.assertEqual([125, 125, 125],
@ -198,26 +198,26 @@ class TestLightMQTT(unittest.TestCase):
self.assertIsNone(state.attributes.get(ATTR_ASSUMED_STATE)) self.assertIsNone(state.attributes.get(ATTR_ASSUMED_STATE))
fire_mqtt_message(self.hass, 'test_scale/status', 'on') fire_mqtt_message(self.hass, 'test_scale/status', 'on')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('light.test') state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)
self.assertEqual(255, state.attributes.get('brightness')) self.assertEqual(255, state.attributes.get('brightness'))
fire_mqtt_message(self.hass, 'test_scale/status', 'off') fire_mqtt_message(self.hass, 'test_scale/status', 'off')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('light.test') state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state) self.assertEqual(STATE_OFF, state.state)
fire_mqtt_message(self.hass, 'test_scale/status', 'on') fire_mqtt_message(self.hass, 'test_scale/status', 'on')
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_mqtt_message(self.hass, 'test_scale/brightness/status', '99') fire_mqtt_message(self.hass, 'test_scale/brightness/status', '99')
self.hass.pool.block_till_done() self.hass.block_till_done()
light_state = self.hass.states.get('light.test') light_state = self.hass.states.get('light.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(255, self.assertEqual(255,
light_state.attributes['brightness']) light_state.attributes['brightness'])
@ -249,7 +249,7 @@ class TestLightMQTT(unittest.TestCase):
'{"hello": "ON"}') '{"hello": "ON"}')
fire_mqtt_message(self.hass, 'test_light_rgb/brightness/status', fire_mqtt_message(self.hass, 'test_light_rgb/brightness/status',
'{"hello": "50"}') '{"hello": "50"}')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('light.test') state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)
@ -277,7 +277,7 @@ class TestLightMQTT(unittest.TestCase):
self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE)) self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE))
light.turn_on(self.hass, 'light.test') light.turn_on(self.hass, 'light.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('test_light_rgb/set', 'on', 2, False), self.assertEqual(('test_light_rgb/set', 'on', 2, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -285,7 +285,7 @@ class TestLightMQTT(unittest.TestCase):
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)
light.turn_off(self.hass, 'light.test') light.turn_off(self.hass, 'light.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('test_light_rgb/set', 'off', 2, False), self.assertEqual(('test_light_rgb/set', 'off', 2, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -294,7 +294,7 @@ class TestLightMQTT(unittest.TestCase):
light.turn_on(self.hass, 'light.test', rgb_color=[75, 75, 75], light.turn_on(self.hass, 'light.test', rgb_color=[75, 75, 75],
brightness=50) brightness=50)
self.hass.pool.block_till_done() self.hass.block_till_done()
# Calls are threaded so we need to reorder them # Calls are threaded so we need to reorder them
bright_call, rgb_call, state_call = \ bright_call, rgb_call, state_call = \
@ -333,7 +333,7 @@ class TestLightMQTT(unittest.TestCase):
self.assertIsNone(state.attributes.get('brightness')) self.assertIsNone(state.attributes.get('brightness'))
fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON') fire_mqtt_message(self.hass, 'test_light_rgb/status', 'ON')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('light.test') state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)

View file

@ -78,7 +78,7 @@ class TestLightMQTTJSON(unittest.TestCase):
self.assertIsNone(state.attributes.get('brightness')) self.assertIsNone(state.attributes.get('brightness'))
fire_mqtt_message(self.hass, 'test_light_rgb', '{"state":"ON"}') fire_mqtt_message(self.hass, 'test_light_rgb', '{"state":"ON"}')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('light.test') state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)
@ -112,7 +112,7 @@ class TestLightMQTTJSON(unittest.TestCase):
'"color":{"r":255,"g":255,"b":255},' + '"color":{"r":255,"g":255,"b":255},' +
'"brightness":255}' '"brightness":255}'
) )
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('light.test') state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)
@ -121,7 +121,7 @@ class TestLightMQTTJSON(unittest.TestCase):
# Turn the light off # Turn the light off
fire_mqtt_message(self.hass, 'test_light_rgb', '{"state":"OFF"}') fire_mqtt_message(self.hass, 'test_light_rgb', '{"state":"OFF"}')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('light.test') state = self.hass.states.get('light.test')
self.assertEqual(STATE_OFF, state.state) self.assertEqual(STATE_OFF, state.state)
@ -130,10 +130,10 @@ class TestLightMQTTJSON(unittest.TestCase):
'{"state":"ON",' + '{"state":"ON",' +
'"brightness":100}' '"brightness":100}'
) )
self.hass.pool.block_till_done() self.hass.block_till_done()
light_state = self.hass.states.get('light.test') light_state = self.hass.states.get('light.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(100, self.assertEqual(100,
light_state.attributes['brightness']) light_state.attributes['brightness'])
@ -141,7 +141,7 @@ class TestLightMQTTJSON(unittest.TestCase):
'{"state":"ON",' + '{"state":"ON",' +
'"color":{"r":125,"g":125,"b":125}}' '"color":{"r":125,"g":125,"b":125}}'
) )
self.hass.pool.block_till_done() self.hass.block_till_done()
light_state = self.hass.states.get('light.test') light_state = self.hass.states.get('light.test')
self.assertEqual([125, 125, 125], self.assertEqual([125, 125, 125],
@ -166,7 +166,7 @@ class TestLightMQTTJSON(unittest.TestCase):
self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE)) self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE))
light.turn_on(self.hass, 'light.test') light.turn_on(self.hass, 'light.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('test_light_rgb/set', '{"state": "ON"}', 2, False), self.assertEqual(('test_light_rgb/set', '{"state": "ON"}', 2, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -174,7 +174,7 @@ class TestLightMQTTJSON(unittest.TestCase):
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)
light.turn_off(self.hass, 'light.test') light.turn_off(self.hass, 'light.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('test_light_rgb/set', '{"state": "OFF"}', 2, False), self.assertEqual(('test_light_rgb/set', '{"state": "OFF"}', 2, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -183,7 +183,7 @@ class TestLightMQTTJSON(unittest.TestCase):
light.turn_on(self.hass, 'light.test', rgb_color=[75, 75, 75], light.turn_on(self.hass, 'light.test', rgb_color=[75, 75, 75],
brightness=50) brightness=50)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual('test_light_rgb/set', self.assertEqual('test_light_rgb/set',
self.mock_publish.mock_calls[-1][1][0]) self.mock_publish.mock_calls[-1][1][0])
@ -221,7 +221,7 @@ class TestLightMQTTJSON(unittest.TestCase):
self.assertEqual(STATE_OFF, state.state) self.assertEqual(STATE_OFF, state.state)
light.turn_on(self.hass, 'light.test', flash="short") light.turn_on(self.hass, 'light.test', flash="short")
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual('test_light_rgb/set', self.assertEqual('test_light_rgb/set',
self.mock_publish.mock_calls[-1][1][0]) self.mock_publish.mock_calls[-1][1][0])
@ -233,7 +233,7 @@ class TestLightMQTTJSON(unittest.TestCase):
self.assertEqual("ON", message_json["state"]) self.assertEqual("ON", message_json["state"])
light.turn_on(self.hass, 'light.test', flash="long") light.turn_on(self.hass, 'light.test', flash="long")
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual('test_light_rgb/set', self.assertEqual('test_light_rgb/set',
self.mock_publish.mock_calls[-1][1][0]) self.mock_publish.mock_calls[-1][1][0])
@ -261,7 +261,7 @@ class TestLightMQTTJSON(unittest.TestCase):
self.assertEqual(STATE_OFF, state.state) self.assertEqual(STATE_OFF, state.state)
light.turn_on(self.hass, 'light.test', transition=10) light.turn_on(self.hass, 'light.test', transition=10)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual('test_light_rgb/set', self.assertEqual('test_light_rgb/set',
self.mock_publish.mock_calls[-1][1][0]) self.mock_publish.mock_calls[-1][1][0])
@ -274,7 +274,7 @@ class TestLightMQTTJSON(unittest.TestCase):
# Transition back off # Transition back off
light.turn_off(self.hass, 'light.test', transition=10) light.turn_off(self.hass, 'light.test', transition=10)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual('test_light_rgb/set', self.assertEqual('test_light_rgb/set',
self.mock_publish.mock_calls[-1][1][0]) self.mock_publish.mock_calls[-1][1][0])
@ -312,7 +312,7 @@ class TestLightMQTTJSON(unittest.TestCase):
'"color":{"r":255,"g":255,"b":255},' + '"color":{"r":255,"g":255,"b":255},' +
'"brightness": 255}' '"brightness": 255}'
) )
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('light.test') state = self.hass.states.get('light.test')
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)
@ -324,7 +324,7 @@ class TestLightMQTTJSON(unittest.TestCase):
'{"state":"ON",' + '{"state":"ON",' +
'"color":{"r":"bad","g":"val","b":"test"}}' '"color":{"r":"bad","g":"val","b":"test"}}'
) )
self.hass.pool.block_till_done() self.hass.block_till_done()
# Color should not have changed # Color should not have changed
state = self.hass.states.get('light.test') state = self.hass.states.get('light.test')
@ -336,7 +336,7 @@ class TestLightMQTTJSON(unittest.TestCase):
'{"state":"ON",' + '{"state":"ON",' +
'"brightness": "badValue"}' '"brightness": "badValue"}'
) )
self.hass.pool.block_till_done() self.hass.block_till_done()
# Brightness should not have changed # Brightness should not have changed
state = self.hass.states.get('light.test') state = self.hass.states.get('light.test')

View file

@ -37,13 +37,13 @@ class TestLockDemo(unittest.TestCase):
def test_locking(self): def test_locking(self):
"""Test the locking of a lock.""" """Test the locking of a lock."""
lock.lock(self.hass, KITCHEN) lock.lock(self.hass, KITCHEN)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(lock.is_locked(self.hass, KITCHEN)) self.assertTrue(lock.is_locked(self.hass, KITCHEN))
def test_unlocking(self): def test_unlocking(self):
"""Test the unlocking of a lock.""" """Test the unlocking of a lock."""
lock.unlock(self.hass, FRONT) lock.unlock(self.hass, FRONT)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertFalse(lock.is_locked(self.hass, FRONT)) self.assertFalse(lock.is_locked(self.hass, FRONT))

View file

@ -40,13 +40,13 @@ class TestLockMQTT(unittest.TestCase):
self.assertIsNone(state.attributes.get(ATTR_ASSUMED_STATE)) self.assertIsNone(state.attributes.get(ATTR_ASSUMED_STATE))
fire_mqtt_message(self.hass, 'state-topic', 'LOCK') fire_mqtt_message(self.hass, 'state-topic', 'LOCK')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('lock.test') state = self.hass.states.get('lock.test')
self.assertEqual(STATE_LOCKED, state.state) self.assertEqual(STATE_LOCKED, state.state)
fire_mqtt_message(self.hass, 'state-topic', 'UNLOCK') fire_mqtt_message(self.hass, 'state-topic', 'UNLOCK')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('lock.test') state = self.hass.states.get('lock.test')
self.assertEqual(STATE_UNLOCKED, state.state) self.assertEqual(STATE_UNLOCKED, state.state)
@ -70,7 +70,7 @@ class TestLockMQTT(unittest.TestCase):
self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE)) self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE))
lock.lock(self.hass, 'lock.test') lock.lock(self.hass, 'lock.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('command-topic', 'LOCK', 2, False), self.assertEqual(('command-topic', 'LOCK', 2, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -78,7 +78,7 @@ class TestLockMQTT(unittest.TestCase):
self.assertEqual(STATE_LOCKED, state.state) self.assertEqual(STATE_LOCKED, state.state)
lock.unlock(self.hass, 'lock.test') lock.unlock(self.hass, 'lock.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('command-topic', 'UNLOCK', 2, False), self.assertEqual(('command-topic', 'UNLOCK', 2, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -104,13 +104,13 @@ class TestLockMQTT(unittest.TestCase):
self.assertEqual(STATE_UNLOCKED, state.state) self.assertEqual(STATE_UNLOCKED, state.state)
fire_mqtt_message(self.hass, 'state-topic', '{"val":"LOCK"}') fire_mqtt_message(self.hass, 'state-topic', '{"val":"LOCK"}')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('lock.test') state = self.hass.states.get('lock.test')
self.assertEqual(STATE_LOCKED, state.state) self.assertEqual(STATE_LOCKED, state.state)
fire_mqtt_message(self.hass, 'state-topic', '{"val":"UNLOCK"}') fire_mqtt_message(self.hass, 'state-topic', '{"val":"UNLOCK"}')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('lock.test') state = self.hass.states.get('lock.test')
self.assertEqual(STATE_UNLOCKED, state.state) self.assertEqual(STATE_UNLOCKED, state.state)

View file

@ -60,12 +60,12 @@ class TestDemoMediaPlayer(unittest.TestCase):
assert 'dvd' == state.attributes.get('source') assert 'dvd' == state.attributes.get('source')
mp.select_source(self.hass, None, entity_id) mp.select_source(self.hass, None, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(entity_id) state = self.hass.states.get(entity_id)
assert 'dvd' == state.attributes.get('source') assert 'dvd' == state.attributes.get('source')
mp.select_source(self.hass, 'xbox', entity_id) mp.select_source(self.hass, 'xbox', entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(entity_id) state = self.hass.states.get(entity_id)
assert 'xbox' == state.attributes.get('source') assert 'xbox' == state.attributes.get('source')
@ -75,7 +75,7 @@ class TestDemoMediaPlayer(unittest.TestCase):
assert self.hass.states.is_state(entity_id, 'playing') assert self.hass.states.is_state(entity_id, 'playing')
mp.clear_playlist(self.hass, entity_id) mp.clear_playlist(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert self.hass.states.is_state(entity_id, 'off') assert self.hass.states.is_state(entity_id, 'off')
def test_volume_services(self): def test_volume_services(self):
@ -85,34 +85,34 @@ class TestDemoMediaPlayer(unittest.TestCase):
assert 1.0 == state.attributes.get('volume_level') assert 1.0 == state.attributes.get('volume_level')
mp.set_volume_level(self.hass, None, entity_id) mp.set_volume_level(self.hass, None, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(entity_id) state = self.hass.states.get(entity_id)
assert 1.0 == state.attributes.get('volume_level') assert 1.0 == state.attributes.get('volume_level')
mp.set_volume_level(self.hass, 0.5, entity_id) mp.set_volume_level(self.hass, 0.5, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(entity_id) state = self.hass.states.get(entity_id)
assert 0.5 == state.attributes.get('volume_level') assert 0.5 == state.attributes.get('volume_level')
mp.volume_down(self.hass, entity_id) mp.volume_down(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(entity_id) state = self.hass.states.get(entity_id)
assert 0.4 == state.attributes.get('volume_level') assert 0.4 == state.attributes.get('volume_level')
mp.volume_up(self.hass, entity_id) mp.volume_up(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(entity_id) state = self.hass.states.get(entity_id)
assert 0.5 == state.attributes.get('volume_level') assert 0.5 == state.attributes.get('volume_level')
assert False is state.attributes.get('is_volume_muted') assert False is state.attributes.get('is_volume_muted')
mp.mute_volume(self.hass, None, entity_id) mp.mute_volume(self.hass, None, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(entity_id) state = self.hass.states.get(entity_id)
assert False is state.attributes.get('is_volume_muted') assert False is state.attributes.get('is_volume_muted')
mp.mute_volume(self.hass, True, entity_id) mp.mute_volume(self.hass, True, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(entity_id) state = self.hass.states.get(entity_id)
assert True is state.attributes.get('is_volume_muted') assert True is state.attributes.get('is_volume_muted')
@ -122,16 +122,16 @@ class TestDemoMediaPlayer(unittest.TestCase):
assert self.hass.states.is_state(entity_id, 'playing') assert self.hass.states.is_state(entity_id, 'playing')
mp.turn_off(self.hass, entity_id) mp.turn_off(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert self.hass.states.is_state(entity_id, 'off') assert self.hass.states.is_state(entity_id, 'off')
assert not mp.is_on(self.hass, entity_id) assert not mp.is_on(self.hass, entity_id)
mp.turn_on(self.hass, entity_id) mp.turn_on(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert self.hass.states.is_state(entity_id, 'playing') assert self.hass.states.is_state(entity_id, 'playing')
mp.toggle(self.hass, entity_id) mp.toggle(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert self.hass.states.is_state(entity_id, 'off') assert self.hass.states.is_state(entity_id, 'off')
assert not mp.is_on(self.hass, entity_id) assert not mp.is_on(self.hass, entity_id)
@ -141,19 +141,19 @@ class TestDemoMediaPlayer(unittest.TestCase):
assert self.hass.states.is_state(entity_id, 'playing') assert self.hass.states.is_state(entity_id, 'playing')
mp.media_pause(self.hass, entity_id) mp.media_pause(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert self.hass.states.is_state(entity_id, 'paused') assert self.hass.states.is_state(entity_id, 'paused')
mp.media_play_pause(self.hass, entity_id) mp.media_play_pause(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert self.hass.states.is_state(entity_id, 'playing') assert self.hass.states.is_state(entity_id, 'playing')
mp.media_play_pause(self.hass, entity_id) mp.media_play_pause(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert self.hass.states.is_state(entity_id, 'paused') assert self.hass.states.is_state(entity_id, 'paused')
mp.media_play(self.hass, entity_id) mp.media_play(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert self.hass.states.is_state(entity_id, 'playing') assert self.hass.states.is_state(entity_id, 'playing')
def test_prev_next_track(self): def test_prev_next_track(self):
@ -165,21 +165,21 @@ class TestDemoMediaPlayer(unittest.TestCase):
state.attributes.get('supported_media_commands')) state.attributes.get('supported_media_commands'))
mp.media_next_track(self.hass, entity_id) mp.media_next_track(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(entity_id) state = self.hass.states.get(entity_id)
assert 2 == state.attributes.get('media_track') assert 2 == state.attributes.get('media_track')
assert 0 < (mp.SUPPORT_PREVIOUS_TRACK & assert 0 < (mp.SUPPORT_PREVIOUS_TRACK &
state.attributes.get('supported_media_commands')) state.attributes.get('supported_media_commands'))
mp.media_next_track(self.hass, entity_id) mp.media_next_track(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(entity_id) state = self.hass.states.get(entity_id)
assert 3 == state.attributes.get('media_track') assert 3 == state.attributes.get('media_track')
assert 0 < (mp.SUPPORT_PREVIOUS_TRACK & assert 0 < (mp.SUPPORT_PREVIOUS_TRACK &
state.attributes.get('supported_media_commands')) state.attributes.get('supported_media_commands'))
mp.media_previous_track(self.hass, entity_id) mp.media_previous_track(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(entity_id) state = self.hass.states.get(entity_id)
assert 2 == state.attributes.get('media_track') assert 2 == state.attributes.get('media_track')
assert 0 < (mp.SUPPORT_PREVIOUS_TRACK & assert 0 < (mp.SUPPORT_PREVIOUS_TRACK &
@ -193,14 +193,14 @@ class TestDemoMediaPlayer(unittest.TestCase):
state.attributes.get('supported_media_commands')) state.attributes.get('supported_media_commands'))
mp.media_next_track(self.hass, ent_id) mp.media_next_track(self.hass, ent_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ent_id) state = self.hass.states.get(ent_id)
assert 2 == state.attributes.get('media_episode') assert 2 == state.attributes.get('media_episode')
assert 0 < (mp.SUPPORT_PREVIOUS_TRACK & assert 0 < (mp.SUPPORT_PREVIOUS_TRACK &
state.attributes.get('supported_media_commands')) state.attributes.get('supported_media_commands'))
mp.media_previous_track(self.hass, ent_id) mp.media_previous_track(self.hass, ent_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ent_id) state = self.hass.states.get(ent_id)
assert 1 == state.attributes.get('media_episode') assert 1 == state.attributes.get('media_episode')
assert 0 == (mp.SUPPORT_PREVIOUS_TRACK & assert 0 == (mp.SUPPORT_PREVIOUS_TRACK &
@ -231,14 +231,14 @@ class TestDemoMediaPlayer(unittest.TestCase):
assert state.attributes.get('media_content_id') is not None assert state.attributes.get('media_content_id') is not None
mp.play_media(self.hass, None, 'some_id', ent_id) mp.play_media(self.hass, None, 'some_id', ent_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ent_id) state = self.hass.states.get(ent_id)
assert 0 < (mp.SUPPORT_PLAY_MEDIA & assert 0 < (mp.SUPPORT_PLAY_MEDIA &
state.attributes.get('supported_media_commands')) state.attributes.get('supported_media_commands'))
assert not 'some_id' == state.attributes.get('media_content_id') assert not 'some_id' == state.attributes.get('media_content_id')
mp.play_media(self.hass, 'youtube', 'some_id', ent_id) mp.play_media(self.hass, 'youtube', 'some_id', ent_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ent_id) state = self.hass.states.get(ent_id)
assert 0 < (mp.SUPPORT_PLAY_MEDIA & assert 0 < (mp.SUPPORT_PLAY_MEDIA &
state.attributes.get('supported_media_commands')) state.attributes.get('supported_media_commands'))
@ -246,8 +246,8 @@ class TestDemoMediaPlayer(unittest.TestCase):
assert not mock_seek.called assert not mock_seek.called
mp.media_seek(self.hass, None, ent_id) mp.media_seek(self.hass, None, ent_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert not mock_seek.called assert not mock_seek.called
mp.media_seek(self.hass, 100, ent_id) mp.media_seek(self.hass, 100, ent_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert mock_seek.called assert mock_seek.called

View file

@ -36,15 +36,15 @@ class TestMQTT(unittest.TestCase):
def test_client_starts_on_home_assistant_start(self): def test_client_starts_on_home_assistant_start(self):
""""Test if client start on HA launch.""" """"Test if client start on HA launch."""
self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.bus.fire(EVENT_HOMEASSISTANT_START)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(mqtt.MQTT_CLIENT.start.called) self.assertTrue(mqtt.MQTT_CLIENT.start.called)
def test_client_stops_on_home_assistant_start(self): def test_client_stops_on_home_assistant_start(self):
"""Test if client stops on HA launch.""" """Test if client stops on HA launch."""
self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.bus.fire(EVENT_HOMEASSISTANT_START)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.bus.fire(EVENT_HOMEASSISTANT_STOP) self.hass.bus.fire(EVENT_HOMEASSISTANT_STOP)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(mqtt.MQTT_CLIENT.stop.called) self.assertTrue(mqtt.MQTT_CLIENT.stop.called)
def test_setup_fails_if_no_connect_broker(self): def test_setup_fails_if_no_connect_broker(self):
@ -75,7 +75,7 @@ class TestMQTT(unittest.TestCase):
mqtt.publish(self.hass, 'test-topic', 'test-payload') mqtt.publish(self.hass, 'test-topic', 'test-payload')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.assertEqual( self.assertEqual(
@ -91,7 +91,7 @@ class TestMQTT(unittest.TestCase):
ATTR_DOMAIN: mqtt.DOMAIN, ATTR_DOMAIN: mqtt.DOMAIN,
ATTR_SERVICE: mqtt.SERVICE_PUBLISH ATTR_SERVICE: mqtt.SERVICE_PUBLISH
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(not mqtt.MQTT_CLIENT.publish.called) self.assertTrue(not mqtt.MQTT_CLIENT.publish.called)
def test_service_call_with_template_payload_renders_template(self): def test_service_call_with_template_payload_renders_template(self):
@ -100,7 +100,7 @@ class TestMQTT(unittest.TestCase):
If 'payload_template' is provided and 'payload' is not, then render it. If 'payload_template' is provided and 'payload' is not, then render it.
""" """
mqtt.publish_template(self.hass, "test/topic", "{{ 1+1 }}") mqtt.publish_template(self.hass, "test/topic", "{{ 1+1 }}")
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(mqtt.MQTT_CLIENT.publish.called) self.assertTrue(mqtt.MQTT_CLIENT.publish.called)
self.assertEqual(mqtt.MQTT_CLIENT.publish.call_args[0][1], "2") self.assertEqual(mqtt.MQTT_CLIENT.publish.call_args[0][1], "2")
@ -153,7 +153,7 @@ class TestMQTT(unittest.TestCase):
fire_mqtt_message(self.hass, 'test-topic', 'test-payload') fire_mqtt_message(self.hass, 'test-topic', 'test-payload')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.assertEqual('test-topic', self.calls[0][0]) self.assertEqual('test-topic', self.calls[0][0])
self.assertEqual('test-payload', self.calls[0][1]) self.assertEqual('test-payload', self.calls[0][1])
@ -162,7 +162,7 @@ class TestMQTT(unittest.TestCase):
fire_mqtt_message(self.hass, 'test-topic', 'test-payload') fire_mqtt_message(self.hass, 'test-topic', 'test-payload')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_subscribe_topic_not_match(self): def test_subscribe_topic_not_match(self):
@ -171,7 +171,7 @@ class TestMQTT(unittest.TestCase):
fire_mqtt_message(self.hass, 'another-test-topic', 'test-payload') fire_mqtt_message(self.hass, 'another-test-topic', 'test-payload')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_subscribe_topic_level_wildcard(self): def test_subscribe_topic_level_wildcard(self):
@ -180,7 +180,7 @@ class TestMQTT(unittest.TestCase):
fire_mqtt_message(self.hass, 'test-topic/bier/on', 'test-payload') fire_mqtt_message(self.hass, 'test-topic/bier/on', 'test-payload')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.assertEqual('test-topic/bier/on', self.calls[0][0]) self.assertEqual('test-topic/bier/on', self.calls[0][0])
self.assertEqual('test-payload', self.calls[0][1]) self.assertEqual('test-payload', self.calls[0][1])
@ -191,7 +191,7 @@ class TestMQTT(unittest.TestCase):
fire_mqtt_message(self.hass, 'test-topic/bier', 'test-payload') fire_mqtt_message(self.hass, 'test-topic/bier', 'test-payload')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_subscribe_topic_subtree_wildcard_subtree_topic(self): def test_subscribe_topic_subtree_wildcard_subtree_topic(self):
@ -200,7 +200,7 @@ class TestMQTT(unittest.TestCase):
fire_mqtt_message(self.hass, 'test-topic/bier/on', 'test-payload') fire_mqtt_message(self.hass, 'test-topic/bier/on', 'test-payload')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.assertEqual('test-topic/bier/on', self.calls[0][0]) self.assertEqual('test-topic/bier/on', self.calls[0][0])
self.assertEqual('test-payload', self.calls[0][1]) self.assertEqual('test-payload', self.calls[0][1])
@ -211,7 +211,7 @@ class TestMQTT(unittest.TestCase):
fire_mqtt_message(self.hass, 'test-topic', 'test-payload') fire_mqtt_message(self.hass, 'test-topic', 'test-payload')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.assertEqual('test-topic', self.calls[0][0]) self.assertEqual('test-topic', self.calls[0][0])
self.assertEqual('test-payload', self.calls[0][1]) self.assertEqual('test-payload', self.calls[0][1])
@ -222,7 +222,7 @@ class TestMQTT(unittest.TestCase):
fire_mqtt_message(self.hass, 'another-test-topic', 'test-payload') fire_mqtt_message(self.hass, 'another-test-topic', 'test-payload')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
@ -260,7 +260,7 @@ class TestMQTTCallbacks(unittest.TestCase):
message = MQTTMessage('test_topic', 1, 'Hello World!'.encode('utf-8')) message = MQTTMessage('test_topic', 1, 'Hello World!'.encode('utf-8'))
mqtt.MQTT_CLIENT._mqtt_on_message(None, {'hass': self.hass}, message) mqtt.MQTT_CLIENT._mqtt_on_message(None, {'hass': self.hass}, message)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(calls)) self.assertEqual(1, len(calls))
last_event = calls[0] last_event = calls[0]

View file

@ -51,8 +51,10 @@ class TestCommandLine(unittest.TestCase):
} }
})) }))
self.assertTrue(
self.hass.services.call('notify', 'test', {'message': message}, self.hass.services.call('notify', 'test', {'message': message},
blocking=True) blocking=True)
)
result = open(filename).read() result = open(filename).read()
# the echo command adds a line break # the echo command adds a line break
@ -69,6 +71,8 @@ class TestCommandLine(unittest.TestCase):
} }
})) }))
self.assertTrue(
self.hass.services.call('notify', 'test', {'message': 'error'}, self.hass.services.call('notify', 'test', {'message': 'error'},
blocking=True) blocking=True)
)
self.assertEqual(1, mock_error.call_count) self.assertEqual(1, mock_error.call_count)

View file

@ -41,7 +41,7 @@ class TestNotifyDemo(unittest.TestCase):
def test_sending_none_message(self): def test_sending_none_message(self):
"""Test send with None as message.""" """Test send with None as message."""
notify.send_message(self.hass, None) notify.send_message(self.hass, None)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(len(self.events) == 0) self.assertTrue(len(self.events) == 0)
def test_sending_templated_message(self): def test_sending_templated_message(self):
@ -49,7 +49,7 @@ class TestNotifyDemo(unittest.TestCase):
self.hass.states.set('sensor.temperature', 10) self.hass.states.set('sensor.temperature', 10)
notify.send_message(self.hass, '{{ states.sensor.temperature.state }}', notify.send_message(self.hass, '{{ states.sensor.temperature.state }}',
'{{ states.sensor.temperature.name }}') '{{ states.sensor.temperature.name }}')
self.hass.pool.block_till_done() self.hass.block_till_done()
last_event = self.events[-1] last_event = self.events[-1]
self.assertEqual(last_event.data[notify.ATTR_TITLE], 'temperature') self.assertEqual(last_event.data[notify.ATTR_TITLE], 'temperature')
self.assertEqual(last_event.data[notify.ATTR_MESSAGE], '10') self.assertEqual(last_event.data[notify.ATTR_MESSAGE], '10')
@ -58,7 +58,7 @@ class TestNotifyDemo(unittest.TestCase):
"""Test that all data from the service gets forwarded to service.""" """Test that all data from the service gets forwarded to service."""
notify.send_message(self.hass, 'my message', 'my title', notify.send_message(self.hass, 'my message', 'my title',
{'hello': 'world'}) {'hello': 'world'})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(len(self.events) == 1) self.assertTrue(len(self.events) == 1)
data = self.events[0].data data = self.events[0].data
assert { assert {
@ -87,7 +87,7 @@ data_template:
conf = yaml.load_yaml(fp.name) conf = yaml.load_yaml(fp.name)
script.call_from_config(self.hass, conf) script.call_from_config(self.hass, conf)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(len(self.events) == 1) self.assertTrue(len(self.events) == 1)
assert { assert {
'message': 'Test 123 4', 'message': 'Test 123 4',
@ -145,7 +145,7 @@ data_template:
'title': 'my title', 'title': 'my title',
'data': {'hello': 'world'}}) 'data': {'hello': 'world'}})
self.hass.pool.block_till_done() self.hass.block_till_done()
data = self.calls[0][0].data data = self.calls[0][0].data

View file

@ -48,7 +48,7 @@ class TestNotifyGroup(unittest.TestCase):
def test_send_message_to_group(self): def test_send_message_to_group(self):
"""Test sending a message to a notify group.""" """Test sending a message to a notify group."""
self.service.send_message('Hello', title='Test notification') self.service.send_message('Hello', title='Test notification')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(len(self.events) == 2) self.assertTrue(len(self.events) == 2)
last_event = self.events[-1] last_event = self.events[-1]
self.assertEqual(last_event.data[notify.ATTR_TITLE], self.assertEqual(last_event.data[notify.ATTR_TITLE],
@ -60,7 +60,7 @@ class TestNotifyGroup(unittest.TestCase):
notify_data = {'hello': 'world'} notify_data = {'hello': 'world'}
self.service.send_message('Hello', title='Test notification', self.service.send_message('Hello', title='Test notification',
data=notify_data) data=notify_data)
self.hass.pool.block_till_done() self.hass.block_till_done()
last_event = self.events[-1] last_event = self.events[-1]
self.assertEqual(last_event.data[notify.ATTR_TITLE], self.assertEqual(last_event.data[notify.ATTR_TITLE],
'Test notification') 'Test notification')
@ -72,7 +72,7 @@ class TestNotifyGroup(unittest.TestCase):
notify_data = {'hello': 'world'} notify_data = {'hello': 'world'}
self.service.send_message('Hello', title='Test notification', self.service.send_message('Hello', title='Test notification',
data=notify_data) data=notify_data)
self.hass.pool.block_till_done() self.hass.block_till_done()
data = self.events[-1].data data = self.events[-1].data
assert { assert {
'message': 'Hello', 'message': 'Hello',

View file

@ -37,7 +37,7 @@ class TestRecorder(unittest.TestCase):
five_days_ago = now - timedelta(days=5) five_days_ago = now - timedelta(days=5)
attributes = {'test_attr': 5, 'test_attr_10': 'nice'} attributes = {'test_attr': 5, 'test_attr_10': 'nice'}
self.hass.pool.block_till_done() self.hass.block_till_done()
recorder._INSTANCE.block_till_done() recorder._INSTANCE.block_till_done()
for event_id in range(5): for event_id in range(5):
@ -67,7 +67,7 @@ class TestRecorder(unittest.TestCase):
five_days_ago = now - timedelta(days=5) five_days_ago = now - timedelta(days=5)
event_data = {'test_attr': 5, 'test_attr_10': 'nice'} event_data = {'test_attr': 5, 'test_attr_10': 'nice'}
self.hass.pool.block_till_done() self.hass.block_till_done()
recorder._INSTANCE.block_till_done() recorder._INSTANCE.block_till_done()
for event_id in range(5): for event_id in range(5):
if event_id < 2: if event_id < 2:
@ -93,7 +93,7 @@ class TestRecorder(unittest.TestCase):
self.hass.states.set(entity_id, state, attributes) self.hass.states.set(entity_id, state, attributes)
self.hass.pool.block_till_done() self.hass.block_till_done()
recorder._INSTANCE.block_till_done() recorder._INSTANCE.block_till_done()
db_states = recorder.query('States') db_states = recorder.query('States')
@ -120,7 +120,7 @@ class TestRecorder(unittest.TestCase):
self.hass.bus.fire(event_type, event_data) self.hass.bus.fire(event_type, event_data)
self.hass.pool.block_till_done() self.hass.block_till_done()
recorder._INSTANCE.block_till_done() recorder._INSTANCE.block_till_done()
db_events = recorder.execute( db_events = recorder.execute(

View file

@ -5,10 +5,10 @@ import tempfile
import unittest import unittest
from unittest import mock from unittest import mock
import homeassistant.core as ha
import homeassistant.components.rollershutter as rollershutter import homeassistant.components.rollershutter as rollershutter
from homeassistant.components.rollershutter import ( from homeassistant.components.rollershutter import (
command_line as cmd_rs) command_line as cmd_rs)
from tests.common import get_test_home_assistant
class TestCommandRollerShutter(unittest.TestCase): class TestCommandRollerShutter(unittest.TestCase):
@ -16,7 +16,7 @@ class TestCommandRollerShutter(unittest.TestCase):
def setup_method(self, method): def setup_method(self, method):
"""Setup things to be run when tests are started.""" """Setup things to be run when tests are started."""
self.hass = ha.HomeAssistant() self.hass = get_test_home_assistant()
self.hass.config.latitude = 32.87336 self.hass.config.latitude = 32.87336
self.hass.config.longitude = 117.22743 self.hass.config.longitude = 117.22743
self.rs = cmd_rs.CommandRollershutter(self.hass, 'foo', self.rs = cmd_rs.CommandRollershutter(self.hass, 'foo',
@ -66,19 +66,19 @@ class TestCommandRollerShutter(unittest.TestCase):
self.assertEqual('unknown', state.state) self.assertEqual('unknown', state.state)
rollershutter.move_up(self.hass, 'rollershutter.test') rollershutter.move_up(self.hass, 'rollershutter.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('rollershutter.test') state = self.hass.states.get('rollershutter.test')
self.assertEqual('open', state.state) self.assertEqual('open', state.state)
rollershutter.move_down(self.hass, 'rollershutter.test') rollershutter.move_down(self.hass, 'rollershutter.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('rollershutter.test') state = self.hass.states.get('rollershutter.test')
self.assertEqual('open', state.state) self.assertEqual('open', state.state)
rollershutter.stop(self.hass, 'rollershutter.test') rollershutter.stop(self.hass, 'rollershutter.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('rollershutter.test') state = self.hass.states.get('rollershutter.test')
self.assertEqual('closed', state.state) self.assertEqual('closed', state.state)

View file

@ -23,7 +23,7 @@ class TestRollershutterDemo(unittest.TestCase):
entity.move_up() entity.move_up()
fire_time_changed(self.hass, dt_util.utcnow()) fire_time_changed(self.hass, dt_util.utcnow())
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(90, entity.current_position) self.assertEqual(90, entity.current_position)
def test_move_down(self): def test_move_down(self):
@ -32,7 +32,7 @@ class TestRollershutterDemo(unittest.TestCase):
entity.move_down() entity.move_down()
fire_time_changed(self.hass, dt_util.utcnow()) fire_time_changed(self.hass, dt_util.utcnow())
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(10, entity.current_position) self.assertEqual(10, entity.current_position)
def test_move_position(self): def test_move_position(self):
@ -41,7 +41,7 @@ class TestRollershutterDemo(unittest.TestCase):
entity.move_position(10) entity.move_position(10)
fire_time_changed(self.hass, dt_util.utcnow()) fire_time_changed(self.hass, dt_util.utcnow())
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(10, entity.current_position) self.assertEqual(10, entity.current_position)
def test_stop(self): def test_stop(self):
@ -51,5 +51,5 @@ class TestRollershutterDemo(unittest.TestCase):
entity.stop() entity.stop()
fire_time_changed(self.hass, dt_util.utcnow()) fire_time_changed(self.hass, dt_util.utcnow())
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, entity.current_position) self.assertEqual(0, entity.current_position)

View file

@ -41,19 +41,19 @@ class TestRollershutterMQTT(unittest.TestCase):
self.assertEqual(STATE_UNKNOWN, state.state) self.assertEqual(STATE_UNKNOWN, state.state)
fire_mqtt_message(self.hass, 'state-topic', '0') fire_mqtt_message(self.hass, 'state-topic', '0')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('rollershutter.test') state = self.hass.states.get('rollershutter.test')
self.assertEqual(STATE_CLOSED, state.state) self.assertEqual(STATE_CLOSED, state.state)
fire_mqtt_message(self.hass, 'state-topic', '50') fire_mqtt_message(self.hass, 'state-topic', '50')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('rollershutter.test') state = self.hass.states.get('rollershutter.test')
self.assertEqual(STATE_OPEN, state.state) self.assertEqual(STATE_OPEN, state.state)
fire_mqtt_message(self.hass, 'state-topic', '100') fire_mqtt_message(self.hass, 'state-topic', '100')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('rollershutter.test') state = self.hass.states.get('rollershutter.test')
self.assertEqual(STATE_OPEN, state.state) self.assertEqual(STATE_OPEN, state.state)
@ -75,7 +75,7 @@ class TestRollershutterMQTT(unittest.TestCase):
self.assertEqual(STATE_UNKNOWN, state.state) self.assertEqual(STATE_UNKNOWN, state.state)
rollershutter.move_up(self.hass, 'rollershutter.test') rollershutter.move_up(self.hass, 'rollershutter.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('command-topic', 'UP', 2, False), self.assertEqual(('command-topic', 'UP', 2, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -99,7 +99,7 @@ class TestRollershutterMQTT(unittest.TestCase):
self.assertEqual(STATE_UNKNOWN, state.state) self.assertEqual(STATE_UNKNOWN, state.state)
rollershutter.move_down(self.hass, 'rollershutter.test') rollershutter.move_down(self.hass, 'rollershutter.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('command-topic', 'DOWN', 2, False), self.assertEqual(('command-topic', 'DOWN', 2, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -123,7 +123,7 @@ class TestRollershutterMQTT(unittest.TestCase):
self.assertEqual(STATE_UNKNOWN, state.state) self.assertEqual(STATE_UNKNOWN, state.state)
rollershutter.stop(self.hass, 'rollershutter.test') rollershutter.stop(self.hass, 'rollershutter.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('command-topic', 'STOP', 2, False), self.assertEqual(('command-topic', 'STOP', 2, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -150,25 +150,25 @@ class TestRollershutterMQTT(unittest.TestCase):
self.assertFalse('current_position' in state_attributes_dict) self.assertFalse('current_position' in state_attributes_dict)
fire_mqtt_message(self.hass, 'state-topic', '0') fire_mqtt_message(self.hass, 'state-topic', '0')
self.hass.pool.block_till_done() self.hass.block_till_done()
current_position = self.hass.states.get( current_position = self.hass.states.get(
'rollershutter.test').attributes['current_position'] 'rollershutter.test').attributes['current_position']
self.assertEqual(0, current_position) self.assertEqual(0, current_position)
fire_mqtt_message(self.hass, 'state-topic', '50') fire_mqtt_message(self.hass, 'state-topic', '50')
self.hass.pool.block_till_done() self.hass.block_till_done()
current_position = self.hass.states.get( current_position = self.hass.states.get(
'rollershutter.test').attributes['current_position'] 'rollershutter.test').attributes['current_position']
self.assertEqual(50, current_position) self.assertEqual(50, current_position)
fire_mqtt_message(self.hass, 'state-topic', '101') fire_mqtt_message(self.hass, 'state-topic', '101')
self.hass.pool.block_till_done() self.hass.block_till_done()
current_position = self.hass.states.get( current_position = self.hass.states.get(
'rollershutter.test').attributes['current_position'] 'rollershutter.test').attributes['current_position']
self.assertEqual(50, current_position) self.assertEqual(50, current_position)
fire_mqtt_message(self.hass, 'state-topic', 'non-numeric') fire_mqtt_message(self.hass, 'state-topic', 'non-numeric')
self.hass.pool.block_till_done() self.hass.block_till_done()
current_position = self.hass.states.get( current_position = self.hass.states.get(
'rollershutter.test').attributes['current_position'] 'rollershutter.test').attributes['current_position']
self.assertEqual(50, current_position) self.assertEqual(50, current_position)

View file

@ -8,9 +8,8 @@ from requests.exceptions import HTTPError
import requests_mock import requests_mock
from homeassistant.components.sensor import forecast from homeassistant.components.sensor import forecast
from homeassistant import core as ha
from tests.common import load_fixture from tests.common import load_fixture, get_test_home_assistant
class TestForecastSetup(unittest.TestCase): class TestForecastSetup(unittest.TestCase):
@ -18,7 +17,7 @@ class TestForecastSetup(unittest.TestCase):
def setUp(self): def setUp(self):
"""Initialize values for this testcase class.""" """Initialize values for this testcase class."""
self.hass = ha.HomeAssistant() self.hass = get_test_home_assistant()
self.key = 'foo' self.key = 'foo'
self.config = { self.config = {
'api_key': 'foo', 'api_key': 'foo',

View file

@ -22,7 +22,7 @@ class TestSensorMoldIndicator(unittest.TestCase):
{ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS}) {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
self.hass.states.set('test.indoorhumidity', '50', self.hass.states.set('test.indoorhumidity', '50',
{ATTR_UNIT_OF_MEASUREMENT: '%'}) {ATTR_UNIT_OF_MEASUREMENT: '%'})
self.hass.pool.block_till_done() self.hass.block_till_done()
def tearDown(self): def tearDown(self):
"""Stop down everything that was started.""" """Stop down everything that was started."""
@ -112,15 +112,15 @@ class TestSensorMoldIndicator(unittest.TestCase):
self.hass.states.set('test.indoortemp', '30', self.hass.states.set('test.indoortemp', '30',
{ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS}) {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
self.hass.pool.block_till_done() self.hass.block_till_done()
assert self.hass.states.get('sensor.mold_indicator').state == '90' assert self.hass.states.get('sensor.mold_indicator').state == '90'
self.hass.states.set('test.outdoortemp', '25', self.hass.states.set('test.outdoortemp', '25',
{ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS}) {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
self.hass.pool.block_till_done() self.hass.block_till_done()
assert self.hass.states.get('sensor.mold_indicator').state == '57' assert self.hass.states.get('sensor.mold_indicator').state == '57'
self.hass.states.set('test.indoorhumidity', '20', self.hass.states.set('test.indoorhumidity', '20',
{ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS}) {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
self.hass.pool.block_till_done() self.hass.block_till_done()
assert self.hass.states.get('sensor.mold_indicator').state == '23' assert self.hass.states.get('sensor.mold_indicator').state == '23'

View file

@ -33,7 +33,7 @@ class TestSensorMQTT(unittest.TestCase):
}) })
fire_mqtt_message(self.hass, 'test-topic', '100') fire_mqtt_message(self.hass, 'test-topic', '100')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('sensor.test') state = self.hass.states.get('sensor.test')
self.assertEqual('100', state.state) self.assertEqual('100', state.state)
@ -54,7 +54,7 @@ class TestSensorMQTT(unittest.TestCase):
}) })
fire_mqtt_message(self.hass, 'test-topic', '{ "val": "100" }') fire_mqtt_message(self.hass, 'test-topic', '{ "val": "100" }')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('sensor.test') state = self.hass.states.get('sensor.test')
self.assertEqual('100', state.state) self.assertEqual('100', state.state)

View file

@ -73,7 +73,7 @@ class TestMQTTRoomSensor(unittest.TestCase):
"""Test the sending of a message.""" """Test the sending of a message."""
fire_mqtt_message( fire_mqtt_message(
self.hass, topic, json.dumps(message)) self.hass, topic, json.dumps(message))
self.hass.pool.block_till_done() self.hass.block_till_done()
def assert_state(self, room): def assert_state(self, room):
"""Test the assertion of a room state.""" """Test the assertion of a room state."""

View file

@ -33,7 +33,7 @@ class TestTemplateSensor:
assert state.state == 'It .' assert state.state == 'It .'
self.hass.states.set('sensor.test_state', 'Works') self.hass.states.set('sensor.test_state', 'Works')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('sensor.test_template_sensor') state = self.hass.states.get('sensor.test_template_sensor')
assert state.state == 'It Works.' assert state.state == 'It Works.'

View file

@ -3,7 +3,8 @@ import unittest
from homeassistant.components.sensor import wunderground from homeassistant.components.sensor import wunderground
from homeassistant.const import TEMP_CELSIUS from homeassistant.const import TEMP_CELSIUS
from homeassistant import core as ha
from tests.common import get_test_home_assistant
VALID_CONFIG_PWS = { VALID_CONFIG_PWS = {
'platform': 'wunderground', 'platform': 'wunderground',
@ -90,7 +91,7 @@ class TestWundergroundSetup(unittest.TestCase):
def setUp(self): def setUp(self):
"""Initialize values for this testcase class.""" """Initialize values for this testcase class."""
self.DEVICES = [] self.DEVICES = []
self.hass = ha.HomeAssistant() self.hass = get_test_home_assistant()
self.key = 'foo' self.key = 'foo'
self.config = VALID_CONFIG_PWS self.config = VALID_CONFIG_PWS
self.lat = 37.8267 self.lat = 37.8267

View file

@ -43,13 +43,13 @@ class TestCommandSwitch(unittest.TestCase):
self.assertEqual(STATE_OFF, state.state) self.assertEqual(STATE_OFF, state.state)
switch.turn_on(self.hass, 'switch.test') switch.turn_on(self.hass, 'switch.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('switch.test') state = self.hass.states.get('switch.test')
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)
switch.turn_off(self.hass, 'switch.test') switch.turn_off(self.hass, 'switch.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('switch.test') state = self.hass.states.get('switch.test')
self.assertEqual(STATE_OFF, state.state) self.assertEqual(STATE_OFF, state.state)
@ -77,13 +77,13 @@ class TestCommandSwitch(unittest.TestCase):
self.assertEqual(STATE_OFF, state.state) self.assertEqual(STATE_OFF, state.state)
switch.turn_on(self.hass, 'switch.test') switch.turn_on(self.hass, 'switch.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('switch.test') state = self.hass.states.get('switch.test')
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)
switch.turn_off(self.hass, 'switch.test') switch.turn_off(self.hass, 'switch.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('switch.test') state = self.hass.states.get('switch.test')
self.assertEqual(STATE_OFF, state.state) self.assertEqual(STATE_OFF, state.state)
@ -113,13 +113,13 @@ class TestCommandSwitch(unittest.TestCase):
self.assertEqual(STATE_OFF, state.state) self.assertEqual(STATE_OFF, state.state)
switch.turn_on(self.hass, 'switch.test') switch.turn_on(self.hass, 'switch.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('switch.test') state = self.hass.states.get('switch.test')
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)
switch.turn_off(self.hass, 'switch.test') switch.turn_off(self.hass, 'switch.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('switch.test') state = self.hass.states.get('switch.test')
self.assertEqual(STATE_OFF, state.state) self.assertEqual(STATE_OFF, state.state)
@ -146,13 +146,13 @@ class TestCommandSwitch(unittest.TestCase):
self.assertEqual(STATE_OFF, state.state) self.assertEqual(STATE_OFF, state.state)
switch.turn_on(self.hass, 'switch.test') switch.turn_on(self.hass, 'switch.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('switch.test') state = self.hass.states.get('switch.test')
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)
switch.turn_off(self.hass, 'switch.test') switch.turn_off(self.hass, 'switch.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('switch.test') state = self.hass.states.get('switch.test')
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)

View file

@ -102,7 +102,7 @@ class TestSwitchFlux(unittest.TestCase):
turn_on_calls = mock_service( turn_on_calls = mock_service(
self.hass, light.DOMAIN, SERVICE_TURN_ON) self.hass, light.DOMAIN, SERVICE_TURN_ON)
fire_time_changed(self.hass, test_time) fire_time_changed(self.hass, test_time)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(turn_on_calls)) self.assertEqual(0, len(turn_on_calls))
def test_flux_before_sunrise(self): def test_flux_before_sunrise(self):
@ -141,9 +141,9 @@ class TestSwitchFlux(unittest.TestCase):
turn_on_calls = mock_service( turn_on_calls = mock_service(
self.hass, light.DOMAIN, SERVICE_TURN_ON) self.hass, light.DOMAIN, SERVICE_TURN_ON)
switch.turn_on(self.hass, 'switch.flux') switch.turn_on(self.hass, 'switch.flux')
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_time_changed(self.hass, test_time) fire_time_changed(self.hass, test_time)
self.hass.pool.block_till_done() self.hass.block_till_done()
call = turn_on_calls[-1] call = turn_on_calls[-1]
self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 119) self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 119)
self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.591, 0.395]) self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.591, 0.395])
@ -185,9 +185,9 @@ class TestSwitchFlux(unittest.TestCase):
turn_on_calls = mock_service( turn_on_calls = mock_service(
self.hass, light.DOMAIN, SERVICE_TURN_ON) self.hass, light.DOMAIN, SERVICE_TURN_ON)
switch.turn_on(self.hass, 'switch.flux') switch.turn_on(self.hass, 'switch.flux')
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_time_changed(self.hass, test_time) fire_time_changed(self.hass, test_time)
self.hass.pool.block_till_done() self.hass.block_till_done()
call = turn_on_calls[-1] call = turn_on_calls[-1]
self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 180) self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 180)
self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.431, 0.38]) self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.431, 0.38])
@ -229,9 +229,9 @@ class TestSwitchFlux(unittest.TestCase):
turn_on_calls = mock_service( turn_on_calls = mock_service(
self.hass, light.DOMAIN, SERVICE_TURN_ON) self.hass, light.DOMAIN, SERVICE_TURN_ON)
switch.turn_on(self.hass, 'switch.flux') switch.turn_on(self.hass, 'switch.flux')
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_time_changed(self.hass, test_time) fire_time_changed(self.hass, test_time)
self.hass.pool.block_till_done() self.hass.block_till_done()
call = turn_on_calls[-1] call = turn_on_calls[-1]
self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 153) self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 153)
self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.496, 0.397]) self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.496, 0.397])
@ -273,9 +273,9 @@ class TestSwitchFlux(unittest.TestCase):
turn_on_calls = mock_service( turn_on_calls = mock_service(
self.hass, light.DOMAIN, SERVICE_TURN_ON) self.hass, light.DOMAIN, SERVICE_TURN_ON)
switch.turn_on(self.hass, 'switch.flux') switch.turn_on(self.hass, 'switch.flux')
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_time_changed(self.hass, test_time) fire_time_changed(self.hass, test_time)
self.hass.pool.block_till_done() self.hass.block_till_done()
call = turn_on_calls[-1] call = turn_on_calls[-1]
self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 119) self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 119)
self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.591, 0.395]) self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.591, 0.395])
@ -319,9 +319,9 @@ class TestSwitchFlux(unittest.TestCase):
turn_on_calls = mock_service( turn_on_calls = mock_service(
self.hass, light.DOMAIN, SERVICE_TURN_ON) self.hass, light.DOMAIN, SERVICE_TURN_ON)
switch.turn_on(self.hass, 'switch.flux') switch.turn_on(self.hass, 'switch.flux')
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_time_changed(self.hass, test_time) fire_time_changed(self.hass, test_time)
self.hass.pool.block_till_done() self.hass.block_till_done()
call = turn_on_calls[-1] call = turn_on_calls[-1]
self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 154) self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 154)
self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.494, 0.397]) self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.494, 0.397])
@ -365,9 +365,9 @@ class TestSwitchFlux(unittest.TestCase):
turn_on_calls = mock_service( turn_on_calls = mock_service(
self.hass, light.DOMAIN, SERVICE_TURN_ON) self.hass, light.DOMAIN, SERVICE_TURN_ON)
switch.turn_on(self.hass, 'switch.flux') switch.turn_on(self.hass, 'switch.flux')
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_time_changed(self.hass, test_time) fire_time_changed(self.hass, test_time)
self.hass.pool.block_till_done() self.hass.block_till_done()
call = turn_on_calls[-1] call = turn_on_calls[-1]
self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 167) self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 167)
self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.461, 0.389]) self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.461, 0.389])
@ -410,9 +410,9 @@ class TestSwitchFlux(unittest.TestCase):
turn_on_calls = mock_service( turn_on_calls = mock_service(
self.hass, light.DOMAIN, SERVICE_TURN_ON) self.hass, light.DOMAIN, SERVICE_TURN_ON)
switch.turn_on(self.hass, 'switch.flux') switch.turn_on(self.hass, 'switch.flux')
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_time_changed(self.hass, test_time) fire_time_changed(self.hass, test_time)
self.hass.pool.block_till_done() self.hass.block_till_done()
call = turn_on_calls[-1] call = turn_on_calls[-1]
self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 255) self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 255)
self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.496, 0.397]) self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.496, 0.397])
@ -426,9 +426,9 @@ class TestSwitchFlux(unittest.TestCase):
dev1, dev2, dev3 = platform.DEVICES dev1, dev2, dev3 = platform.DEVICES
light.turn_on(self.hass, entity_id=dev2.entity_id) light.turn_on(self.hass, entity_id=dev2.entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
light.turn_on(self.hass, entity_id=dev3.entity_id) light.turn_on(self.hass, entity_id=dev3.entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(dev1.entity_id) state = self.hass.states.get(dev1.entity_id)
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)
@ -468,9 +468,9 @@ class TestSwitchFlux(unittest.TestCase):
turn_on_calls = mock_service( turn_on_calls = mock_service(
self.hass, light.DOMAIN, SERVICE_TURN_ON) self.hass, light.DOMAIN, SERVICE_TURN_ON)
switch.turn_on(self.hass, 'switch.flux') switch.turn_on(self.hass, 'switch.flux')
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_time_changed(self.hass, test_time) fire_time_changed(self.hass, test_time)
self.hass.pool.block_till_done() self.hass.block_till_done()
call = turn_on_calls[-1] call = turn_on_calls[-1]
self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 171) self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 171)
self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.452, 0.386]) self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.452, 0.386])
@ -517,9 +517,9 @@ class TestSwitchFlux(unittest.TestCase):
turn_on_calls = mock_service( turn_on_calls = mock_service(
self.hass, light.DOMAIN, SERVICE_TURN_ON) self.hass, light.DOMAIN, SERVICE_TURN_ON)
switch.turn_on(self.hass, 'switch.flux') switch.turn_on(self.hass, 'switch.flux')
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_time_changed(self.hass, test_time) fire_time_changed(self.hass, test_time)
self.hass.pool.block_till_done() self.hass.block_till_done()
call = turn_on_calls[-1] call = turn_on_calls[-1]
self.assertEqual(call.data[light.ATTR_COLOR_TEMP], 269) self.assertEqual(call.data[light.ATTR_COLOR_TEMP], 269)
@ -559,8 +559,8 @@ class TestSwitchFlux(unittest.TestCase):
turn_on_calls = mock_service( turn_on_calls = mock_service(
self.hass, light.DOMAIN, SERVICE_TURN_ON) self.hass, light.DOMAIN, SERVICE_TURN_ON)
switch.turn_on(self.hass, 'switch.flux') switch.turn_on(self.hass, 'switch.flux')
self.hass.pool.block_till_done() self.hass.block_till_done()
fire_time_changed(self.hass, test_time) fire_time_changed(self.hass, test_time)
self.hass.pool.block_till_done() self.hass.block_till_done()
call = turn_on_calls[-1] call = turn_on_calls[-1]
self.assertEqual(call.data[light.ATTR_COLOR_TEMP], 3708) self.assertEqual(call.data[light.ATTR_COLOR_TEMP], 3708)

View file

@ -42,7 +42,7 @@ class TestSwitch(unittest.TestCase):
switch.turn_off(self.hass, self.switch_1.entity_id) switch.turn_off(self.hass, self.switch_1.entity_id)
switch.turn_on(self.hass, self.switch_2.entity_id) switch.turn_on(self.hass, self.switch_2.entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(switch.is_on(self.hass)) self.assertTrue(switch.is_on(self.hass))
self.assertFalse(switch.is_on(self.hass, self.switch_1.entity_id)) self.assertFalse(switch.is_on(self.hass, self.switch_1.entity_id))
@ -51,7 +51,7 @@ class TestSwitch(unittest.TestCase):
# Turn all off # Turn all off
switch.turn_off(self.hass) switch.turn_off(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertFalse(switch.is_on(self.hass)) self.assertFalse(switch.is_on(self.hass))
self.assertEqual( self.assertEqual(
@ -64,7 +64,7 @@ class TestSwitch(unittest.TestCase):
# Turn all on # Turn all on
switch.turn_on(self.hass) switch.turn_on(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(switch.is_on(self.hass)) self.assertTrue(switch.is_on(self.hass))
self.assertEqual( self.assertEqual(

View file

@ -39,13 +39,13 @@ class TestSensorMQTT(unittest.TestCase):
self.assertIsNone(state.attributes.get(ATTR_ASSUMED_STATE)) self.assertIsNone(state.attributes.get(ATTR_ASSUMED_STATE))
fire_mqtt_message(self.hass, 'state-topic', '1') fire_mqtt_message(self.hass, 'state-topic', '1')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('switch.test') state = self.hass.states.get('switch.test')
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)
fire_mqtt_message(self.hass, 'state-topic', '0') fire_mqtt_message(self.hass, 'state-topic', '0')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('switch.test') state = self.hass.states.get('switch.test')
self.assertEqual(STATE_OFF, state.state) self.assertEqual(STATE_OFF, state.state)
@ -69,7 +69,7 @@ class TestSensorMQTT(unittest.TestCase):
self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE)) self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE))
switch.turn_on(self.hass, 'switch.test') switch.turn_on(self.hass, 'switch.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('command-topic', 'beer on', 2, False), self.assertEqual(('command-topic', 'beer on', 2, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -77,7 +77,7 @@ class TestSensorMQTT(unittest.TestCase):
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)
switch.turn_off(self.hass, 'switch.test') switch.turn_off(self.hass, 'switch.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(('command-topic', 'beer off', 2, False), self.assertEqual(('command-topic', 'beer off', 2, False),
self.mock_publish.mock_calls[-1][1]) self.mock_publish.mock_calls[-1][1])
@ -103,13 +103,13 @@ class TestSensorMQTT(unittest.TestCase):
self.assertEqual(STATE_OFF, state.state) self.assertEqual(STATE_OFF, state.state)
fire_mqtt_message(self.hass, 'state-topic', '{"val":"beer on"}') fire_mqtt_message(self.hass, 'state-topic', '{"val":"beer on"}')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('switch.test') state = self.hass.states.get('switch.test')
self.assertEqual(STATE_ON, state.state) self.assertEqual(STATE_ON, state.state)
fire_mqtt_message(self.hass, 'state-topic', '{"val":"beer off"}') fire_mqtt_message(self.hass, 'state-topic', '{"val":"beer off"}')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('switch.test') state = self.hass.states.get('switch.test')
self.assertEqual(STATE_OFF, state.state) self.assertEqual(STATE_OFF, state.state)

View file

@ -50,13 +50,13 @@ class TestTemplateSwitch:
}) })
state = self.hass.states.set('switch.test_state', STATE_ON) state = self.hass.states.set('switch.test_state', STATE_ON)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('switch.test_template_switch') state = self.hass.states.get('switch.test_template_switch')
assert state.state == STATE_ON assert state.state == STATE_ON
state = self.hass.states.set('switch.test_state', STATE_OFF) state = self.hass.states.set('switch.test_state', STATE_OFF)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('switch.test_template_switch') state = self.hass.states.get('switch.test_template_switch')
assert state.state == STATE_OFF assert state.state == STATE_OFF
@ -268,13 +268,13 @@ class TestTemplateSwitch:
} }
}) })
self.hass.states.set('switch.test_state', STATE_OFF) self.hass.states.set('switch.test_state', STATE_OFF)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('switch.test_template_switch') state = self.hass.states.get('switch.test_template_switch')
assert state.state == STATE_OFF assert state.state == STATE_OFF
core.switch.turn_on(self.hass, 'switch.test_template_switch') core.switch.turn_on(self.hass, 'switch.test_template_switch')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 1 assert len(self.calls) == 1
@ -300,12 +300,12 @@ class TestTemplateSwitch:
} }
}) })
self.hass.states.set('switch.test_state', STATE_ON) self.hass.states.set('switch.test_state', STATE_ON)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('switch.test_template_switch') state = self.hass.states.get('switch.test_template_switch')
assert state.state == STATE_ON assert state.state == STATE_ON
core.switch.turn_off(self.hass, 'switch.test_template_switch') core.switch.turn_off(self.hass, 'switch.test_template_switch')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.calls) == 1 assert len(self.calls) == 1

View file

@ -104,7 +104,7 @@ class TestAlexa(unittest.TestCase):
def tearDown(self): def tearDown(self):
"""Stop everything that was started.""" """Stop everything that was started."""
hass.pool.block_till_done() hass.block_till_done()
def test_launch_request(self): def test_launch_request(self):
"""Test the launch of a request.""" """Test the launch of a request."""

View file

@ -61,7 +61,7 @@ class TestAPI(unittest.TestCase):
def tearDown(self): def tearDown(self):
"""Stop everything that was started.""" """Stop everything that was started."""
hass.pool.block_till_done() hass.block_till_done()
def test_api_list_state_entities(self): def test_api_list_state_entities(self):
"""Test if the debug interface allows us to list state entities.""" """Test if the debug interface allows us to list state entities."""
@ -169,7 +169,7 @@ class TestAPI(unittest.TestCase):
_url(const.URL_API_EVENTS_EVENT.format("test.event_no_data")), _url(const.URL_API_EVENTS_EVENT.format("test.event_no_data")),
headers=HA_HEADERS) headers=HA_HEADERS)
hass.pool.block_till_done() hass.block_till_done()
self.assertEqual(1, len(test_value)) self.assertEqual(1, len(test_value))
@ -193,7 +193,7 @@ class TestAPI(unittest.TestCase):
data=json.dumps({"test": 1}), data=json.dumps({"test": 1}),
headers=HA_HEADERS) headers=HA_HEADERS)
hass.pool.block_till_done() hass.block_till_done()
self.assertEqual(1, len(test_value)) self.assertEqual(1, len(test_value))
@ -213,7 +213,7 @@ class TestAPI(unittest.TestCase):
data=json.dumps('not an object'), data=json.dumps('not an object'),
headers=HA_HEADERS) headers=HA_HEADERS)
hass.pool.block_till_done() hass.block_till_done()
self.assertEqual(400, req.status_code) self.assertEqual(400, req.status_code)
self.assertEqual(0, len(test_value)) self.assertEqual(0, len(test_value))
@ -224,7 +224,7 @@ class TestAPI(unittest.TestCase):
data=json.dumps([1, 2, 3]), data=json.dumps([1, 2, 3]),
headers=HA_HEADERS) headers=HA_HEADERS)
hass.pool.block_till_done() hass.block_till_done()
self.assertEqual(400, req.status_code) self.assertEqual(400, req.status_code)
self.assertEqual(0, len(test_value)) self.assertEqual(0, len(test_value))
@ -294,7 +294,7 @@ class TestAPI(unittest.TestCase):
"test_domain", "test_service")), "test_domain", "test_service")),
headers=HA_HEADERS) headers=HA_HEADERS)
hass.pool.block_till_done() hass.block_till_done()
self.assertEqual(1, len(test_value)) self.assertEqual(1, len(test_value))
@ -318,7 +318,7 @@ class TestAPI(unittest.TestCase):
data=json.dumps({"test": 1}), data=json.dumps({"test": 1}),
headers=HA_HEADERS) headers=HA_HEADERS)
hass.pool.block_till_done() hass.block_till_done()
self.assertEqual(1, len(test_value)) self.assertEqual(1, len(test_value))

View file

@ -70,7 +70,7 @@ class TestConfigurator(unittest.TestCase):
configurator.DOMAIN, configurator.SERVICE_CONFIGURE, configurator.DOMAIN, configurator.SERVICE_CONFIGURE,
{configurator.ATTR_CONFIGURE_ID: request_id}) {configurator.ATTR_CONFIGURE_ID: request_id})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(calls), "Callback not called") self.assertEqual(1, len(calls), "Callback not called")
def test_state_change_on_notify_errors(self): def test_state_change_on_notify_errors(self):
@ -95,7 +95,7 @@ class TestConfigurator(unittest.TestCase):
self.assertEqual(1, len(self.hass.states.all())) self.assertEqual(1, len(self.hass.states.all()))
self.hass.bus.fire(EVENT_TIME_CHANGED) self.hass.bus.fire(EVENT_TIME_CHANGED)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.hass.states.all())) self.assertEqual(0, len(self.hass.states.all()))
def test_request_done_fail_silently_on_bad_request_id(self): def test_request_done_fail_silently_on_bad_request_id(self):

View file

@ -76,10 +76,10 @@ class TestDeviceSunLightTrigger(unittest.TestCase):
ensure_sun_risen(self.hass) ensure_sun_risen(self.hass)
light.turn_off(self.hass) light.turn_off(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
ensure_sun_set(self.hass) ensure_sun_set(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(light.is_on(self.hass)) self.assertTrue(light.is_on(self.hass))
@ -88,7 +88,7 @@ class TestDeviceSunLightTrigger(unittest.TestCase):
"""Test lights turn off when everyone leaves the house.""" """Test lights turn off when everyone leaves the house."""
light.turn_on(self.hass) light.turn_on(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(device_sun_light_trigger.setup( self.assertTrue(device_sun_light_trigger.setup(
self.hass, {device_sun_light_trigger.DOMAIN: {}})) self.hass, {device_sun_light_trigger.DOMAIN: {}}))
@ -96,7 +96,7 @@ class TestDeviceSunLightTrigger(unittest.TestCase):
self.hass.states.set(device_tracker.ENTITY_ID_ALL_DEVICES, self.hass.states.set(device_tracker.ENTITY_ID_ALL_DEVICES,
STATE_NOT_HOME) STATE_NOT_HOME)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertFalse(light.is_on(self.hass)) self.assertFalse(light.is_on(self.hass))
@ -106,7 +106,7 @@ class TestDeviceSunLightTrigger(unittest.TestCase):
light.turn_off(self.hass) light.turn_off(self.hass)
ensure_sun_set(self.hass) ensure_sun_set(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(device_sun_light_trigger.setup( self.assertTrue(device_sun_light_trigger.setup(
self.hass, {device_sun_light_trigger.DOMAIN: {}})) self.hass, {device_sun_light_trigger.DOMAIN: {}}))
@ -114,5 +114,5 @@ class TestDeviceSunLightTrigger(unittest.TestCase):
self.hass.states.set( self.hass.states.set(
device_tracker.ENTITY_ID_FORMAT.format('device_2'), STATE_HOME) device_tracker.ENTITY_ID_FORMAT.format('device_2'), STATE_HOME)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(light.is_on(self.hass)) self.assertTrue(light.is_on(self.hass))

View file

@ -56,7 +56,7 @@ class TestFrontend(unittest.TestCase):
def tearDown(self): def tearDown(self):
"""Stop everything that was started.""" """Stop everything that was started."""
hass.pool.block_till_done() hass.block_till_done()
def test_frontend_and_static(self): def test_frontend_and_static(self):
"""Test if we can get the frontend.""" """Test if we can get the frontend."""

View file

@ -85,7 +85,7 @@ class TestComponentsGroup(unittest.TestCase):
test_group = group.Group( test_group = group.Group(
self.hass, 'init_group', ['light.Bowl', 'light.Ceiling'], False) self.hass, 'init_group', ['light.Bowl', 'light.Ceiling'], False)
self.hass.pool.block_till_done() self.hass.block_till_done()
group_state = self.hass.states.get(test_group.entity_id) group_state = self.hass.states.get(test_group.entity_id)
self.assertEqual(STATE_OFF, group_state.state) self.assertEqual(STATE_OFF, group_state.state)
@ -99,7 +99,7 @@ class TestComponentsGroup(unittest.TestCase):
# Turn one on # Turn one on
self.hass.states.set('light.Ceiling', STATE_ON) self.hass.states.set('light.Ceiling', STATE_ON)
self.hass.pool.block_till_done() self.hass.block_till_done()
group_state = self.hass.states.get(test_group.entity_id) group_state = self.hass.states.get(test_group.entity_id)
self.assertEqual(STATE_ON, group_state.state) self.assertEqual(STATE_ON, group_state.state)
@ -113,7 +113,7 @@ class TestComponentsGroup(unittest.TestCase):
self.assertTrue(group.is_on(self.hass, test_group.entity_id)) self.assertTrue(group.is_on(self.hass, test_group.entity_id))
self.hass.states.set('light.Bowl', STATE_OFF) self.hass.states.set('light.Bowl', STATE_OFF)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertFalse(group.is_on(self.hass, test_group.entity_id)) self.assertFalse(group.is_on(self.hass, test_group.entity_id))
# Try on non existing state # Try on non existing state
@ -193,7 +193,7 @@ class TestComponentsGroup(unittest.TestCase):
self.hass.states.set('light.not_there_1', STATE_ON) self.hass.states.set('light.not_there_1', STATE_ON)
self.hass.pool.block_till_done() self.hass.block_till_done()
group_state = self.hass.states.get(test_group.entity_id) group_state = self.hass.states.get(test_group.entity_id)
self.assertEqual(STATE_ON, group_state.state) self.assertEqual(STATE_ON, group_state.state)
@ -209,7 +209,7 @@ class TestComponentsGroup(unittest.TestCase):
self.hass.states.set('light.not_there_1', STATE_OFF) self.hass.states.set('light.not_there_1', STATE_OFF)
self.hass.pool.block_till_done() self.hass.block_till_done()
group_state = self.hass.states.get(test_group.entity_id) group_state = self.hass.states.get(test_group.entity_id)
self.assertEqual(STATE_OFF, group_state.state) self.assertEqual(STATE_OFF, group_state.state)
@ -288,13 +288,13 @@ class TestComponentsGroup(unittest.TestCase):
self.hass.states.set('light.Bowl', STATE_ON, { self.hass.states.set('light.Bowl', STATE_ON, {
ATTR_ASSUMED_STATE: True ATTR_ASSUMED_STATE: True
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(test_group.entity_id) state = self.hass.states.get(test_group.entity_id)
self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE)) self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE))
self.hass.states.set('light.Bowl', STATE_ON) self.hass.states.set('light.Bowl', STATE_ON)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(test_group.entity_id) state = self.hass.states.get(test_group.entity_id)
self.assertIsNone(state.attributes.get(ATTR_ASSUMED_STATE)) self.assertIsNone(state.attributes.get(ATTR_ASSUMED_STATE))
@ -303,12 +303,12 @@ class TestComponentsGroup(unittest.TestCase):
"""Test group state when device tracker in group changes zone.""" """Test group state when device tracker in group changes zone."""
self.hass.states.set('device_tracker.Adam', STATE_HOME) self.hass.states.set('device_tracker.Adam', STATE_HOME)
self.hass.states.set('device_tracker.Eve', STATE_NOT_HOME) self.hass.states.set('device_tracker.Eve', STATE_NOT_HOME)
self.hass.pool.block_till_done() self.hass.block_till_done()
group.Group( group.Group(
self.hass, 'peeps', self.hass, 'peeps',
['device_tracker.Adam', 'device_tracker.Eve']) ['device_tracker.Adam', 'device_tracker.Eve'])
self.hass.states.set('device_tracker.Adam', 'cool_state_not_home') self.hass.states.set('device_tracker.Adam', 'cool_state_not_home')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(STATE_NOT_HOME, self.assertEqual(STATE_NOT_HOME,
self.hass.states.get( self.hass.states.get(
group.ENTITY_ID_FORMAT.format('peeps')).state) group.ENTITY_ID_FORMAT.format('peeps')).state)
@ -338,7 +338,7 @@ class TestComponentsGroup(unittest.TestCase):
'view': True, 'view': True,
}}}): }}}):
group.reload(self.hass) group.reload(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert self.hass.states.entity_ids() == ['group.hello'] assert self.hass.states.entity_ids() == ['group.hello']
assert self.hass.bus.listeners['state_changed'] == 1 assert self.hass.bus.listeners['state_changed'] == 1

View file

@ -17,7 +17,7 @@ class TestComponentHistory(unittest.TestCase):
def setUp(self): # pylint: disable=invalid-name def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started.""" """Setup things to be run when tests are started."""
self.hass = get_test_home_assistant(1) self.hass = get_test_home_assistant()
def tearDown(self): # pylint: disable=invalid-name def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started.""" """Stop everything that was started."""
@ -36,7 +36,7 @@ class TestComponentHistory(unittest.TestCase):
def wait_recording_done(self): def wait_recording_done(self):
"""Block till recording is done.""" """Block till recording is done."""
self.hass.pool.block_till_done() self.hass.block_till_done()
recorder._INSTANCE.block_till_done() recorder._INSTANCE.block_till_done()
def test_setup(self): def test_setup(self):

View file

@ -42,28 +42,28 @@ class TestComponentsCore(unittest.TestCase):
"""Test turn_on method without entities.""" """Test turn_on method without entities."""
calls = mock_service(self.hass, 'light', SERVICE_TURN_ON) calls = mock_service(self.hass, 'light', SERVICE_TURN_ON)
comps.turn_on(self.hass) comps.turn_on(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(calls)) self.assertEqual(0, len(calls))
def test_turn_on(self): def test_turn_on(self):
"""Test turn_on method.""" """Test turn_on method."""
calls = mock_service(self.hass, 'light', SERVICE_TURN_ON) calls = mock_service(self.hass, 'light', SERVICE_TURN_ON)
comps.turn_on(self.hass, 'light.Ceiling') comps.turn_on(self.hass, 'light.Ceiling')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(calls)) self.assertEqual(1, len(calls))
def test_turn_off(self): def test_turn_off(self):
"""Test turn_off method.""" """Test turn_off method."""
calls = mock_service(self.hass, 'light', SERVICE_TURN_OFF) calls = mock_service(self.hass, 'light', SERVICE_TURN_OFF)
comps.turn_off(self.hass, 'light.Bowl') comps.turn_off(self.hass, 'light.Bowl')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(calls)) self.assertEqual(1, len(calls))
def test_toggle(self): def test_toggle(self):
"""Test toggle method.""" """Test toggle method."""
calls = mock_service(self.hass, 'light', SERVICE_TOGGLE) calls = mock_service(self.hass, 'light', SERVICE_TOGGLE)
comps.toggle(self.hass, 'light.Bowl') comps.toggle(self.hass, 'light.Bowl')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(calls)) self.assertEqual(1, len(calls))
@patch('homeassistant.core.ServiceRegistry.call') @patch('homeassistant.core.ServiceRegistry.call')
@ -118,7 +118,7 @@ class TestComponentsCore(unittest.TestCase):
})) }))
comps.reload_core_config(self.hass) comps.reload_core_config(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert 10 == self.hass.config.latitude assert 10 == self.hass.config.latitude
assert 20 == self.hass.config.longitude assert 20 == self.hass.config.longitude
@ -142,7 +142,7 @@ class TestComponentsCore(unittest.TestCase):
fp.write(yaml.dump(['invalid', 'config'])) fp.write(yaml.dump(['invalid', 'config']))
comps.reload_core_config(self.hass) comps.reload_core_config(self.hass)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert mock_error.called assert mock_error.called
assert mock_process.called is False assert mock_process.called is False

View file

@ -51,14 +51,14 @@ class TestInputBoolean(unittest.TestCase):
input_boolean.turn_on(self.hass, entity_id) input_boolean.turn_on(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue( self.assertTrue(
input_boolean.is_on(self.hass, entity_id)) input_boolean.is_on(self.hass, entity_id))
input_boolean.turn_off(self.hass, entity_id) input_boolean.turn_off(self.hass, entity_id)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertFalse( self.assertFalse(
input_boolean.is_on(self.hass, entity_id)) input_boolean.is_on(self.hass, entity_id))

View file

@ -69,13 +69,13 @@ class TestInputSelect(unittest.TestCase):
self.assertEqual('some option', state.state) self.assertEqual('some option', state.state)
input_select.select_option(self.hass, entity_id, 'another option') input_select.select_option(self.hass, entity_id, 'another option')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(entity_id) state = self.hass.states.get(entity_id)
self.assertEqual('another option', state.state) self.assertEqual('another option', state.state)
input_select.select_option(self.hass, entity_id, 'non existing option') input_select.select_option(self.hass, entity_id, 'non existing option')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(entity_id) state = self.hass.states.get(entity_id)
self.assertEqual('another option', state.state) self.assertEqual('another option', state.state)

View file

@ -52,19 +52,19 @@ class TestInputSlider(unittest.TestCase):
self.assertEqual(50, float(state.state)) self.assertEqual(50, float(state.state))
input_slider.select_value(self.hass, entity_id, '30.4') input_slider.select_value(self.hass, entity_id, '30.4')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(entity_id) state = self.hass.states.get(entity_id)
self.assertEqual(30.4, float(state.state)) self.assertEqual(30.4, float(state.state))
input_slider.select_value(self.hass, entity_id, '70') input_slider.select_value(self.hass, entity_id, '70')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(entity_id) state = self.hass.states.get(entity_id)
self.assertEqual(70, float(state.state)) self.assertEqual(70, float(state.state))
input_slider.select_value(self.hass, entity_id, '110') input_slider.select_value(self.hass, entity_id, '110')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(entity_id) state = self.hass.states.get(entity_id)
self.assertEqual(70, float(state.state)) self.assertEqual(70, float(state.state))

View file

@ -39,7 +39,7 @@ class TestComponentLogbook(unittest.TestCase):
logbook.ATTR_DOMAIN: 'switch', logbook.ATTR_DOMAIN: 'switch',
logbook.ATTR_ENTITY_ID: 'switch.test_switch' logbook.ATTR_ENTITY_ID: 'switch.test_switch'
}, True) }, True)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(calls)) self.assertEqual(1, len(calls))
last_call = calls[-1] last_call = calls[-1]
@ -60,7 +60,7 @@ class TestComponentLogbook(unittest.TestCase):
self.hass.bus.listen(logbook.EVENT_LOGBOOK_ENTRY, event_listener) self.hass.bus.listen(logbook.EVENT_LOGBOOK_ENTRY, event_listener)
self.hass.services.call(logbook.DOMAIN, 'log', {}, True) self.hass.services.call(logbook.DOMAIN, 'log', {}, True)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(calls)) self.assertEqual(0, len(calls))

View file

@ -50,7 +50,7 @@ class TestMqttEventStream(unittest.TestCase):
self.assertEqual(self.hass.bus.listeners.get('*'), None) self.assertEqual(self.hass.bus.listeners.get('*'), None)
self.assertTrue(self.add_eventstream(pub_topic='bar')) self.assertTrue(self.add_eventstream(pub_topic='bar'))
self.hass.pool.block_till_done() self.hass.block_till_done()
# Verify that the event handler has been added as a listener # Verify that the event handler has been added as a listener
self.assertEqual(self.hass.bus.listeners.get('*'), 1) self.assertEqual(self.hass.bus.listeners.get('*'), 1)
@ -60,7 +60,7 @@ class TestMqttEventStream(unittest.TestCase):
""""Test the subscription.""" """"Test the subscription."""
sub_topic = 'foo' sub_topic = 'foo'
self.assertTrue(self.add_eventstream(sub_topic=sub_topic)) self.assertTrue(self.add_eventstream(sub_topic=sub_topic))
self.hass.pool.block_till_done() self.hass.block_till_done()
# Verify that the this entity was subscribed to the topic # Verify that the this entity was subscribed to the topic
mock_sub.assert_called_with(self.hass, sub_topic, ANY) mock_sub.assert_called_with(self.hass, sub_topic, ANY)
@ -76,7 +76,7 @@ class TestMqttEventStream(unittest.TestCase):
# Add the eventstream component for publishing events # Add the eventstream component for publishing events
self.assertTrue(self.add_eventstream(pub_topic=pub_topic)) self.assertTrue(self.add_eventstream(pub_topic=pub_topic))
self.hass.pool.block_till_done() self.hass.block_till_done()
# Reset the mock because it will have already gotten calls for the # Reset the mock because it will have already gotten calls for the
# mqtt_eventstream state change on initialization, etc. # mqtt_eventstream state change on initialization, etc.
@ -84,7 +84,7 @@ class TestMqttEventStream(unittest.TestCase):
# Set a state of an entity # Set a state of an entity
mock_state_change_event(self.hass, State(e_id, 'on')) mock_state_change_event(self.hass, State(e_id, 'on'))
self.hass.pool.block_till_done() self.hass.block_till_done()
# The order of the JSON is indeterminate, # The order of the JSON is indeterminate,
# so first just check that publish was called # so first just check that publish was called
@ -112,7 +112,7 @@ class TestMqttEventStream(unittest.TestCase):
def test_time_event_does_not_send_message(self, mock_pub): def test_time_event_does_not_send_message(self, mock_pub):
""""Test the sending of a new message if time event.""" """"Test the sending of a new message if time event."""
self.assertTrue(self.add_eventstream(pub_topic='bar')) self.assertTrue(self.add_eventstream(pub_topic='bar'))
self.hass.pool.block_till_done() self.hass.block_till_done()
# Reset the mock because it will have already gotten calls for the # Reset the mock because it will have already gotten calls for the
# mqtt_eventstream state change on initialization, etc. # mqtt_eventstream state change on initialization, etc.
@ -125,17 +125,17 @@ class TestMqttEventStream(unittest.TestCase):
""""Test the receiving of the remotely fired event.""" """"Test the receiving of the remotely fired event."""
sub_topic = 'foo' sub_topic = 'foo'
self.assertTrue(self.add_eventstream(sub_topic=sub_topic)) self.assertTrue(self.add_eventstream(sub_topic=sub_topic))
self.hass.pool.block_till_done() self.hass.block_till_done()
calls = [] calls = []
self.hass.bus.listen_once('test_event', lambda _: calls.append(1)) self.hass.bus.listen_once('test_event', lambda _: calls.append(1))
self.hass.pool.block_till_done() self.hass.block_till_done()
payload = json.dumps( payload = json.dumps(
{'event_type': 'test_event', 'event_data': {}}, {'event_type': 'test_event', 'event_data': {}},
cls=JSONEncoder cls=JSONEncoder
) )
fire_mqtt_message(self.hass, sub_topic, payload) fire_mqtt_message(self.hass, sub_topic, payload)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(calls)) self.assertEqual(1, len(calls))

View file

@ -22,7 +22,7 @@ class TestPersistentNotification:
pn.create(self.hass, 'Hello World {{ 1 + 1 }}', pn.create(self.hass, 'Hello World {{ 1 + 1 }}',
title='{{ 1 + 1 }} beers') title='{{ 1 + 1 }} beers')
self.hass.pool.block_till_done() self.hass.block_till_done()
entity_ids = self.hass.states.entity_ids(pn.DOMAIN) entity_ids = self.hass.states.entity_ids(pn.DOMAIN)
assert len(entity_ids) == 1 assert len(entity_ids) == 1
@ -36,14 +36,14 @@ class TestPersistentNotification:
assert len(self.hass.states.entity_ids(pn.DOMAIN)) == 0 assert len(self.hass.states.entity_ids(pn.DOMAIN)) == 0
pn.create(self.hass, 'test', notification_id='Beer 2') pn.create(self.hass, 'test', notification_id='Beer 2')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(self.hass.states.entity_ids()) == 1 assert len(self.hass.states.entity_ids()) == 1
state = self.hass.states.get('persistent_notification.beer_2') state = self.hass.states.get('persistent_notification.beer_2')
assert state.state == 'test' assert state.state == 'test'
pn.create(self.hass, 'test 2', notification_id='Beer 2') pn.create(self.hass, 'test 2', notification_id='Beer 2')
self.hass.pool.block_till_done() self.hass.block_till_done()
# We should have overwritten old one # We should have overwritten old one
assert len(self.hass.states.entity_ids()) == 1 assert len(self.hass.states.entity_ids()) == 1
@ -55,7 +55,7 @@ class TestPersistentNotification:
assert len(self.hass.states.entity_ids(pn.DOMAIN)) == 0 assert len(self.hass.states.entity_ids(pn.DOMAIN)) == 0
pn.create(self.hass, '{{ message + 1 }}', '{{ title + 1 }}') pn.create(self.hass, '{{ message + 1 }}', '{{ title + 1 }}')
self.hass.pool.block_till_done() self.hass.block_till_done()
entity_ids = self.hass.states.entity_ids(pn.DOMAIN) entity_ids = self.hass.states.entity_ids(pn.DOMAIN)
assert len(entity_ids) == 1 assert len(entity_ids) == 1

View file

@ -62,7 +62,7 @@ class TestProximity:
assert state.attributes.get('dir_of_travel') == 'not set' assert state.attributes.get('dir_of_travel') == 'not set'
self.hass.states.set('proximity.' + prox, '0') self.hass.states.set('proximity.' + prox, '0')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.' + prox) state = self.hass.states.get('proximity.' + prox)
assert state.state == '0' assert state.state == '0'
@ -107,7 +107,7 @@ class TestProximity:
assert state.attributes.get('dir_of_travel') == 'not set' assert state.attributes.get('dir_of_travel') == 'not set'
self.hass.states.set('proximity.home', '0') self.hass.states.set('proximity.home', '0')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.state == '0' assert state.state == '0'
@ -188,7 +188,7 @@ class TestProximity:
'latitude': 2.1, 'latitude': 2.1,
'longitude': 1.1 'longitude': 1.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.state == '0' assert state.state == '0'
assert state.attributes.get('nearest') == 'test1' assert state.attributes.get('nearest') == 'test1'
@ -217,7 +217,7 @@ class TestProximity:
'latitude': 2.1, 'latitude': 2.1,
'longitude': 1.1 'longitude': 1.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set( self.hass.states.set(
'device_tracker.test2', 'home', 'device_tracker.test2', 'home',
{ {
@ -225,7 +225,7 @@ class TestProximity:
'latitude': 2.1, 'latitude': 2.1,
'longitude': 1.1 'longitude': 1.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.state == '0' assert state.state == '0'
assert ((state.attributes.get('nearest') == 'test1, test2') or assert ((state.attributes.get('nearest') == 'test1, test2') or
@ -254,7 +254,7 @@ class TestProximity:
'latitude': 20.1, 'latitude': 20.1,
'longitude': 10.1 'longitude': 10.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.attributes.get('nearest') == 'test1' assert state.attributes.get('nearest') == 'test1'
assert state.attributes.get('dir_of_travel') == 'unknown' assert state.attributes.get('dir_of_travel') == 'unknown'
@ -280,7 +280,7 @@ class TestProximity:
'latitude': 20.1, 'latitude': 20.1,
'longitude': 10.1 'longitude': 10.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.attributes.get('nearest') == 'test1' assert state.attributes.get('nearest') == 'test1'
assert state.attributes.get('dir_of_travel') == 'unknown' assert state.attributes.get('dir_of_travel') == 'unknown'
@ -291,7 +291,7 @@ class TestProximity:
'latitude': 40.1, 'latitude': 40.1,
'longitude': 20.1 'longitude': 20.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.attributes.get('nearest') == 'test1' assert state.attributes.get('nearest') == 'test1'
assert state.attributes.get('dir_of_travel') == 'away_from' assert state.attributes.get('dir_of_travel') == 'away_from'
@ -317,7 +317,7 @@ class TestProximity:
'latitude': 40.1, 'latitude': 40.1,
'longitude': 20.1 'longitude': 20.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.attributes.get('nearest') == 'test1' assert state.attributes.get('nearest') == 'test1'
assert state.attributes.get('dir_of_travel') == 'unknown' assert state.attributes.get('dir_of_travel') == 'unknown'
@ -328,7 +328,7 @@ class TestProximity:
'latitude': 20.1, 'latitude': 20.1,
'longitude': 10.1 'longitude': 10.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.attributes.get('nearest') == 'test1' assert state.attributes.get('nearest') == 'test1'
assert state.attributes.get('dir_of_travel') == 'towards' assert state.attributes.get('dir_of_travel') == 'towards'
@ -352,7 +352,7 @@ class TestProximity:
{ {
'friendly_name': 'test1' 'friendly_name': 'test1'
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.state == 'not set' assert state.state == 'not set'
assert state.attributes.get('nearest') == 'not set' assert state.attributes.get('nearest') == 'not set'
@ -378,7 +378,7 @@ class TestProximity:
{ {
'friendly_name': 'test1' 'friendly_name': 'test1'
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.attributes.get('nearest') == 'not set' assert state.attributes.get('nearest') == 'not set'
assert state.attributes.get('dir_of_travel') == 'not set' assert state.attributes.get('dir_of_travel') == 'not set'
@ -390,13 +390,13 @@ class TestProximity:
{ {
'friendly_name': 'test1' 'friendly_name': 'test1'
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set( self.hass.states.set(
'device_tracker.test2', 'not_home', 'device_tracker.test2', 'not_home',
{ {
'friendly_name': 'test2' 'friendly_name': 'test2'
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
assert proximity.setup(self.hass, { assert proximity.setup(self.hass, {
'proximity': { 'proximity': {
'zone': 'home', 'zone': 'home',
@ -417,7 +417,7 @@ class TestProximity:
'latitude': 20.1, 'latitude': 20.1,
'longitude': 10.1 'longitude': 10.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.attributes.get('nearest') == 'test1' assert state.attributes.get('nearest') == 'test1'
assert state.attributes.get('dir_of_travel') == 'unknown' assert state.attributes.get('dir_of_travel') == 'unknown'
@ -428,7 +428,7 @@ class TestProximity:
'latitude': 40.1, 'latitude': 40.1,
'longitude': 20.1 'longitude': 20.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.attributes.get('nearest') == 'test1' assert state.attributes.get('nearest') == 'test1'
assert state.attributes.get('dir_of_travel') == 'unknown' assert state.attributes.get('dir_of_travel') == 'unknown'
@ -440,13 +440,13 @@ class TestProximity:
{ {
'friendly_name': 'test1' 'friendly_name': 'test1'
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set( self.hass.states.set(
'device_tracker.test2', 'not_home', 'device_tracker.test2', 'not_home',
{ {
'friendly_name': 'test2' 'friendly_name': 'test2'
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
assert proximity.setup(self.hass, { assert proximity.setup(self.hass, {
'proximity': { 'proximity': {
'zone': 'home', 'zone': 'home',
@ -467,7 +467,7 @@ class TestProximity:
'latitude': 40.1, 'latitude': 40.1,
'longitude': 20.1 'longitude': 20.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.attributes.get('nearest') == 'test2' assert state.attributes.get('nearest') == 'test2'
assert state.attributes.get('dir_of_travel') == 'unknown' assert state.attributes.get('dir_of_travel') == 'unknown'
@ -478,7 +478,7 @@ class TestProximity:
'latitude': 20.1, 'latitude': 20.1,
'longitude': 10.1 'longitude': 10.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.attributes.get('nearest') == 'test1' assert state.attributes.get('nearest') == 'test1'
assert state.attributes.get('dir_of_travel') == 'unknown' assert state.attributes.get('dir_of_travel') == 'unknown'
@ -490,13 +490,13 @@ class TestProximity:
{ {
'friendly_name': 'test1' 'friendly_name': 'test1'
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set( self.hass.states.set(
'device_tracker.test2', 'work', 'device_tracker.test2', 'work',
{ {
'friendly_name': 'test2' 'friendly_name': 'test2'
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
assert proximity.setup(self.hass, { assert proximity.setup(self.hass, {
'proximity': { 'proximity': {
'zone': 'home', 'zone': 'home',
@ -517,7 +517,7 @@ class TestProximity:
'latitude': 20.1, 'latitude': 20.1,
'longitude': 10.1 'longitude': 10.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.attributes.get('nearest') == 'test1' assert state.attributes.get('nearest') == 'test1'
assert state.attributes.get('dir_of_travel') == 'unknown' assert state.attributes.get('dir_of_travel') == 'unknown'
@ -529,13 +529,13 @@ class TestProximity:
{ {
'friendly_name': 'test1' 'friendly_name': 'test1'
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set( self.hass.states.set(
'device_tracker.test2', 'not_home', 'device_tracker.test2', 'not_home',
{ {
'friendly_name': 'test2' 'friendly_name': 'test2'
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
assert proximity.setup(self.hass, { assert proximity.setup(self.hass, {
'proximity': { 'proximity': {
'zone': 'home', 'zone': 'home',
@ -556,7 +556,7 @@ class TestProximity:
'latitude': 10.1, 'latitude': 10.1,
'longitude': 5.1 'longitude': 5.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set( self.hass.states.set(
'device_tracker.test2', 'not_home', 'device_tracker.test2', 'not_home',
@ -565,7 +565,7 @@ class TestProximity:
'latitude': 20.1, 'latitude': 20.1,
'longitude': 10.1 'longitude': 10.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set( self.hass.states.set(
'device_tracker.test1', 'not_home', 'device_tracker.test1', 'not_home',
{ {
@ -573,7 +573,7 @@ class TestProximity:
'latitude': 40.1, 'latitude': 40.1,
'longitude': 20.1 'longitude': 20.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set( self.hass.states.set(
'device_tracker.test1', 'not_home', 'device_tracker.test1', 'not_home',
{ {
@ -581,13 +581,13 @@ class TestProximity:
'latitude': 35.1, 'latitude': 35.1,
'longitude': 15.1 'longitude': 15.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set( self.hass.states.set(
'device_tracker.test1', 'work', 'device_tracker.test1', 'work',
{ {
'friendly_name': 'test1' 'friendly_name': 'test1'
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.attributes.get('nearest') == 'test2' assert state.attributes.get('nearest') == 'test2'
assert state.attributes.get('dir_of_travel') == 'unknown' assert state.attributes.get('dir_of_travel') == 'unknown'
@ -614,7 +614,7 @@ class TestProximity:
'latitude': 20.1000001, 'latitude': 20.1000001,
'longitude': 10.1000001 'longitude': 10.1000001
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.attributes.get('nearest') == 'test1' assert state.attributes.get('nearest') == 'test1'
assert state.attributes.get('dir_of_travel') == 'unknown' assert state.attributes.get('dir_of_travel') == 'unknown'
@ -625,7 +625,7 @@ class TestProximity:
'latitude': 20.1000002, 'latitude': 20.1000002,
'longitude': 10.1000002 'longitude': 10.1000002
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.attributes.get('nearest') == 'test1' assert state.attributes.get('nearest') == 'test1'
assert state.attributes.get('dir_of_travel') == 'stationary' assert state.attributes.get('dir_of_travel') == 'stationary'
@ -637,13 +637,13 @@ class TestProximity:
{ {
'friendly_name': 'test1' 'friendly_name': 'test1'
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.hass.states.set( self.hass.states.set(
'device_tracker.test2', 'not_home', 'device_tracker.test2', 'not_home',
{ {
'friendly_name': 'test2' 'friendly_name': 'test2'
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
assert proximity.setup(self.hass, { assert proximity.setup(self.hass, {
'proximity': { 'proximity': {
'zone': 'home', 'zone': 'home',
@ -664,7 +664,7 @@ class TestProximity:
'latitude': 20.1, 'latitude': 20.1,
'longitude': 10.1 'longitude': 10.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.attributes.get('nearest') == 'test1' assert state.attributes.get('nearest') == 'test1'
assert state.attributes.get('dir_of_travel') == 'unknown' assert state.attributes.get('dir_of_travel') == 'unknown'
@ -676,7 +676,7 @@ class TestProximity:
'latitude': 10.1, 'latitude': 10.1,
'longitude': 5.1 'longitude': 5.1
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.attributes.get('nearest') == 'test2' assert state.attributes.get('nearest') == 'test2'
assert state.attributes.get('dir_of_travel') == 'unknown' assert state.attributes.get('dir_of_travel') == 'unknown'
@ -688,7 +688,7 @@ class TestProximity:
'latitude': 12.6, 'latitude': 12.6,
'longitude': 7.6 'longitude': 7.6
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get('proximity.home') state = self.hass.states.get('proximity.home')
assert state.attributes.get('nearest') == 'test1' assert state.attributes.get('nearest') == 'test1'
assert state.attributes.get('dir_of_travel') == 'unknown' assert state.attributes.get('dir_of_travel') == 'unknown'

View file

@ -94,6 +94,7 @@ class TestRFXTRX(unittest.TestCase):
calls.append(event) calls.append(event)
self.hass.bus.listen(rfxtrx.EVENT_BUTTON_PRESSED, record_event) self.hass.bus.listen(rfxtrx.EVENT_BUTTON_PRESSED, record_event)
self.hass.block_till_done()
entity = rfxtrx.RFX_DEVICES['213c7f216'] entity = rfxtrx.RFX_DEVICES['213c7f216']
self.assertEqual('Test', entity.name) self.assertEqual('Test', entity.name)
@ -104,7 +105,7 @@ class TestRFXTRX(unittest.TestCase):
event.data = bytearray([0x0b, 0x11, 0x00, 0x10, 0x01, 0x18, event.data = bytearray([0x0b, 0x11, 0x00, 0x10, 0x01, 0x18,
0xcd, 0xea, 0x01, 0x01, 0x0f, 0x70]) 0xcd, 0xea, 0x01, 0x01, 0x0f, 0x70])
rfxtrx.RECEIVED_EVT_SUBSCRIBERS[0](event) rfxtrx.RECEIVED_EVT_SUBSCRIBERS[0](event)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(event.values['Command'], "On") self.assertEqual(event.values['Command'], "On")
self.assertEqual('on', entity.state) self.assertEqual('on', entity.state)
@ -138,11 +139,12 @@ class TestRFXTRX(unittest.TestCase):
calls.append(event) calls.append(event)
self.hass.bus.listen("signal_received", record_event) self.hass.bus.listen("signal_received", record_event)
self.hass.block_till_done()
event = rfxtrx.get_rfx_object('0a520802060101ff0f0269') event = rfxtrx.get_rfx_object('0a520802060101ff0f0269')
event.data = bytearray(b'\nR\x08\x01\x07\x01\x00\xb8\x1b\x02y') event.data = bytearray(b'\nR\x08\x01\x07\x01\x00\xb8\x1b\x02y')
rfxtrx.RECEIVED_EVT_SUBSCRIBERS[0](event) rfxtrx.RECEIVED_EVT_SUBSCRIBERS[0](event)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(rfxtrx.RFX_DEVICES)) self.assertEqual(1, len(rfxtrx.RFX_DEVICES))
self.assertEqual(1, len(calls)) self.assertEqual(1, len(calls))
self.assertEqual(calls[0].data, self.assertEqual(calls[0].data,

View file

@ -46,7 +46,7 @@ class TestScene(unittest.TestCase):
light.turn_off(self.hass, [light_1.entity_id, light_2.entity_id]) light.turn_off(self.hass, [light_1.entity_id, light_2.entity_id])
self.hass.pool.block_till_done() self.hass.block_till_done()
entity_state = { entity_state = {
'state': 'on', 'state': 'on',
@ -63,7 +63,7 @@ class TestScene(unittest.TestCase):
})) }))
scene.activate(self.hass, 'scene.test') scene.activate(self.hass, 'scene.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(light_1.is_on) self.assertTrue(light_1.is_on)
self.assertTrue(light_2.is_on) self.assertTrue(light_2.is_on)
@ -85,7 +85,7 @@ class TestScene(unittest.TestCase):
light.turn_off(self.hass, [light_1.entity_id, light_2.entity_id]) light.turn_off(self.hass, [light_1.entity_id, light_2.entity_id])
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(scene.setup(self.hass, { self.assertTrue(scene.setup(self.hass, {
'scene': [{ 'scene': [{
@ -101,7 +101,7 @@ class TestScene(unittest.TestCase):
})) }))
scene.activate(self.hass, 'scene.test') scene.activate(self.hass, 'scene.test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(light_1.is_on) self.assertTrue(light_1.is_on)
self.assertTrue(light_2.is_on) self.assertTrue(light_2.is_on)

View file

@ -73,13 +73,13 @@ class TestScriptComponent(unittest.TestCase):
}) })
script.turn_on(self.hass, ENTITY_ID) script.turn_on(self.hass, ENTITY_ID)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(script.is_on(self.hass, ENTITY_ID)) self.assertTrue(script.is_on(self.hass, ENTITY_ID))
self.assertEqual(0, len(events)) self.assertEqual(0, len(events))
# Calling turn_on a second time should not advance the script # Calling turn_on a second time should not advance the script
script.turn_on(self.hass, ENTITY_ID) script.turn_on(self.hass, ENTITY_ID)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(events)) self.assertEqual(0, len(events))
def test_toggle_service(self): def test_toggle_service(self):
@ -108,12 +108,12 @@ class TestScriptComponent(unittest.TestCase):
}) })
script.toggle(self.hass, ENTITY_ID) script.toggle(self.hass, ENTITY_ID)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(script.is_on(self.hass, ENTITY_ID)) self.assertTrue(script.is_on(self.hass, ENTITY_ID))
self.assertEqual(0, len(events)) self.assertEqual(0, len(events))
script.toggle(self.hass, ENTITY_ID) script.toggle(self.hass, ENTITY_ID)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertFalse(script.is_on(self.hass, ENTITY_ID)) self.assertFalse(script.is_on(self.hass, ENTITY_ID))
self.assertEqual(0, len(events)) self.assertEqual(0, len(events))
@ -144,7 +144,7 @@ class TestScriptComponent(unittest.TestCase):
'greeting': 'world' 'greeting': 'world'
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(calls) == 1 assert len(calls) == 1
assert calls[-1].data['hello'] == 'world' assert calls[-1].data['hello'] == 'world'
@ -153,7 +153,7 @@ class TestScriptComponent(unittest.TestCase):
'greeting': 'universe', 'greeting': 'universe',
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(calls) == 2 assert len(calls) == 2
assert calls[-1].data['hello'] == 'universe' assert calls[-1].data['hello'] == 'universe'

View file

@ -34,6 +34,7 @@ class TestShellCommand(unittest.TestCase):
self.hass.services.call('shell_command', 'test_service', self.hass.services.call('shell_command', 'test_service',
blocking=True) blocking=True)
self.hass.block_till_done()
self.assertTrue(os.path.isfile(path)) self.assertTrue(os.path.isfile(path))

View file

@ -85,7 +85,7 @@ class TestSun(unittest.TestCase):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, self.hass.bus.fire(ha.EVENT_TIME_CHANGED,
{ha.ATTR_NOW: test_time + timedelta(seconds=5)}) {ha.ATTR_NOW: test_time + timedelta(seconds=5)})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(test_state, self.hass.states.get(sun.ENTITY_ID).state) self.assertEqual(test_state, self.hass.states.get(sun.ENTITY_ID).state)

View file

@ -55,7 +55,7 @@ class TestUpdater(unittest.TestCase):
fire_time_changed(self.hass, fire_time_changed(self.hass,
dt_util.utcnow().replace(hour=0, minute=0, second=0)) dt_util.utcnow().replace(hour=0, minute=0, second=0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(self.hass.states.is_state(updater.ENTITY_ID, self.assertTrue(self.hass.states.is_state(updater.ENTITY_ID,
NEW_VERSION)) NEW_VERSION))

View file

@ -45,13 +45,13 @@ class TestDemoThermostat(unittest.TestCase):
"""Test setting the target temperature without required attribute.""" """Test setting the target temperature without required attribute."""
self.assertEqual('21.0', self.hass.states.get(ENTITY_NEST).state) self.assertEqual('21.0', self.hass.states.get(ENTITY_NEST).state)
thermostat.set_temperature(self.hass, None, ENTITY_NEST) thermostat.set_temperature(self.hass, None, ENTITY_NEST)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual('21.0', self.hass.states.get(ENTITY_NEST).state) self.assertEqual('21.0', self.hass.states.get(ENTITY_NEST).state)
def test_set_target_temp(self): def test_set_target_temp(self):
"""Test the setting of the target temperature.""" """Test the setting of the target temperature."""
thermostat.set_temperature(self.hass, 30, ENTITY_NEST) thermostat.set_temperature(self.hass, 30, ENTITY_NEST)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual('30.0', self.hass.states.get(ENTITY_NEST).state) self.assertEqual('30.0', self.hass.states.get(ENTITY_NEST).state)
def test_set_away_mode_bad_attr(self): def test_set_away_mode_bad_attr(self):
@ -59,21 +59,21 @@ class TestDemoThermostat(unittest.TestCase):
state = self.hass.states.get(ENTITY_NEST) state = self.hass.states.get(ENTITY_NEST)
self.assertEqual('off', state.attributes.get('away_mode')) self.assertEqual('off', state.attributes.get('away_mode'))
thermostat.set_away_mode(self.hass, None, ENTITY_NEST) thermostat.set_away_mode(self.hass, None, ENTITY_NEST)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_NEST) state = self.hass.states.get(ENTITY_NEST)
self.assertEqual('off', state.attributes.get('away_mode')) self.assertEqual('off', state.attributes.get('away_mode'))
def test_set_away_mode_on(self): def test_set_away_mode_on(self):
"""Test setting the away mode on/true.""" """Test setting the away mode on/true."""
thermostat.set_away_mode(self.hass, True, ENTITY_NEST) thermostat.set_away_mode(self.hass, True, ENTITY_NEST)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_NEST) state = self.hass.states.get(ENTITY_NEST)
self.assertEqual('on', state.attributes.get('away_mode')) self.assertEqual('on', state.attributes.get('away_mode'))
def test_set_away_mode_off(self): def test_set_away_mode_off(self):
"""Test setting the away mode off/false.""" """Test setting the away mode off/false."""
thermostat.set_away_mode(self.hass, False, ENTITY_NEST) thermostat.set_away_mode(self.hass, False, ENTITY_NEST)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_NEST) state = self.hass.states.get(ENTITY_NEST)
self.assertEqual('off', state.attributes.get('away_mode')) self.assertEqual('off', state.attributes.get('away_mode'))
@ -82,20 +82,20 @@ class TestDemoThermostat(unittest.TestCase):
state = self.hass.states.get(ENTITY_NEST) state = self.hass.states.get(ENTITY_NEST)
self.assertEqual('off', state.attributes.get('fan')) self.assertEqual('off', state.attributes.get('fan'))
thermostat.set_fan_mode(self.hass, None, ENTITY_NEST) thermostat.set_fan_mode(self.hass, None, ENTITY_NEST)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_NEST) state = self.hass.states.get(ENTITY_NEST)
self.assertEqual('off', state.attributes.get('fan')) self.assertEqual('off', state.attributes.get('fan'))
def test_set_fan_mode_on(self): def test_set_fan_mode_on(self):
"""Test setting the fan mode on/true.""" """Test setting the fan mode on/true."""
thermostat.set_fan_mode(self.hass, True, ENTITY_NEST) thermostat.set_fan_mode(self.hass, True, ENTITY_NEST)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_NEST) state = self.hass.states.get(ENTITY_NEST)
self.assertEqual('on', state.attributes.get('fan')) self.assertEqual('on', state.attributes.get('fan'))
def test_set_fan_mode_off(self): def test_set_fan_mode_off(self):
"""Test setting the fan mode off/false.""" """Test setting the fan mode off/false."""
thermostat.set_fan_mode(self.hass, False, ENTITY_NEST) thermostat.set_fan_mode(self.hass, False, ENTITY_NEST)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY_NEST) state = self.hass.states.get(ENTITY_NEST)
self.assertEqual('off', state.attributes.get('fan')) self.assertEqual('off', state.attributes.get('fan'))

View file

@ -122,7 +122,7 @@ class TestThermostatHeatControl(unittest.TestCase):
def test_set_target_temp(self): def test_set_target_temp(self):
"""Test the setting of the target temperature.""" """Test the setting of the target temperature."""
thermostat.set_temperature(self.hass, 30) thermostat.set_temperature(self.hass, 30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual('30.0', self.hass.states.get(ENTITY).state) self.assertEqual('30.0', self.hass.states.get(ENTITY).state)
def test_sensor_bad_unit(self): def test_sensor_bad_unit(self):
@ -132,7 +132,7 @@ class TestThermostatHeatControl(unittest.TestCase):
unit = state.attributes.get('unit_of_measurement') unit = state.attributes.get('unit_of_measurement')
self._setup_sensor(22.0, unit='bad_unit') self._setup_sensor(22.0, unit='bad_unit')
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY) state = self.hass.states.get(ENTITY)
self.assertEqual(unit, state.attributes.get('unit_of_measurement')) self.assertEqual(unit, state.attributes.get('unit_of_measurement'))
@ -145,7 +145,7 @@ class TestThermostatHeatControl(unittest.TestCase):
unit = state.attributes.get('unit_of_measurement') unit = state.attributes.get('unit_of_measurement')
self._setup_sensor(None) self._setup_sensor(None)
self.hass.pool.block_till_done() self.hass.block_till_done()
state = self.hass.states.get(ENTITY) state = self.hass.states.get(ENTITY)
self.assertEqual(unit, state.attributes.get('unit_of_measurement')) self.assertEqual(unit, state.attributes.get('unit_of_measurement'))
@ -155,9 +155,9 @@ class TestThermostatHeatControl(unittest.TestCase):
"""Test if target temperature turn heater on.""" """Test if target temperature turn heater on."""
self._setup_switch(False) self._setup_switch(False)
self._setup_sensor(25) self._setup_sensor(25)
self.hass.pool.block_till_done() self.hass.block_till_done()
thermostat.set_temperature(self.hass, 30) thermostat.set_temperature(self.hass, 30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -168,9 +168,9 @@ class TestThermostatHeatControl(unittest.TestCase):
"""Test if target temperature turn heater off.""" """Test if target temperature turn heater off."""
self._setup_switch(True) self._setup_switch(True)
self._setup_sensor(30) self._setup_sensor(30)
self.hass.pool.block_till_done() self.hass.block_till_done()
thermostat.set_temperature(self.hass, 25) thermostat.set_temperature(self.hass, 25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -181,9 +181,9 @@ class TestThermostatHeatControl(unittest.TestCase):
"""Test if temperature change turn heater on.""" """Test if temperature change turn heater on."""
self._setup_switch(False) self._setup_switch(False)
thermostat.set_temperature(self.hass, 30) thermostat.set_temperature(self.hass, 30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(25) self._setup_sensor(25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -194,9 +194,9 @@ class TestThermostatHeatControl(unittest.TestCase):
"""Test if temperature change turn heater off.""" """Test if temperature change turn heater off."""
self._setup_switch(True) self._setup_switch(True)
thermostat.set_temperature(self.hass, 25) thermostat.set_temperature(self.hass, 25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(30) self._setup_sensor(30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -245,9 +245,9 @@ class TestThermostatHeatControlACMode(unittest.TestCase):
"""Test if target temperature turn ac off.""" """Test if target temperature turn ac off."""
self._setup_switch(True) self._setup_switch(True)
self._setup_sensor(25) self._setup_sensor(25)
self.hass.pool.block_till_done() self.hass.block_till_done()
thermostat.set_temperature(self.hass, 30) thermostat.set_temperature(self.hass, 30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -258,9 +258,9 @@ class TestThermostatHeatControlACMode(unittest.TestCase):
"""Test if target temperature turn ac on.""" """Test if target temperature turn ac on."""
self._setup_switch(False) self._setup_switch(False)
self._setup_sensor(30) self._setup_sensor(30)
self.hass.pool.block_till_done() self.hass.block_till_done()
thermostat.set_temperature(self.hass, 25) thermostat.set_temperature(self.hass, 25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -271,9 +271,9 @@ class TestThermostatHeatControlACMode(unittest.TestCase):
"""Test if temperature change turn ac off.""" """Test if temperature change turn ac off."""
self._setup_switch(True) self._setup_switch(True)
thermostat.set_temperature(self.hass, 30) thermostat.set_temperature(self.hass, 30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(25) self._setup_sensor(25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -284,9 +284,9 @@ class TestThermostatHeatControlACMode(unittest.TestCase):
"""Test if temperature change turn ac on.""" """Test if temperature change turn ac on."""
self._setup_switch(False) self._setup_switch(False)
thermostat.set_temperature(self.hass, 25) thermostat.set_temperature(self.hass, 25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(30) self._setup_sensor(30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -336,9 +336,9 @@ class TestThermostatHeatControlACModeMinCycle(unittest.TestCase):
"""Test if temperature change turn ac on.""" """Test if temperature change turn ac on."""
self._setup_switch(False) self._setup_switch(False)
thermostat.set_temperature(self.hass, 25) thermostat.set_temperature(self.hass, 25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(30) self._setup_sensor(30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_temp_change_ac_trigger_on_long_enough(self): def test_temp_change_ac_trigger_on_long_enough(self):
@ -349,9 +349,9 @@ class TestThermostatHeatControlACModeMinCycle(unittest.TestCase):
return_value=fake_changed): return_value=fake_changed):
self._setup_switch(False) self._setup_switch(False)
thermostat.set_temperature(self.hass, 25) thermostat.set_temperature(self.hass, 25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(30) self._setup_sensor(30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -362,9 +362,9 @@ class TestThermostatHeatControlACModeMinCycle(unittest.TestCase):
"""Test if temperature change turn ac on.""" """Test if temperature change turn ac on."""
self._setup_switch(True) self._setup_switch(True)
thermostat.set_temperature(self.hass, 30) thermostat.set_temperature(self.hass, 30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(25) self._setup_sensor(25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_temp_change_ac_trigger_off_long_enough(self): def test_temp_change_ac_trigger_off_long_enough(self):
@ -375,9 +375,9 @@ class TestThermostatHeatControlACModeMinCycle(unittest.TestCase):
return_value=fake_changed): return_value=fake_changed):
self._setup_switch(True) self._setup_switch(True)
thermostat.set_temperature(self.hass, 30) thermostat.set_temperature(self.hass, 30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(25) self._setup_sensor(25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -426,18 +426,18 @@ class TestThermostatHeatControlMinCycle(unittest.TestCase):
"""Test if temp change doesn't turn heater off because of time.""" """Test if temp change doesn't turn heater off because of time."""
self._setup_switch(True) self._setup_switch(True)
thermostat.set_temperature(self.hass, 25) thermostat.set_temperature(self.hass, 25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(30) self._setup_sensor(30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_temp_change_heater_trigger_on_not_long_enough(self): def test_temp_change_heater_trigger_on_not_long_enough(self):
"""Test if temp change doesn't turn heater on because of time.""" """Test if temp change doesn't turn heater on because of time."""
self._setup_switch(False) self._setup_switch(False)
thermostat.set_temperature(self.hass, 30) thermostat.set_temperature(self.hass, 30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(25) self._setup_sensor(25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(self.calls)) self.assertEqual(0, len(self.calls))
def test_temp_change_heater_trigger_on_long_enough(self): def test_temp_change_heater_trigger_on_long_enough(self):
@ -448,9 +448,9 @@ class TestThermostatHeatControlMinCycle(unittest.TestCase):
return_value=fake_changed): return_value=fake_changed):
self._setup_switch(False) self._setup_switch(False)
thermostat.set_temperature(self.hass, 30) thermostat.set_temperature(self.hass, 30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(25) self._setup_sensor(25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)
@ -465,9 +465,9 @@ class TestThermostatHeatControlMinCycle(unittest.TestCase):
return_value=fake_changed): return_value=fake_changed):
self._setup_switch(True) self._setup_switch(True)
thermostat.set_temperature(self.hass, 25) thermostat.set_temperature(self.hass, 25)
self.hass.pool.block_till_done() self.hass.block_till_done()
self._setup_sensor(30) self._setup_sensor(30)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
call = self.calls[0] call = self.calls[0]
self.assertEqual('switch', call.domain) self.assertEqual('switch', call.domain)

View file

@ -38,11 +38,11 @@ class TestHelpersDiscovery:
discovery.discover(self.hass, 'test service', 'discovery info', discovery.discover(self.hass, 'test service', 'discovery info',
'test_component') 'test_component')
self.hass.pool.block_till_done() self.hass.block_till_done()
discovery.discover(self.hass, 'another service', 'discovery info', discovery.discover(self.hass, 'another service', 'discovery info',
'test_component') 'test_component')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert mock_setup_component.called assert mock_setup_component.called
assert mock_setup_component.call_args[0] == \ assert mock_setup_component.call_args[0] == \
@ -69,15 +69,15 @@ class TestHelpersDiscovery:
discovery.load_platform(self.hass, 'test_component', 'test_platform', discovery.load_platform(self.hass, 'test_component', 'test_platform',
'discovery info') 'discovery info')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert mock_setup_component.called assert mock_setup_component.called
assert mock_setup_component.call_args[0] == \ assert mock_setup_component.call_args[0] == \
(self.hass, 'test_component', None) (self.hass, 'test_component', None)
self.hass.pool.block_till_done() self.hass.block_till_done()
discovery.load_platform(self.hass, 'test_component_2', 'test_platform', discovery.load_platform(self.hass, 'test_component_2', 'test_platform',
'discovery info') 'discovery info')
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(calls) == 1 assert len(calls) == 1
assert calls[0] == ('test_platform', 'discovery info') assert calls[0] == ('test_platform', 'discovery info')
@ -86,7 +86,7 @@ class TestHelpersDiscovery:
discovery.ATTR_SERVICE: discovery.ATTR_SERVICE:
discovery.EVENT_LOAD_PLATFORM.format('test_component') discovery.EVENT_LOAD_PLATFORM.format('test_component')
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(calls) == 1 assert len(calls) == 1
@ -122,7 +122,7 @@ class TestHelpersDiscovery:
'platform': 'test_circular', 'platform': 'test_circular',
}], }],
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
assert 'test_component' in self.hass.config.components assert 'test_component' in self.hass.config.components
assert 'switch' in self.hass.config.components assert 'switch' in self.hass.config.components

View file

@ -104,7 +104,7 @@ class TestHelpersEntityComponent(unittest.TestCase):
poll_ent.update_ha_state.reset_mock() poll_ent.update_ha_state.reset_mock()
fire_time_changed(self.hass, dt_util.utcnow().replace(second=0)) fire_time_changed(self.hass, dt_util.utcnow().replace(second=0))
self.hass.pool.block_till_done() self.hass.block_till_done()
assert not no_poll_ent.update_ha_state.called assert not no_poll_ent.update_ha_state.called
assert poll_ent.update_ha_state.called assert poll_ent.update_ha_state.called
@ -121,7 +121,7 @@ class TestHelpersEntityComponent(unittest.TestCase):
ent2.update_ha_state = lambda *_: component.add_entities([ent1]) ent2.update_ha_state = lambda *_: component.add_entities([ent1])
fire_time_changed(self.hass, dt_util.utcnow().replace(second=0)) fire_time_changed(self.hass, dt_util.utcnow().replace(second=0))
self.hass.pool.block_till_done() self.hass.block_till_done()
assert 2 == len(self.hass.states.entity_ids()) assert 2 == len(self.hass.states.entity_ids())
@ -236,7 +236,7 @@ class TestHelpersEntityComponent(unittest.TestCase):
discovery.load_platform(self.hass, DOMAIN, 'platform_test', discovery.load_platform(self.hass, DOMAIN, 'platform_test',
{'msg': 'discovery_info'}) {'msg': 'discovery_info'})
self.hass.pool.block_till_done() self.hass.block_till_done()
assert mock_setup.called assert mock_setup.called
assert ('platform_test', {}, {'msg': 'discovery_info'}) == \ assert ('platform_test', {}, {'msg': 'discovery_info'}) == \

View file

@ -46,23 +46,23 @@ class TestEventHelpers(unittest.TestCase):
self.hass, lambda x: runs.append(1), birthday_paulus) self.hass, lambda x: runs.append(1), birthday_paulus)
self._send_time_changed(before_birthday) self._send_time_changed(before_birthday)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(runs)) self.assertEqual(0, len(runs))
self._send_time_changed(birthday_paulus) self._send_time_changed(birthday_paulus)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(runs)) self.assertEqual(1, len(runs))
# A point in time tracker will only fire once, this should do nothing # A point in time tracker will only fire once, this should do nothing
self._send_time_changed(birthday_paulus) self._send_time_changed(birthday_paulus)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(runs)) self.assertEqual(1, len(runs))
track_point_in_time( track_point_in_time(
self.hass, lambda x: runs.append(1), birthday_paulus) self.hass, lambda x: runs.append(1), birthday_paulus)
self._send_time_changed(after_birthday) self._send_time_changed(after_birthday)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(runs)) self.assertEqual(2, len(runs))
unsub = track_point_in_time( unsub = track_point_in_time(
@ -70,7 +70,7 @@ class TestEventHelpers(unittest.TestCase):
unsub() unsub()
self._send_time_changed(after_birthday) self._send_time_changed(after_birthday)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(runs)) self.assertEqual(2, len(runs))
def test_track_time_change(self): def test_track_time_change(self):
@ -83,17 +83,17 @@ class TestEventHelpers(unittest.TestCase):
self.hass, lambda x: specific_runs.append(1), second=[0, 30]) self.hass, lambda x: specific_runs.append(1), second=[0, 30])
self._send_time_changed(datetime(2014, 5, 24, 12, 0, 0)) self._send_time_changed(datetime(2014, 5, 24, 12, 0, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self.assertEqual(1, len(wildcard_runs)) self.assertEqual(1, len(wildcard_runs))
self._send_time_changed(datetime(2014, 5, 24, 12, 0, 15)) self._send_time_changed(datetime(2014, 5, 24, 12, 0, 15))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self.assertEqual(2, len(wildcard_runs)) self.assertEqual(2, len(wildcard_runs))
self._send_time_changed(datetime(2014, 5, 24, 12, 0, 30)) self._send_time_changed(datetime(2014, 5, 24, 12, 0, 30))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(specific_runs)) self.assertEqual(2, len(specific_runs))
self.assertEqual(3, len(wildcard_runs)) self.assertEqual(3, len(wildcard_runs))
@ -101,7 +101,7 @@ class TestEventHelpers(unittest.TestCase):
unsub_utc() unsub_utc()
self._send_time_changed(datetime(2014, 5, 24, 12, 0, 30)) self._send_time_changed(datetime(2014, 5, 24, 12, 0, 30))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(specific_runs)) self.assertEqual(2, len(specific_runs))
self.assertEqual(3, len(wildcard_runs)) self.assertEqual(3, len(wildcard_runs))
@ -126,7 +126,7 @@ class TestEventHelpers(unittest.TestCase):
# Adding state to state machine # Adding state to state machine
self.hass.states.set("light.Bowl", "on") self.hass.states.set("light.Bowl", "on")
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(specific_runs)) self.assertEqual(0, len(specific_runs))
self.assertEqual(1, len(wildcard_runs)) self.assertEqual(1, len(wildcard_runs))
self.assertEqual(1, len(wildercard_runs)) self.assertEqual(1, len(wildercard_runs))
@ -135,34 +135,34 @@ class TestEventHelpers(unittest.TestCase):
# Set same state should not trigger a state change/listener # Set same state should not trigger a state change/listener
self.hass.states.set('light.Bowl', 'on') self.hass.states.set('light.Bowl', 'on')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(specific_runs)) self.assertEqual(0, len(specific_runs))
self.assertEqual(1, len(wildcard_runs)) self.assertEqual(1, len(wildcard_runs))
self.assertEqual(1, len(wildercard_runs)) self.assertEqual(1, len(wildercard_runs))
# State change off -> on # State change off -> on
self.hass.states.set('light.Bowl', 'off') self.hass.states.set('light.Bowl', 'off')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self.assertEqual(2, len(wildcard_runs)) self.assertEqual(2, len(wildcard_runs))
self.assertEqual(2, len(wildercard_runs)) self.assertEqual(2, len(wildercard_runs))
# State change off -> off # State change off -> off
self.hass.states.set('light.Bowl', 'off', {"some_attr": 1}) self.hass.states.set('light.Bowl', 'off', {"some_attr": 1})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self.assertEqual(3, len(wildcard_runs)) self.assertEqual(3, len(wildcard_runs))
self.assertEqual(3, len(wildercard_runs)) self.assertEqual(3, len(wildercard_runs))
# State change off -> on # State change off -> on
self.hass.states.set('light.Bowl', 'on') self.hass.states.set('light.Bowl', 'on')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self.assertEqual(4, len(wildcard_runs)) self.assertEqual(4, len(wildcard_runs))
self.assertEqual(4, len(wildercard_runs)) self.assertEqual(4, len(wildercard_runs))
self.hass.states.remove('light.bowl') self.hass.states.remove('light.bowl')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self.assertEqual(5, len(wildcard_runs)) self.assertEqual(5, len(wildcard_runs))
self.assertEqual(5, len(wildercard_runs)) self.assertEqual(5, len(wildercard_runs))
@ -173,7 +173,7 @@ class TestEventHelpers(unittest.TestCase):
# Set state for different entity id # Set state for different entity id
self.hass.states.set('switch.kitchen', 'on') self.hass.states.set('switch.kitchen', 'on')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self.assertEqual(5, len(wildcard_runs)) self.assertEqual(5, len(wildcard_runs))
self.assertEqual(6, len(wildercard_runs)) self.assertEqual(6, len(wildercard_runs))
@ -211,17 +211,17 @@ class TestEventHelpers(unittest.TestCase):
# run tests # run tests
self._send_time_changed(next_rising - offset) self._send_time_changed(next_rising - offset)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(runs)) self.assertEqual(0, len(runs))
self.assertEqual(0, len(offset_runs)) self.assertEqual(0, len(offset_runs))
self._send_time_changed(next_rising) self._send_time_changed(next_rising)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(runs)) self.assertEqual(1, len(runs))
self.assertEqual(0, len(offset_runs)) self.assertEqual(0, len(offset_runs))
self._send_time_changed(next_rising + offset) self._send_time_changed(next_rising + offset)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(runs)) self.assertEqual(2, len(runs))
self.assertEqual(1, len(offset_runs)) self.assertEqual(1, len(offset_runs))
@ -229,7 +229,7 @@ class TestEventHelpers(unittest.TestCase):
unsub2() unsub2()
self._send_time_changed(next_rising + offset) self._send_time_changed(next_rising + offset)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(runs)) self.assertEqual(2, len(runs))
self.assertEqual(1, len(offset_runs)) self.assertEqual(1, len(offset_runs))
@ -265,17 +265,17 @@ class TestEventHelpers(unittest.TestCase):
# Run tests # Run tests
self._send_time_changed(next_setting - offset) self._send_time_changed(next_setting - offset)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(runs)) self.assertEqual(0, len(runs))
self.assertEqual(0, len(offset_runs)) self.assertEqual(0, len(offset_runs))
self._send_time_changed(next_setting) self._send_time_changed(next_setting)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(runs)) self.assertEqual(1, len(runs))
self.assertEqual(0, len(offset_runs)) self.assertEqual(0, len(offset_runs))
self._send_time_changed(next_setting + offset) self._send_time_changed(next_setting + offset)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(runs)) self.assertEqual(2, len(runs))
self.assertEqual(1, len(offset_runs)) self.assertEqual(1, len(offset_runs))
@ -283,7 +283,7 @@ class TestEventHelpers(unittest.TestCase):
unsub2() unsub2()
self._send_time_changed(next_setting + offset) self._send_time_changed(next_setting + offset)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(runs)) self.assertEqual(2, len(runs))
self.assertEqual(1, len(offset_runs)) self.assertEqual(1, len(offset_runs))
@ -299,21 +299,21 @@ class TestEventHelpers(unittest.TestCase):
self.hass, lambda x: specific_runs.append(1), minute='/5') self.hass, lambda x: specific_runs.append(1), minute='/5')
self._send_time_changed(datetime(2014, 5, 24, 12, 0, 0)) self._send_time_changed(datetime(2014, 5, 24, 12, 0, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self._send_time_changed(datetime(2014, 5, 24, 12, 3, 0)) self._send_time_changed(datetime(2014, 5, 24, 12, 3, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self._send_time_changed(datetime(2014, 5, 24, 12, 5, 0)) self._send_time_changed(datetime(2014, 5, 24, 12, 5, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(specific_runs)) self.assertEqual(2, len(specific_runs))
unsub() unsub()
self._send_time_changed(datetime(2014, 5, 24, 12, 5, 0)) self._send_time_changed(datetime(2014, 5, 24, 12, 5, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(specific_runs)) self.assertEqual(2, len(specific_runs))
def test_periodic_task_hour(self): def test_periodic_task_hour(self):
@ -324,29 +324,29 @@ class TestEventHelpers(unittest.TestCase):
self.hass, lambda x: specific_runs.append(1), hour='/2') self.hass, lambda x: specific_runs.append(1), hour='/2')
self._send_time_changed(datetime(2014, 5, 24, 22, 0, 0)) self._send_time_changed(datetime(2014, 5, 24, 22, 0, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self._send_time_changed(datetime(2014, 5, 24, 23, 0, 0)) self._send_time_changed(datetime(2014, 5, 24, 23, 0, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self._send_time_changed(datetime(2014, 5, 24, 0, 0, 0)) self._send_time_changed(datetime(2014, 5, 24, 0, 0, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(specific_runs)) self.assertEqual(2, len(specific_runs))
self._send_time_changed(datetime(2014, 5, 25, 1, 0, 0)) self._send_time_changed(datetime(2014, 5, 25, 1, 0, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(specific_runs)) self.assertEqual(2, len(specific_runs))
self._send_time_changed(datetime(2014, 5, 25, 2, 0, 0)) self._send_time_changed(datetime(2014, 5, 25, 2, 0, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(3, len(specific_runs)) self.assertEqual(3, len(specific_runs))
unsub() unsub()
self._send_time_changed(datetime(2014, 5, 25, 2, 0, 0)) self._send_time_changed(datetime(2014, 5, 25, 2, 0, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(3, len(specific_runs)) self.assertEqual(3, len(specific_runs))
def test_periodic_task_day(self): def test_periodic_task_day(self):
@ -357,21 +357,21 @@ class TestEventHelpers(unittest.TestCase):
self.hass, lambda x: specific_runs.append(1), day='/2') self.hass, lambda x: specific_runs.append(1), day='/2')
self._send_time_changed(datetime(2014, 5, 2, 0, 0, 0)) self._send_time_changed(datetime(2014, 5, 2, 0, 0, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self._send_time_changed(datetime(2014, 5, 3, 12, 0, 0)) self._send_time_changed(datetime(2014, 5, 3, 12, 0, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self._send_time_changed(datetime(2014, 5, 4, 0, 0, 0)) self._send_time_changed(datetime(2014, 5, 4, 0, 0, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(specific_runs)) self.assertEqual(2, len(specific_runs))
unsub() unsub()
self._send_time_changed(datetime(2014, 5, 4, 0, 0, 0)) self._send_time_changed(datetime(2014, 5, 4, 0, 0, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(specific_runs)) self.assertEqual(2, len(specific_runs))
def test_periodic_task_year(self): def test_periodic_task_year(self):
@ -382,21 +382,21 @@ class TestEventHelpers(unittest.TestCase):
self.hass, lambda x: specific_runs.append(1), year='/2') self.hass, lambda x: specific_runs.append(1), year='/2')
self._send_time_changed(datetime(2014, 5, 2, 0, 0, 0)) self._send_time_changed(datetime(2014, 5, 2, 0, 0, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self._send_time_changed(datetime(2015, 5, 2, 0, 0, 0)) self._send_time_changed(datetime(2015, 5, 2, 0, 0, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self._send_time_changed(datetime(2016, 5, 2, 0, 0, 0)) self._send_time_changed(datetime(2016, 5, 2, 0, 0, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(specific_runs)) self.assertEqual(2, len(specific_runs))
unsub() unsub()
self._send_time_changed(datetime(2016, 5, 2, 0, 0, 0)) self._send_time_changed(datetime(2016, 5, 2, 0, 0, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(specific_runs)) self.assertEqual(2, len(specific_runs))
def test_periodic_task_wrong_input(self): def test_periodic_task_wrong_input(self):
@ -407,5 +407,5 @@ class TestEventHelpers(unittest.TestCase):
self.hass, lambda x: specific_runs.append(1), year='/two') self.hass, lambda x: specific_runs.append(1), year='/two')
self._send_time_changed(datetime(2014, 5, 2, 0, 0, 0)) self._send_time_changed(datetime(2014, 5, 2, 0, 0, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(specific_runs)) self.assertEqual(0, len(specific_runs))

View file

@ -67,17 +67,17 @@ class TestEventDecoratorHelpers(unittest.TestCase):
# Run tests # Run tests
self._send_time_changed(next_rising - offset) self._send_time_changed(next_rising - offset)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(runs)) self.assertEqual(0, len(runs))
self.assertEqual(0, len(offset_runs)) self.assertEqual(0, len(offset_runs))
self._send_time_changed(next_rising) self._send_time_changed(next_rising)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(runs)) self.assertEqual(1, len(runs))
self.assertEqual(0, len(offset_runs)) self.assertEqual(0, len(offset_runs))
self._send_time_changed(next_rising + offset) self._send_time_changed(next_rising + offset)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(runs)) self.assertEqual(2, len(runs))
self.assertEqual(1, len(offset_runs)) self.assertEqual(1, len(offset_runs))
@ -115,17 +115,17 @@ class TestEventDecoratorHelpers(unittest.TestCase):
# run tests # run tests
self._send_time_changed(next_setting - offset) self._send_time_changed(next_setting - offset)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(runs)) self.assertEqual(0, len(runs))
self.assertEqual(0, len(offset_runs)) self.assertEqual(0, len(offset_runs))
self._send_time_changed(next_setting) self._send_time_changed(next_setting)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(runs)) self.assertEqual(1, len(runs))
self.assertEqual(0, len(offset_runs)) self.assertEqual(0, len(offset_runs))
self._send_time_changed(next_setting + offset) self._send_time_changed(next_setting + offset)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(runs)) self.assertEqual(2, len(runs))
self.assertEqual(1, len(offset_runs)) self.assertEqual(1, len(offset_runs))
@ -141,17 +141,17 @@ class TestEventDecoratorHelpers(unittest.TestCase):
decor(lambda x, y: specific_runs.append(1)) decor(lambda x, y: specific_runs.append(1))
self._send_time_changed(datetime(2014, 5, 24, 12, 0, 0)) self._send_time_changed(datetime(2014, 5, 24, 12, 0, 0))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self.assertEqual(1, len(wildcard_runs)) self.assertEqual(1, len(wildcard_runs))
self._send_time_changed(datetime(2014, 5, 24, 12, 0, 15)) self._send_time_changed(datetime(2014, 5, 24, 12, 0, 15))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self.assertEqual(2, len(wildcard_runs)) self.assertEqual(2, len(wildcard_runs))
self._send_time_changed(datetime(2014, 5, 24, 12, 0, 30)) self._send_time_changed(datetime(2014, 5, 24, 12, 0, 30))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(2, len(specific_runs)) self.assertEqual(2, len(specific_runs))
self.assertEqual(3, len(wildcard_runs)) self.assertEqual(3, len(wildcard_runs))
@ -169,25 +169,25 @@ class TestEventDecoratorHelpers(unittest.TestCase):
# Set same state should not trigger a state change/listener # Set same state should not trigger a state change/listener
self.hass.states.set('light.Bowl', 'on') self.hass.states.set('light.Bowl', 'on')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(specific_runs)) self.assertEqual(0, len(specific_runs))
self.assertEqual(0, len(wildcard_runs)) self.assertEqual(0, len(wildcard_runs))
# State change off -> on # State change off -> on
self.hass.states.set('light.Bowl', 'off') self.hass.states.set('light.Bowl', 'off')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self.assertEqual(1, len(wildcard_runs)) self.assertEqual(1, len(wildcard_runs))
# State change off -> off # State change off -> off
self.hass.states.set('light.Bowl', 'off', {"some_attr": 1}) self.hass.states.set('light.Bowl', 'off', {"some_attr": 1})
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self.assertEqual(2, len(wildcard_runs)) self.assertEqual(2, len(wildcard_runs))
# State change off -> on # State change off -> on
self.hass.states.set('light.Bowl', 'on') self.hass.states.set('light.Bowl', 'on')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(specific_runs)) self.assertEqual(1, len(specific_runs))
self.assertEqual(3, len(wildcard_runs)) self.assertEqual(3, len(wildcard_runs))

View file

@ -45,7 +45,7 @@ class TestScriptHelper(unittest.TestCase):
script_obj.run() script_obj.run()
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(calls) == 1 assert len(calls) == 1
assert calls[0].data.get('hello') == 'world' assert calls[0].data.get('hello') == 'world'
@ -69,7 +69,7 @@ class TestScriptHelper(unittest.TestCase):
}) })
script_obj.run() script_obj.run()
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(calls) == 1 assert len(calls) == 1
assert calls[0].data.get('hello') == 'world' assert calls[0].data.get('hello') == 'world'
@ -104,7 +104,7 @@ class TestScriptHelper(unittest.TestCase):
script_obj.run() script_obj.run()
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(calls) == 1 assert len(calls) == 1
assert calls[0].data.get('hello') == 'world' assert calls[0].data.get('hello') == 'world'
@ -127,7 +127,7 @@ class TestScriptHelper(unittest.TestCase):
script_obj.run() script_obj.run()
self.hass.pool.block_till_done() self.hass.block_till_done()
assert script_obj.is_running assert script_obj.is_running
assert script_obj.can_cancel assert script_obj.can_cancel
@ -136,7 +136,7 @@ class TestScriptHelper(unittest.TestCase):
future = dt_util.utcnow() + timedelta(seconds=5) future = dt_util.utcnow() + timedelta(seconds=5)
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert not script_obj.is_running assert not script_obj.is_running
assert len(events) == 2 assert len(events) == 2
@ -159,7 +159,7 @@ class TestScriptHelper(unittest.TestCase):
script_obj.run() script_obj.run()
self.hass.pool.block_till_done() self.hass.block_till_done()
assert script_obj.is_running assert script_obj.is_running
assert script_obj.can_cancel assert script_obj.can_cancel
@ -168,7 +168,7 @@ class TestScriptHelper(unittest.TestCase):
future = dt_util.utcnow() + timedelta(seconds=5) future = dt_util.utcnow() + timedelta(seconds=5)
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert not script_obj.is_running assert not script_obj.is_running
assert len(events) == 2 assert len(events) == 2
@ -190,7 +190,7 @@ class TestScriptHelper(unittest.TestCase):
script_obj.run() script_obj.run()
self.hass.pool.block_till_done() self.hass.block_till_done()
assert script_obj.is_running assert script_obj.is_running
assert len(events) == 0 assert len(events) == 0
@ -202,7 +202,7 @@ class TestScriptHelper(unittest.TestCase):
# Make sure the script is really stopped. # Make sure the script is really stopped.
future = dt_util.utcnow() + timedelta(seconds=5) future = dt_util.utcnow() + timedelta(seconds=5)
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert not script_obj.is_running assert not script_obj.is_running
assert len(events) == 0 assert len(events) == 0
@ -237,7 +237,7 @@ class TestScriptHelper(unittest.TestCase):
'greeting2': 'universe', 'greeting2': 'universe',
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
assert script_obj.is_running assert script_obj.is_running
assert len(calls) == 1 assert len(calls) == 1
@ -245,7 +245,7 @@ class TestScriptHelper(unittest.TestCase):
future = dt_util.utcnow() + timedelta(seconds=5) future = dt_util.utcnow() + timedelta(seconds=5)
fire_time_changed(self.hass, future) fire_time_changed(self.hass, future)
self.hass.pool.block_till_done() self.hass.block_till_done()
assert not script_obj.is_running assert not script_obj.is_running
assert len(calls) == 2 assert len(calls) == 2
@ -274,11 +274,11 @@ class TestScriptHelper(unittest.TestCase):
]) ])
script_obj.run() script_obj.run()
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(events) == 2 assert len(events) == 2
self.hass.states.set('test.entity', 'goodbye') self.hass.states.set('test.entity', 'goodbye')
script_obj.run() script_obj.run()
self.hass.pool.block_till_done() self.hass.block_till_done()
assert len(events) == 3 assert len(events) == 3

View file

@ -33,7 +33,7 @@ class TestServiceHelpers(unittest.TestCase):
decor(lambda x, y: runs.append(1)) decor(lambda x, y: runs.append(1))
self.hass.services.call('test', 'test') self.hass.services.call('test', 'test')
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(runs)) self.assertEqual(1, len(runs))
def test_template_service_call(self): def test_template_service_call(self):
@ -56,7 +56,7 @@ class TestServiceHelpers(unittest.TestCase):
decor(lambda x, y: runs.append(y)) decor(lambda x, y: runs.append(y))
service.call_from_config(self.hass, config) service.call_from_config(self.hass, config)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual('goodbye', runs[0].data['hello']) self.assertEqual('goodbye', runs[0].data['hello'])
self.assertEqual('complex', runs[0].data['data']['value']) self.assertEqual('complex', runs[0].data['data']['value'])
@ -81,7 +81,7 @@ class TestServiceHelpers(unittest.TestCase):
'var_service': 'test_domain.test_service', 'var_service': 'test_domain.test_service',
'var_data': 'goodbye', 'var_data': 'goodbye',
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual('goodbye', runs[0].data['hello']) self.assertEqual('goodbye', runs[0].data['hello'])
@ -91,7 +91,7 @@ class TestServiceHelpers(unittest.TestCase):
'service': 'test_domain.test_service', 'service': 'test_domain.test_service',
'entity_id': 'hello.world, sensor.beer' 'entity_id': 'hello.world, sensor.beer'
}) })
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(['hello.world', 'sensor.beer'], self.assertEqual(['hello.world', 'sensor.beer'],
self.calls[-1].data.get('entity_id')) self.calls[-1].data.get('entity_id'))
@ -105,7 +105,7 @@ class TestServiceHelpers(unittest.TestCase):
}, },
} }
service.call_from_config(self.hass, orig) service.call_from_config(self.hass, orig)
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual({ self.assertEqual({
'service': 'test_domain.test_service', 'service': 'test_domain.test_service',
'entity_id': 'hello.world, sensor.beer', 'entity_id': 'hello.world, sensor.beer',

View file

@ -85,7 +85,7 @@ class TestStateHelpers(unittest.TestCase):
state.reproduce_state(self.hass, ha.State('light.test', 'on')) state.reproduce_state(self.hass, ha.State('light.test', 'on'))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(len(calls) == 0) self.assertTrue(len(calls) == 0)
self.assertEqual(None, self.hass.states.get('light.test')) self.assertEqual(None, self.hass.states.get('light.test'))
@ -98,7 +98,7 @@ class TestStateHelpers(unittest.TestCase):
state.reproduce_state(self.hass, ha.State('light.test', 'on')) state.reproduce_state(self.hass, ha.State('light.test', 'on'))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(len(calls) > 0) self.assertTrue(len(calls) > 0)
last_call = calls[-1] last_call = calls[-1]
@ -114,7 +114,7 @@ class TestStateHelpers(unittest.TestCase):
state.reproduce_state(self.hass, ha.State('light.test', 'off')) state.reproduce_state(self.hass, ha.State('light.test', 'off'))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(len(calls) > 0) self.assertTrue(len(calls) > 0)
last_call = calls[-1] last_call = calls[-1]
@ -134,7 +134,7 @@ class TestStateHelpers(unittest.TestCase):
'complex': complex_data 'complex': complex_data
})) }))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(len(calls) > 0) self.assertTrue(len(calls) > 0)
last_call = calls[-1] last_call = calls[-1]
@ -154,7 +154,7 @@ class TestStateHelpers(unittest.TestCase):
state.reproduce_state(self.hass, ha.State('media_player.test', 'None', state.reproduce_state(self.hass, ha.State('media_player.test', 'None',
media_attributes)) media_attributes))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(len(calls) > 0) self.assertTrue(len(calls) > 0)
last_call = calls[-1] last_call = calls[-1]
@ -172,7 +172,7 @@ class TestStateHelpers(unittest.TestCase):
state.reproduce_state( state.reproduce_state(
self.hass, ha.State('media_player.test', 'playing')) self.hass, ha.State('media_player.test', 'playing'))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(len(calls) > 0) self.assertTrue(len(calls) > 0)
last_call = calls[-1] last_call = calls[-1]
@ -190,7 +190,7 @@ class TestStateHelpers(unittest.TestCase):
state.reproduce_state( state.reproduce_state(
self.hass, ha.State('media_player.test', 'paused')) self.hass, ha.State('media_player.test', 'paused'))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(len(calls) > 0) self.assertTrue(len(calls) > 0)
last_call = calls[-1] last_call = calls[-1]
@ -207,7 +207,7 @@ class TestStateHelpers(unittest.TestCase):
state.reproduce_state(self.hass, ha.State('light.test', 'bad')) state.reproduce_state(self.hass, ha.State('light.test', 'bad'))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertTrue(len(calls) == 0) self.assertTrue(len(calls) == 0)
self.assertEqual('off', self.hass.states.get('light.test').state) self.assertEqual('off', self.hass.states.get('light.test').state)
@ -221,7 +221,7 @@ class TestStateHelpers(unittest.TestCase):
state.reproduce_state(self.hass, ha.State('group.test', 'on')) state.reproduce_state(self.hass, ha.State('group.test', 'on'))
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(light_calls)) self.assertEqual(1, len(light_calls))
last_call = light_calls[-1] last_call = light_calls[-1]
@ -241,7 +241,7 @@ class TestStateHelpers(unittest.TestCase):
ha.State('light.test1', 'on', {'brightness': 95}), ha.State('light.test1', 'on', {'brightness': 95}),
ha.State('light.test2', 'on', {'brightness': 95})]) ha.State('light.test2', 'on', {'brightness': 95})])
self.hass.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(light_calls)) self.assertEqual(1, len(light_calls))
last_call = light_calls[-1] last_call = light_calls[-1]

View file

@ -1,7 +1,9 @@
"""Test check_config script.""" """Test check_config script."""
import unittest import asyncio
import logging import logging
import os import os
import unittest
from unittest.mock import patch
import homeassistant.scripts.check_config as check_config import homeassistant.scripts.check_config as check_config
from tests.common import patch_yaml_files, get_test_config_dir from tests.common import patch_yaml_files, get_test_config_dir
@ -43,11 +45,12 @@ def tearDownModule(self): # pylint: disable=invalid-name
os.remove(path) os.remove(path)
@patch('asyncio.get_event_loop', return_value=asyncio.new_event_loop())
class TestCheckConfig(unittest.TestCase): class TestCheckConfig(unittest.TestCase):
"""Tests for the homeassistant.scripts.check_config module.""" """Tests for the homeassistant.scripts.check_config module."""
# pylint: disable=no-self-use,invalid-name # pylint: disable=no-self-use,invalid-name
def test_config_platform_valid(self): def test_config_platform_valid(self, mock_get_loop):
"""Test a valid platform setup.""" """Test a valid platform setup."""
files = { files = {
'light.yaml': BASE_CONFIG + 'light:\n platform: hue', 'light.yaml': BASE_CONFIG + 'light:\n platform: hue',
@ -63,7 +66,7 @@ class TestCheckConfig(unittest.TestCase):
'yaml_files': ['.../light.yaml'] 'yaml_files': ['.../light.yaml']
}, res) }, res)
def test_config_component_platform_fail_validation(self): def test_config_component_platform_fail_validation(self, mock_get_loop):
"""Test errors if component & platform not found.""" """Test errors if component & platform not found."""
files = { files = {
'component.yaml': BASE_CONFIG + 'http:\n password: err123', 'component.yaml': BASE_CONFIG + 'http:\n password: err123',
@ -95,7 +98,7 @@ class TestCheckConfig(unittest.TestCase):
'yaml_files': ['.../platform.yaml'] 'yaml_files': ['.../platform.yaml']
}, res) }, res)
def test_component_platform_not_found(self): def test_component_platform_not_found(self, mock_get_loop):
"""Test errors if component or platform not found.""" """Test errors if component or platform not found."""
files = { files = {
'badcomponent.yaml': BASE_CONFIG + 'beer:', 'badcomponent.yaml': BASE_CONFIG + 'beer:',
@ -124,7 +127,7 @@ class TestCheckConfig(unittest.TestCase):
'yaml_files': ['.../badplatform.yaml'] 'yaml_files': ['.../badplatform.yaml']
}, res) }, res)
def test_secrets(self): def test_secrets(self, mock_get_loop):
"""Test secrets config checking method.""" """Test secrets config checking method."""
files = { files = {
get_test_config_dir('secret.yaml'): ( get_test_config_dir('secret.yaml'): (

View file

@ -206,6 +206,8 @@ class TestConfig(unittest.TestCase):
entity.hass = self.hass entity.hass = self.hass
entity.update_ha_state() entity.update_ha_state()
self.hass.block_till_done()
state = self.hass.states.get('test.test') state = self.hass.states.get('test.test')
assert state.attributes['hidden'] assert state.attributes['hidden']

View file

@ -5,15 +5,12 @@ import os
import signal import signal
import unittest import unittest
from unittest.mock import patch from unittest.mock import patch
import time
import threading
from datetime import datetime, timedelta from datetime import datetime, timedelta
import pytz import pytz
import homeassistant.core as ha import homeassistant.core as ha
from homeassistant.exceptions import ( from homeassistant.exceptions import InvalidEntityFormatError
HomeAssistantError, InvalidEntityFormatError)
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
from homeassistant.util.unit_system import (METRIC_SYSTEM) from homeassistant.util.unit_system import (METRIC_SYSTEM)
from homeassistant.const import ( from homeassistant.const import (
@ -39,63 +36,28 @@ class TestHomeAssistant(unittest.TestCase):
def setUp(self): # pylint: disable=invalid-name def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started.""" """Setup things to be run when tests are started."""
self.hass = get_test_home_assistant() self.hass = get_test_home_assistant(0)
self.hass.states.set("light.Bowl", "on")
self.hass.states.set("switch.AC", "off")
def tearDown(self): # pylint: disable=invalid-name def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started.""" """Stop everything that was started."""
try:
self.hass.stop() self.hass.stop()
except HomeAssistantError:
# Already stopped after the block till stopped test
pass
def test_start(self): def test_start_and_sigterm(self):
"""Start the test.""" """Start the test."""
calls = [] calls = []
self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START,
lambda event: calls.append(1)) lambda event: calls.append(1))
self.hass.start() self.hass.start()
self.hass.pool.block_till_done()
self.assertEqual(1, len(calls)) self.assertEqual(1, len(calls))
# @patch('homeassistant.core.time.sleep')
def test_block_till_stoped(self):
"""Test if we can block till stop service is called."""
with patch('time.sleep'):
blocking_thread = threading.Thread(
target=self.hass.block_till_stopped)
self.assertFalse(blocking_thread.is_alive())
blocking_thread.start()
self.assertTrue(blocking_thread.is_alive())
self.hass.services.call(ha.DOMAIN, ha.SERVICE_HOMEASSISTANT_STOP)
self.hass.pool.block_till_done()
# Wait for thread to stop
for _ in range(20):
if not blocking_thread.is_alive():
break
time.sleep(0.05)
self.assertFalse(blocking_thread.is_alive())
def test_stopping_with_sigterm(self):
"""Test for stopping with sigterm."""
calls = []
self.hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, self.hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP,
lambda event: calls.append(1)) lambda event: calls.append(1))
def send_sigterm(length):
"""Send sigterm."""
os.kill(os.getpid(), signal.SIGTERM) os.kill(os.getpid(), signal.SIGTERM)
with patch('homeassistant.core.time.sleep', send_sigterm): self.hass.block_till_done()
self.hass.block_till_stopped()
self.assertEqual(1, len(calls)) self.assertEqual(1, len(calls))
@ -147,16 +109,16 @@ class TestEventBus(unittest.TestCase):
def setUp(self): # pylint: disable=invalid-name def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started.""" """Setup things to be run when tests are started."""
self.bus = ha.EventBus(ha.create_worker_pool(0)) self.hass = get_test_home_assistant()
self.bus = self.hass.bus
self.bus.listen('test_event', lambda x: len) self.bus.listen('test_event', lambda x: len)
def tearDown(self): # pylint: disable=invalid-name def tearDown(self): # pylint: disable=invalid-name
"""Stop down stuff we started.""" """Stop down stuff we started."""
self.bus._pool.stop() self.hass.stop()
def test_add_remove_listener(self): def test_add_remove_listener(self):
"""Test remove_listener method.""" """Test remove_listener method."""
self.bus._pool.add_worker()
old_count = len(self.bus.listeners) old_count = len(self.bus.listeners)
def listener(_): pass def listener(_): pass
@ -177,7 +139,6 @@ class TestEventBus(unittest.TestCase):
def test_unsubscribe_listener(self): def test_unsubscribe_listener(self):
"""Test unsubscribe listener from returned function.""" """Test unsubscribe listener from returned function."""
self.bus._pool.add_worker()
calls = [] calls = []
def listener(event): def listener(event):
@ -187,14 +148,14 @@ class TestEventBus(unittest.TestCase):
unsub = self.bus.listen('test', listener) unsub = self.bus.listen('test', listener)
self.bus.fire('test') self.bus.fire('test')
self.bus._pool.block_till_done() self.hass.block_till_done()
assert len(calls) == 1 assert len(calls) == 1
unsub() unsub()
self.bus.fire('event') self.bus.fire('event')
self.bus._pool.block_till_done() self.hass.block_till_done()
assert len(calls) == 1 assert len(calls) == 1
@ -208,8 +169,7 @@ class TestEventBus(unittest.TestCase):
# Second time it should not increase runs # Second time it should not increase runs
self.bus.fire('test_event') self.bus.fire('test_event')
self.bus._pool.add_worker() self.hass.block_till_done()
self.bus._pool.block_till_done()
self.assertEqual(1, len(runs)) self.assertEqual(1, len(runs))
@ -274,15 +234,14 @@ class TestStateMachine(unittest.TestCase):
def setUp(self): # pylint: disable=invalid-name def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started.""" """Setup things to be run when tests are started."""
self.pool = ha.create_worker_pool(0) self.hass = get_test_home_assistant(0)
self.bus = ha.EventBus(self.pool) self.states = self.hass.states
self.states = ha.StateMachine(self.bus)
self.states.set("light.Bowl", "on") self.states.set("light.Bowl", "on")
self.states.set("switch.AC", "off") self.states.set("switch.AC", "off")
def tearDown(self): # pylint: disable=invalid-name def tearDown(self): # pylint: disable=invalid-name
"""Stop down stuff we started.""" """Stop down stuff we started."""
self.pool.stop() self.hass.stop()
def test_is_state(self): def test_is_state(self):
"""Test is_state method.""" """Test is_state method."""
@ -320,14 +279,13 @@ class TestStateMachine(unittest.TestCase):
def test_remove(self): def test_remove(self):
"""Test remove method.""" """Test remove method."""
self.pool.add_worker()
events = [] events = []
self.bus.listen(EVENT_STATE_CHANGED, self.hass.bus.listen(EVENT_STATE_CHANGED,
lambda event: events.append(event)) lambda event: events.append(event))
self.assertIn('light.bowl', self.states.entity_ids()) self.assertIn('light.bowl', self.states.entity_ids())
self.assertTrue(self.states.remove('light.bowl')) self.assertTrue(self.states.remove('light.bowl'))
self.pool.block_till_done() self.hass.block_till_done()
self.assertNotIn('light.bowl', self.states.entity_ids()) self.assertNotIn('light.bowl', self.states.entity_ids())
self.assertEqual(1, len(events)) self.assertEqual(1, len(events))
@ -338,18 +296,18 @@ class TestStateMachine(unittest.TestCase):
# If it does not exist, we should get False # If it does not exist, we should get False
self.assertFalse(self.states.remove('light.Bowl')) self.assertFalse(self.states.remove('light.Bowl'))
self.pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(events)) self.assertEqual(1, len(events))
def test_case_insensitivty(self): def test_case_insensitivty(self):
"""Test insensitivty.""" """Test insensitivty."""
self.pool.add_worker()
runs = [] runs = []
self.bus.listen(EVENT_STATE_CHANGED, lambda event: runs.append(event)) self.hass.bus.listen(EVENT_STATE_CHANGED,
lambda event: runs.append(event))
self.states.set('light.BOWL', 'off') self.states.set('light.BOWL', 'off')
self.bus._pool.block_till_done() self.hass.block_till_done()
self.assertTrue(self.states.is_state('light.bowl', 'off')) self.assertTrue(self.states.is_state('light.bowl', 'off'))
self.assertEqual(1, len(runs)) self.assertEqual(1, len(runs))
@ -362,22 +320,23 @@ class TestStateMachine(unittest.TestCase):
with patch('homeassistant.util.dt.utcnow', return_value=future): with patch('homeassistant.util.dt.utcnow', return_value=future):
self.states.set("light.Bowl", "on", {'attr': 'triggers_change'}) self.states.set("light.Bowl", "on", {'attr': 'triggers_change'})
self.hass.block_till_done()
self.assertEqual(state.last_changed, state2 = self.states.get('light.Bowl')
self.states.get('light.Bowl').last_changed) assert state2 is not None
assert state.last_changed == state2.last_changed
def test_force_update(self): def test_force_update(self):
"""Test force update option.""" """Test force update option."""
self.pool.add_worker()
events = [] events = []
self.bus.listen(EVENT_STATE_CHANGED, events.append) self.hass.bus.listen(EVENT_STATE_CHANGED, events.append)
self.states.set('light.bowl', 'on') self.states.set('light.bowl', 'on')
self.bus._pool.block_till_done() self.hass.block_till_done()
self.assertEqual(0, len(events)) self.assertEqual(0, len(events))
self.states.set('light.bowl', 'on', None, True) self.states.set('light.bowl', 'on', None, True)
self.bus._pool.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(events)) self.assertEqual(1, len(events))
@ -400,21 +359,14 @@ class TestServiceRegistry(unittest.TestCase):
def setUp(self): # pylint: disable=invalid-name def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started.""" """Setup things to be run when tests are started."""
self.pool = ha.create_worker_pool(0) self.hass = get_test_home_assistant()
self.bus = ha.EventBus(self.pool) self.services = self.hass.services
def add_job(*args, **kwargs):
"""Forward calls to add_job on Home Assistant."""
# self works because we also have self.pool defined.
return ha.HomeAssistant.add_job(self, *args, **kwargs)
self.services = ha.ServiceRegistry(self.bus, add_job)
self.services.register("Test_Domain", "TEST_SERVICE", lambda x: None) self.services.register("Test_Domain", "TEST_SERVICE", lambda x: None)
self.hass.block_till_done()
def tearDown(self): # pylint: disable=invalid-name def tearDown(self): # pylint: disable=invalid-name
"""Stop down stuff we started.""" """Stop down stuff we started."""
if self.pool.worker_count: self.hass.stop()
self.pool.stop()
def test_has_service(self): def test_has_service(self):
"""Test has_service method.""" """Test has_service method."""
@ -434,8 +386,6 @@ class TestServiceRegistry(unittest.TestCase):
def test_call_with_blocking_done_in_time(self): def test_call_with_blocking_done_in_time(self):
"""Test call with blocking.""" """Test call with blocking."""
self.pool.add_worker()
self.pool.add_worker()
calls = [] calls = []
self.services.register("test_domain", "register_calls", self.services.register("test_domain", "register_calls",
lambda x: calls.append(1)) lambda x: calls.append(1))
@ -444,28 +394,15 @@ class TestServiceRegistry(unittest.TestCase):
self.services.call('test_domain', 'REGISTER_CALLS', blocking=True)) self.services.call('test_domain', 'REGISTER_CALLS', blocking=True))
self.assertEqual(1, len(calls)) self.assertEqual(1, len(calls))
def test_call_with_blocking_not_done_in_time(self):
"""Test with blocking."""
calls = []
self.services.register("test_domain", "register_calls",
lambda x: calls.append(1))
orig_limit = ha.SERVICE_CALL_LIMIT
ha.SERVICE_CALL_LIMIT = 0.01
self.assertFalse(
self.services.call('test_domain', 'register_calls', blocking=True))
self.assertEqual(0, len(calls))
ha.SERVICE_CALL_LIMIT = orig_limit
def test_call_non_existing_with_blocking(self): def test_call_non_existing_with_blocking(self):
"""Test non-existing with blocking.""" """Test non-existing with blocking."""
self.pool.add_worker() prior = ha.SERVICE_CALL_LIMIT
self.pool.add_worker() try:
orig_limit = ha.SERVICE_CALL_LIMIT
ha.SERVICE_CALL_LIMIT = 0.01 ha.SERVICE_CALL_LIMIT = 0.01
self.assertFalse( assert not self.services.call('test_domain', 'i_do_not_exist',
self.services.call('test_domain', 'i_do_not_exist', blocking=True)) blocking=True)
ha.SERVICE_CALL_LIMIT = orig_limit finally:
ha.SERVICE_CALL_LIMIT = prior
class TestConfig(unittest.TestCase): class TestConfig(unittest.TestCase):

41
tests/test_main.py Normal file
View file

@ -0,0 +1,41 @@
"""Test methods in __main__."""
from unittest.mock import patch, PropertyMock
from homeassistant import __main__ as main
@patch('sys.exit')
def test_validate_python(mock_exit):
"""Test validate Python version method."""
with patch('sys.version_info',
new_callable=PropertyMock(return_value=(2, 7, 8))):
main.validate_python()
assert mock_exit.called is True
mock_exit.reset_mock()
with patch('sys.version_info',
new_callable=PropertyMock(return_value=(3, 2, 0))):
main.validate_python()
assert mock_exit.called is True
mock_exit.reset_mock()
with patch('sys.version_info',
new_callable=PropertyMock(return_value=(3, 4, 1))):
main.validate_python()
assert mock_exit.called is True
mock_exit.reset_mock()
with patch('sys.version_info',
new_callable=PropertyMock(return_value=(3, 4, 2))):
main.validate_python()
assert mock_exit.called is False
mock_exit.reset_mock()
with patch('sys.version_info',
new_callable=PropertyMock(return_value=(3, 5, 1))):
main.validate_python()
assert mock_exit.called is False

View file

@ -1,7 +1,10 @@
"""Test Home Assistant remote methods and classes.""" """Test Home Assistant remote methods and classes."""
# pylint: disable=protected-access,too-many-public-methods # pylint: disable=protected-access,too-many-public-methods
import asyncio
import threading
import time import time
import unittest import unittest
from unittest.mock import patch
import homeassistant.core as ha import homeassistant.core as ha
import homeassistant.bootstrap as bootstrap import homeassistant.bootstrap as bootstrap
@ -52,13 +55,21 @@ def setUpModule(): # pylint: disable=invalid-name
master_api = remote.API("127.0.0.1", API_PASSWORD, MASTER_PORT) master_api = remote.API("127.0.0.1", API_PASSWORD, MASTER_PORT)
# Start slave # Start slave
slave = remote.HomeAssistant(master_api) loop = asyncio.new_event_loop()
# FIXME: should not be a daemon
threading.Thread(name="SlaveThread", daemon=True,
target=loop.run_forever).start()
slave = remote.HomeAssistant(master_api, loop=loop)
slave.config.config_dir = get_test_config_dir() slave.config.config_dir = get_test_config_dir()
slave.config.skip_pip = True
bootstrap.setup_component( bootstrap.setup_component(
slave, http.DOMAIN, slave, http.DOMAIN,
{http.DOMAIN: {http.CONF_API_PASSWORD: API_PASSWORD, {http.DOMAIN: {http.CONF_API_PASSWORD: API_PASSWORD,
http.CONF_SERVER_PORT: SLAVE_PORT}}) http.CONF_SERVER_PORT: SLAVE_PORT}})
with patch.object(ha, 'create_timer', return_value=None):
slave.start() slave.start()
@ -73,8 +84,8 @@ class TestRemoteMethods(unittest.TestCase):
def tearDown(self): def tearDown(self):
"""Stop everything that was started.""" """Stop everything that was started."""
slave.pool.block_till_done() slave.block_till_done()
hass.pool.block_till_done() hass.block_till_done()
def test_validate_api(self): def test_validate_api(self):
"""Test Python API validate_api.""" """Test Python API validate_api."""
@ -111,7 +122,7 @@ class TestRemoteMethods(unittest.TestCase):
hass.bus.listen("test.event_no_data", listener) hass.bus.listen("test.event_no_data", listener)
remote.fire_event(master_api, "test.event_no_data") remote.fire_event(master_api, "test.event_no_data")
hass.pool.block_till_done() hass.block_till_done()
self.assertEqual(1, len(test_value)) self.assertEqual(1, len(test_value))
# Should not trigger any exception # Should not trigger any exception
@ -156,12 +167,12 @@ class TestRemoteMethods(unittest.TestCase):
remote.set_state(master_api, 'test.test', 'set_test_2') remote.set_state(master_api, 'test.test', 'set_test_2')
remote.set_state(master_api, 'test.test', 'set_test_2') remote.set_state(master_api, 'test.test', 'set_test_2')
hass.bus._pool.block_till_done() hass.block_till_done()
self.assertEqual(1, len(events)) self.assertEqual(1, len(events))
remote.set_state( remote.set_state(
master_api, 'test.test', 'set_test_2', force_update=True) master_api, 'test.test', 'set_test_2', force_update=True)
hass.bus._pool.block_till_done() hass.block_till_done()
self.assertEqual(2, len(events)) self.assertEqual(2, len(events))
def test_is_state(self): def test_is_state(self):
@ -197,7 +208,7 @@ class TestRemoteMethods(unittest.TestCase):
remote.call_service(master_api, "test_domain", "test_service") remote.call_service(master_api, "test_domain", "test_service")
hass.pool.block_till_done() hass.block_till_done()
self.assertEqual(1, len(test_value)) self.assertEqual(1, len(test_value))
@ -223,8 +234,8 @@ class TestRemoteClasses(unittest.TestCase):
def tearDown(self): def tearDown(self):
"""Stop everything that was started.""" """Stop everything that was started."""
slave.pool.block_till_done() slave.block_till_done()
hass.pool.block_till_done() hass.block_till_done()
def test_home_assistant_init(self): def test_home_assistant_init(self):
"""Test HomeAssistant init.""" """Test HomeAssistant init."""
@ -248,9 +259,9 @@ class TestRemoteClasses(unittest.TestCase):
slave.states.set("remote.test", "remote.statemachine test") slave.states.set("remote.test", "remote.statemachine test")
# Wait till slave tells master # Wait till slave tells master
slave.pool.block_till_done() slave.block_till_done()
# Wait till master gives updated state # Wait till master gives updated state
hass.pool.block_till_done() hass.block_till_done()
self.assertEqual("remote.statemachine test", self.assertEqual("remote.statemachine test",
slave.states.get("remote.test").state) slave.states.get("remote.test").state)
@ -258,27 +269,27 @@ class TestRemoteClasses(unittest.TestCase):
def test_statemachine_remove_from_master(self): def test_statemachine_remove_from_master(self):
"""Remove statemachine from master.""" """Remove statemachine from master."""
hass.states.set("remote.master_remove", "remove me!") hass.states.set("remote.master_remove", "remove me!")
hass.pool.block_till_done() hass.block_till_done()
slave.pool.block_till_done() slave.block_till_done()
self.assertIn('remote.master_remove', slave.states.entity_ids()) self.assertIn('remote.master_remove', slave.states.entity_ids())
hass.states.remove("remote.master_remove") hass.states.remove("remote.master_remove")
hass.pool.block_till_done() hass.block_till_done()
slave.pool.block_till_done() slave.block_till_done()
self.assertNotIn('remote.master_remove', slave.states.entity_ids()) self.assertNotIn('remote.master_remove', slave.states.entity_ids())
def test_statemachine_remove_from_slave(self): def test_statemachine_remove_from_slave(self):
"""Remove statemachine from slave.""" """Remove statemachine from slave."""
hass.states.set("remote.slave_remove", "remove me!") hass.states.set("remote.slave_remove", "remove me!")
hass.pool.block_till_done() hass.block_till_done()
self.assertIn('remote.slave_remove', slave.states.entity_ids()) self.assertIn('remote.slave_remove', slave.states.entity_ids())
self.assertTrue(slave.states.remove("remote.slave_remove")) self.assertTrue(slave.states.remove("remote.slave_remove"))
slave.pool.block_till_done() slave.block_till_done()
hass.pool.block_till_done() hass.block_till_done()
self.assertNotIn('remote.slave_remove', slave.states.entity_ids()) self.assertNotIn('remote.slave_remove', slave.states.entity_ids())
@ -292,9 +303,9 @@ class TestRemoteClasses(unittest.TestCase):
slave.bus.fire("test.event_no_data") slave.bus.fire("test.event_no_data")
# Wait till slave tells master # Wait till slave tells master
slave.pool.block_till_done() slave.block_till_done()
# Wait till master gives updated event # Wait till master gives updated event
hass.pool.block_till_done() hass.block_till_done()
self.assertEqual(1, len(hass_call)) self.assertEqual(1, len(hass_call))
self.assertEqual(1, len(slave_call)) self.assertEqual(1, len(slave_call))

77
tests/util/test_async.py Normal file
View file

@ -0,0 +1,77 @@
"""Tests for async util methods from Python source."""
import asyncio
from asyncio import test_utils
from homeassistant.util import async as hasync
class RunCoroutineThreadsafeTests(test_utils.TestCase):
"""Test case for asyncio.run_coroutine_threadsafe."""
def setUp(self):
self.loop = asyncio.new_event_loop()
self.set_event_loop(self.loop) # Will cleanup properly
@asyncio.coroutine
def add(self, a, b, fail=False, cancel=False):
"""Wait 0.05 second and return a + b."""
yield from asyncio.sleep(0.05, loop=self.loop)
if fail:
raise RuntimeError("Fail!")
if cancel:
asyncio.tasks.Task.current_task(self.loop).cancel()
yield
return a + b
def target(self, fail=False, cancel=False, timeout=None,
advance_coro=False):
"""Run add coroutine in the event loop."""
coro = self.add(1, 2, fail=fail, cancel=cancel)
future = hasync.run_coroutine_threadsafe(coro, self.loop)
if advance_coro:
# this is for test_run_coroutine_threadsafe_task_factory_exception;
# otherwise it spills errors and breaks **other** unittests, since
# 'target' is interacting with threads.
# With this call, `coro` will be advanced, so that
# CoroWrapper.__del__ won't do anything when asyncio tests run
# in debug mode.
self.loop.call_soon_threadsafe(coro.send, None)
try:
return future.result(timeout)
finally:
future.done() or future.cancel()
def test_run_coroutine_threadsafe(self):
"""Test coroutine submission from a thread to an event loop."""
future = self.loop.run_in_executor(None, self.target)
result = self.loop.run_until_complete(future)
self.assertEqual(result, 3)
def test_run_coroutine_threadsafe_with_exception(self):
"""Test coroutine submission from a thread to an event loop
when an exception is raised."""
future = self.loop.run_in_executor(None, self.target, True)
with self.assertRaises(RuntimeError) as exc_context:
self.loop.run_until_complete(future)
self.assertIn("Fail!", exc_context.exception.args)
def test_run_coroutine_threadsafe_with_timeout(self):
"""Test coroutine submission from a thread to an event loop
when a timeout is raised."""
callback = lambda: self.target(timeout=0) # noqa
future = self.loop.run_in_executor(None, callback)
with self.assertRaises(asyncio.TimeoutError):
self.loop.run_until_complete(future)
test_utils.run_briefly(self.loop)
# Check that there's no pending task (add has been cancelled)
for task in asyncio.Task.all_tasks(self.loop):
self.assertTrue(task.done())
def test_run_coroutine_threadsafe_task_cancelled(self):
"""Test coroutine submission from a tread to an event loop
when the task is cancelled."""
callback = lambda: self.target(cancel=True) # noqa
future = self.loop.run_in_executor(None, callback)
with self.assertRaises(asyncio.CancelledError):
self.loop.run_until_complete(future)