hass-core/tests/test_core.py
Fabian Affolter 1b46ed5045 0.28 (#3288)
* Backend support for importing waypoints from owntracks as HA zones

* Added test for Owntracks waypoints import

* Backend support for importing waypoints from owntracks as HA zones

* Added test for Owntracks waypoints import

* Removed redundant assignment to CONF_WAYPOINT_IMPORT_USER

* Fixed zone test break and code style issues

* Fixed style issues

* Fixed variable scope issues for entities

* Fixed E302

* Do not install pip packages in tests

* EventBus: return function to unlisten

* Convert automation to entities with services

* Refactored zone creation based on code review feedback, enhanced configuration

* Added unit test to enhance waypoint_whitelist coverage

* Fix JSON encoder issue in recorder

* Fix tests docstring

* * Improved zone naming in waypoint import
* Added more test coverage for owntracks and zone

* Back to 0.28.0.dev0

* Code review feedback from @pavoni

* Added bitfield of features for flux_led since we are supporting effects

* Host should be optional for apcupsd component (#3072)

* Use voluptuous for file (#3049)

* Zwave climate Bugfix: if some setpoints have different units, we should fetch the o… (#3078)

* Bugfix: if some setpoints have different units, we should fetch the one that are active.

* Move order of population for first time detection

* Default to config if None unit_of_measurement

* unit fix (#3083)

* humidity slider (#3088)

* If device was off target temp was null. Default to Heating setpoint (#3091)

* Fix linting

* Upgrade pyuserinput to 0.1.11 (#3068)

* Upgrade pyowm to 2.4.0 (#3067)

* improve isfile validation check (#3101)

* Refactor notification titles to allow for them to be None, this also includes a change in Telegram to only include the title if it's present, and to use a Markdown parse mode for messages (#3100)

* Fix broken test

* rfxtrx sensor clean up

* Bitcoin sensor use warning instead of error (#3103)

* Use voluptuous for HDMI CEC & CONF_DEVICES constants (#3107)

* Update voluptuous for nest (#3109)

* Update configuration check
* Extend platform

* Fix for BLE device tracker (#3019)

* Bug fix tracked devices
* Added scan_duration configuration parameter

* fix homematic climate implementation (#3114)

* Allow 'None' MAC to be loaded from known_devices (#3102)

* Use voluptuous for xmpp (#3127)

* Use voluptuous for twitter (#3126)

* Use voluptuous for Fritzbox and DDWRT (#3122)

* Use Voluptuous for BT Home Hub (#3121)

* Use voluptuous for syslog (#3120)

* Use voluptuous for Aruba (#3119)

* Use constants, update configuration check, and ordering (Pilight) (#3118)

* Use contants, update configuration check, and ordering

* Fix pylint issue

* Migrate to voluptuous (#3113)

* Fix typo (#3108)

* Migrate to voluptuous (#3106)

* Update voluptuous (#3104)

* Climate and cover bugfix (#3097)

* Avoid None comparison for zwave cover.

* Just rely on unit from config for unit_of_measurement

* Explicit return None

* Mqtt (#11)

* Explicit return None

* Missing service and wrong service name defined

* Mqtt state was inverted, and never triggering

* Migrate to voluptuous (#3096)

* Migrate to voluptuous (#3084)

* Fixed Homematic cover (#3116)

* Migrate to voluptuous (#3069)

🐬

* Migrate to voluptuous (#3066)

🐬

* snapcast update (#3012)

* snapcast update

* snapcast update

* validate config

* use conf constants

* orvibo updates (#3006)

🐬

* Update frontend

* move units to temperature for climate zwave. wrong state was sent to mqtt cove

* Use voluptuous for instapush (#3132)

* Use voluptuous for Octoprint (#3111)

* Migrate to voluptuous

* Fix pylint issues

* Add missing docstrings (fix PEP257 issues) (#3098)

* Add missing docstrings (fix PEP257 issues)

* Finish sentence

* Updated braviatv's braviarc version to 0.3.4 (#2997)

* Updated braviarc version to 0.3.4

* Updated braviarc version to requirements_all.txt

* Use voluptuous for Acer projector switch (#3077)

🐬

* Use voluptuous for twilio (#3134)

* Use voluptuous for webostv (#3135)

* Use voluptuous for Command line platforms (#2968)

* Migrate to voluptuous

* Fix pylint issues

* Remove FIXME

* Split setup test

* Test with bootstrap

* Remove lon and lat

* Fix pylint issues

* Add coinmarketcap sensor (#3064)

* Migrate to voluptuous (#3142)

🐬

* Back out insteon hub and fan changes (#3062)

* Move details to docs (#3146)

* Update frontend

* Use constants (#3148)

* Update ordering (#3149)

* Migrate to voluptuous (#3092)

* Display the error instead of the traceback (notify.slack) (#3079)

* Display the error instead of the traceback

* Remove name for check

* Automatic ODB device tracker & device tracker attributes (#3035)

* Migrate to voluptuous (#3173)

* Add voluptuous for tomato and SNMP (#3172)

* Improve voluptuous and login errors for Asus device tracker (#3170)

* Add exclude option to nmap device tracker (#2983)

* Add exclude option to nmap device tracker

Adds an optional exclude paramater to nmap device tracker.
Devices specified in the exclude list will never be scanned
by nmap. This can help to reduce log spam.

ex:
```
device_tracker:
  - platform: nmap_tracker
    hosts: 10.0.0.1/24
    home_interval: 1
    interval_seconds: 12
    consider_home: 120
    track_new_devices: yes
    exclude:
      - 10.0.0.2
      - 10.0.0.1
```

* Handle optional exclude

* Style fixed

* Added Xbox Live component (#3013)

* Added Xbox Live component

* Added Xbox Live sensor to coveralls

* Added init success checks

* Added entity id

* Adding link_names to post.message call (#3167)

If you do not turn link_names on, Slack will not highlight @channel and @username messages.

* Allow https (fixes #3150) (#3155)

* Use constants (#3156)

* Bugfix: ctach Runtime errors (#3153)

"RuntimeError: Disable scan failed" has been seen in a live installation

* Migrate to voluptuous (#3166)

🐬

* Migrate to voluptuous (#3164)

🐬

* Migrate to voluptuous (#3163)

🐬

* Migrate to voluptuous (#3162)

🐬 and 🍪 for fixing quotes!

* Exclude www_static from pydocstyle linting (#3175)

🐬

* Migrate to voluptuous (#3174)

* Migrate to voluptuous (#3171)

* Use voluptuous for mFi switch (#3168)

* Migrate to voluptuous

* Take change configuration into account

* Migrate to voluptuous (#3144)

🐬

* Add the occupancy sensor_class (#3176)

Such a complicated PR

* Update frontend

* Use voluptuous for Unifi, Ubus (#3125)

* Using alert with Hue maintains prior state (#3147)

* When using flash with hue, dont change the on/off state of the light so that it will naturally return to its previous state once flash is complete

* ATTR_FLASH not ATTR_EFFECT

* MQTT fan platform (#3095)

* Add fan.mqtt, allow brightness to be passed and mapped to a fan speed for compatibility with emulated_hue

* Pylint/Flake8 fixes

* Remove brightness

* Add more features, like custom oscillation/speed payloads and setting the speed list

* Flake8 fixes

* flake8/pylint fixes

* Use constants

* block fan.mqtt from coverage

* Fix oscillating comment

* Add Sphinx API doc generation (#3029)

* add's sphinx project to docs/ dir
* include core/helpers autodocs for API reference

* Allow reloading automation without restarting HA (#3002)

* Migrate to voluptuous (#3182)

🐬

* Migrate to voluptuous (#3179)

🐬

* Added scale and offset to the Temper component (#2853)

🐬

* Use voluptuous for BT and Owntracks device trackers (#3187)

🐬

* Correct binary_sensor.ecobee docs URL

* Use voluptuous for Hikvisioncam switch (#3184)

* Migrate to voluptuous

* Use vol.Optional

* Use voluptuous for Edimax (#3178)

🐬

* Use voluptuous for Bravia TV (#3165)

🐬

* Added support to 'effect: random' to Osram Lightify lights (#3192)

* Added support to 'effect: random' to Osram Lightify lights

* removed extra line not required

* Use voluptuous for message_bird, sendgrid (#3136)

* Try out the RTD theme

* Doc updates

* Update voluptuous for existing notify platforms (#3133)

* Update voluptuous for exists notify platforms

* fix constants

* Simple trend sensor. (#3073)

* First cut of trend sensor.

* Tidy.

* Migrate to voluptuous (#3193)

* Migrate to voluptuous (#3194)

🐬

* Migrate to voluptuous (#3197)

* Migrate to voluptuous (#3198)

🐬

* Use extend of PLATFORM_SCHEMA (#3199)

* Migrate to voluptuous (#3202)

🐬

* Updated to use the occupancy sensor_class (#3204)

🐬

* Migrate to voluptuous (#3206)

* Migrate to voluptuous (#3207)

* Migrate to voluptuous (#3208)

🐬

* Migrate to voluptuous (#3209)

🐬

* Migrate to voluptuous (#3214)

* Use voluptuous for SqueezeBox (#3212)

* Migrate to voluptuous

* Remove name

* Migrate to voluptuous and upgrade uber_rides to 0.2.5 (#3181)

* Migrate to voluptuous (#3200)

🐬

* Use Voluptuous for Luci and Netgear device trackers (#3123)

* Use Voluptuous for Luci and NEtgear device trackers

* str_schema shortcut

* Undo str_schema

* change update handling with variable for breack CCU2 (#3215)

* Update ordering (#3216)

* Docs update

* Flake8/pylint

* Add new docs requirements

* Update email validation (#3228)

🐬

* Fix email validation (fixes #3138) (#3227)

* Upgrade slacker to 0.9.25 (#3224)

* Upgrade psutil to 4.3.1 (#3223)

* Upgrade gps3 to 0.33.3 (#3222)

* Upgrade Werkzeug to 0.11.11 (#3220)

* Upgrade sendgrid to 3.4.0 (#3226)

* Bluetooth: keep looking for new devices (#3201)

* keep looking for new devices

* Update bluetooth_tracker.py

* change default value for tracking new devices

* remove commented code

* dlink switch added device state attributes and support for legacy firmware (#3211)

* Use voluptuous for free mobile (#3236)

* Use voluptuous for nma (#3241)

* Improve 1-Wire device family detection and error checking. Use volupt… (#3233)

* Improve 1-Wire device family detection and error checking. Use voluptuous

* Fix detection of gpio connected devices

* Replace rollershutter and garage door with cover, add fan (#3242)

* Use voluptuous for Alarm.com (#3229)

* Use voluptuous for gntp (#3237)

* Use voluptuous for pushbullet, pushetta and pushover (#3240)

* Migrate to voluptuous (#3230)

🐬

* Fix mFi sensors in uninitialized state (#3246)

If mFi sensors are identified but not fully assigned they can
have no tag value, and mficlient throws a ValueError to signal this.
This patch handles that case by considering such devices to always
be STATE_OFF.

* Use voluptuous for PulseAudio Loopback (#3160)

* Migrate to voluptuous

* Fix conf var

* Use voluptuous for Verisure (#3169)

* Migrate to voluptuous

* Update type and add missing config variable

* thread safe modbus (#3188)

*  Upgraded fitbit to version 0.2.3 which fixed oauthlib.oauth2.rfc6749.errors.TokenExpiredError: (token_expired) (#3244)

* update ffmpeg version to 0.10 add get image to camera (#3235)

* Migrate to voluptuous (#3234)

* fix bugfix with unique_id (#3217)

* Zwave climate fix and wink cover. (#3205)

* Fixes setpoint get was done outside loop

* zxt_120

* Wink not migrated to cover

* Clarifying debug

* too long line

* Only add 1 device entity

* Owntracks voluptuous fix (#3191)

* Zwave set temperature fix (#3221)

* If device was off set target temp would not work.

* Changed to use a workaround just for Horstmann HRT4-ZW Zwave Thermostat

* Wrong Horseman id

* style changes

* Change PR to suggestion on gitter (#3243)

* Reload groups (#3203)

* Allow reloading groups without restart

* Test to make sure automation listeners are removed.

* Remove unused imports for group tests

* Simplify group config validation

* Add prepare_reload function to entity component

* Migrate group to use entity_component.prepare_reload

* Migrate automation to use entity_component.prepare_reload

* Clean up group.get_entity_ids

* Use cv.boolean for group config validation

* fix remove listener (#3196)

* Add linux battery sensor (#3238)

* protect service data for changes in calls (#3249)

* protect service data for changes in calls

* change handling

* move MappingProxyType to service call

* Fix issue #3250 (#3253)

* Minor Ecobee changes (#3131)

* Update configuration check, ordering, and constants

* Make API key optional

* issue #3250

* Add voluptuous to ecobee (#3257)

* Use constants and update ordering (#3261)

* Add support for complex template structures to data_template (#3255)

* Improve yaml fault tolerance and handle check_config border cases (#3159)

* Use voluptuous for nx584 alarm (#3231)

* Migrate to voluptuous

* Fix pylint issue

* fastdotcom from pypi (#3269)

* Use constants and update ordering (#3268)

🐬

* Use constants and update ordering (#3267)

🐬

* Add additional template for custom date formats (#3262)

I can live with a few visual line breaks 🐬

* Use constants and update ordering (#3266)

* Updated  braviatv's braviarc version to 0.3.5 (#3271)

* Use voluptuous for Device Sun Light Trigger (#3105)

* Migrate to voluptuous

* Use default

* Point to master till archive is back (#3285)

* Pi-Hole statistics sensor (#3158)

* Add Pi-Hole sensor

* Update docstrings and remove print()

* Use None for payload

* Added stuff for support range setting (#3189)

* cleanup Homematic code (#3291)

* cleanup old code

* cleanup round 2

* remove unwanted platforms

* Update frontend

* Hotfix for #3100 (#3302)

* Fix TP-Link Archer C7 long passwords (#3225)

* Fix tplink C7 long passwords

Fixes an issue where passwords longer than 15 chars could not log in to Archer C7 routers.

* Truncate in correct place

* Add comment about TP-Link C7 pass truncation

* Fix lint error

* Truncate comment at 79 chars not 80

* modbus write registers service (#3252)

* Fix bloomsky platform discovery (#3303)

* Remove dev tag
2016-09-10 18:22:58 -07:00

524 lines
17 KiB
Python

"""Test to verify that Home Assistant core works."""
# pylint: disable=protected-access,too-many-public-methods
# pylint: disable=too-few-public-methods
import os
import signal
import unittest
from unittest.mock import patch
import time
import threading
from datetime import datetime, timedelta
import pytz
import homeassistant.core as ha
from homeassistant.exceptions import (
HomeAssistantError, InvalidEntityFormatError)
import homeassistant.util.dt as dt_util
from homeassistant.util.unit_system import (METRIC_SYSTEM)
from homeassistant.const import (
__version__, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP,
EVENT_STATE_CHANGED, ATTR_FRIENDLY_NAME, CONF_UNIT_SYSTEM)
from tests.common import get_test_home_assistant
PST = pytz.timezone('America/Los_Angeles')
class TestMethods(unittest.TestCase):
"""Test the Home Assistant helper methods."""
def test_split_entity_id(self):
"""Test split_entity_id."""
self.assertEqual(['domain', 'object_id'],
ha.split_entity_id('domain.object_id'))
class TestHomeAssistant(unittest.TestCase):
"""Test the Home Assistant core classes."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.states.set("light.Bowl", "on")
self.hass.states.set("switch.AC", "off")
def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started."""
try:
self.hass.stop()
except HomeAssistantError:
# Already stopped after the block till stopped test
pass
def test_start(self):
"""Start the test."""
calls = []
self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START,
lambda event: calls.append(1))
self.hass.start()
self.hass.pool.block_till_done()
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,
lambda event: calls.append(1))
def send_sigterm(length):
"""Send sigterm."""
os.kill(os.getpid(), signal.SIGTERM)
with patch('homeassistant.core.time.sleep', send_sigterm):
self.hass.block_till_stopped()
self.assertEqual(1, len(calls))
class TestEvent(unittest.TestCase):
"""A Test Event class."""
def test_eq(self):
"""Test events."""
now = dt_util.utcnow()
data = {'some': 'attr'}
event1, event2 = [
ha.Event('some_type', data, time_fired=now)
for _ in range(2)
]
self.assertEqual(event1, event2)
def test_repr(self):
"""Test that repr method works."""
self.assertEqual(
"<Event TestEvent[L]>",
str(ha.Event("TestEvent")))
self.assertEqual(
"<Event TestEvent[R]: beer=nice>",
str(ha.Event("TestEvent",
{"beer": "nice"},
ha.EventOrigin.remote)))
def test_as_dict(self):
"""Test as dictionary."""
event_type = 'some_type'
now = dt_util.utcnow()
data = {'some': 'attr'}
event = ha.Event(event_type, data, ha.EventOrigin.local, now)
expected = {
'event_type': event_type,
'data': data,
'origin': 'LOCAL',
'time_fired': now,
}
self.assertEqual(expected, event.as_dict())
class TestEventBus(unittest.TestCase):
"""Test EventBus methods."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.bus = ha.EventBus(ha.create_worker_pool(0))
self.bus.listen('test_event', lambda x: len)
def tearDown(self): # pylint: disable=invalid-name
"""Stop down stuff we started."""
self.bus._pool.stop()
def test_add_remove_listener(self):
"""Test remove_listener method."""
self.bus._pool.add_worker()
old_count = len(self.bus.listeners)
def listener(_): pass
self.bus.listen('test', listener)
self.assertEqual(old_count + 1, len(self.bus.listeners))
# Try deleting a non registered listener, nothing should happen
self.bus._remove_listener('test', lambda x: len)
# Remove listener
self.bus._remove_listener('test', listener)
self.assertEqual(old_count, len(self.bus.listeners))
# Try deleting listener while category doesn't exist either
self.bus._remove_listener('test', listener)
def test_unsubscribe_listener(self):
"""Test unsubscribe listener from returned function."""
self.bus._pool.add_worker()
calls = []
def listener(event):
"""Mock listener."""
calls.append(event)
unsub = self.bus.listen('test', listener)
self.bus.fire('test')
self.bus._pool.block_till_done()
assert len(calls) == 1
unsub()
self.bus.fire('event')
self.bus._pool.block_till_done()
assert len(calls) == 1
def test_listen_once_event(self):
"""Test listen_once_event method."""
runs = []
self.bus.listen_once('test_event', lambda x: runs.append(1))
self.bus.fire('test_event')
# Second time it should not increase runs
self.bus.fire('test_event')
self.bus._pool.add_worker()
self.bus._pool.block_till_done()
self.assertEqual(1, len(runs))
class TestState(unittest.TestCase):
"""Test State methods."""
def test_init(self):
"""Test state.init."""
self.assertRaises(
InvalidEntityFormatError, ha.State,
'invalid_entity_format', 'test_state')
def test_domain(self):
"""Test domain."""
state = ha.State('some_domain.hello', 'world')
self.assertEqual('some_domain', state.domain)
def test_object_id(self):
"""Test object ID."""
state = ha.State('domain.hello', 'world')
self.assertEqual('hello', state.object_id)
def test_name_if_no_friendly_name_attr(self):
"""Test if there is no friendly name."""
state = ha.State('domain.hello_world', 'world')
self.assertEqual('hello world', state.name)
def test_name_if_friendly_name_attr(self):
"""Test if there is a friendly name."""
name = 'Some Unique Name'
state = ha.State('domain.hello_world', 'world',
{ATTR_FRIENDLY_NAME: name})
self.assertEqual(name, state.name)
def test_dict_conversion(self):
"""Test conversion of dict."""
state = ha.State('domain.hello', 'world', {'some': 'attr'})
self.assertEqual(state, ha.State.from_dict(state.as_dict()))
def test_dict_conversion_with_wrong_data(self):
"""Test conversion with wrong data."""
self.assertIsNone(ha.State.from_dict(None))
self.assertIsNone(ha.State.from_dict({'state': 'yes'}))
self.assertIsNone(ha.State.from_dict({'entity_id': 'yes'}))
def test_repr(self):
"""Test state.repr."""
self.assertEqual("<state happy.happy=on @ 1984-12-08T12:00:00+00:00>",
str(ha.State(
"happy.happy", "on",
last_changed=datetime(1984, 12, 8, 12, 0, 0))))
self.assertEqual(
"<state happy.happy=on; brightness=144 @ "
"1984-12-08T12:00:00+00:00>",
str(ha.State("happy.happy", "on", {"brightness": 144},
datetime(1984, 12, 8, 12, 0, 0))))
class TestStateMachine(unittest.TestCase):
"""Test State machine methods."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.pool = ha.create_worker_pool(0)
self.bus = ha.EventBus(self.pool)
self.states = ha.StateMachine(self.bus)
self.states.set("light.Bowl", "on")
self.states.set("switch.AC", "off")
def tearDown(self): # pylint: disable=invalid-name
"""Stop down stuff we started."""
self.pool.stop()
def test_is_state(self):
"""Test is_state method."""
self.assertTrue(self.states.is_state('light.Bowl', 'on'))
self.assertFalse(self.states.is_state('light.Bowl', 'off'))
self.assertFalse(self.states.is_state('light.Non_existing', 'on'))
def test_is_state_attr(self):
"""Test is_state_attr method."""
self.states.set("light.Bowl", "on", {"brightness": 100})
self.assertTrue(
self.states.is_state_attr('light.Bowl', 'brightness', 100))
self.assertFalse(
self.states.is_state_attr('light.Bowl', 'friendly_name', 200))
self.assertFalse(
self.states.is_state_attr('light.Bowl', 'friendly_name', 'Bowl'))
self.assertFalse(
self.states.is_state_attr('light.Non_existing', 'brightness', 100))
def test_entity_ids(self):
"""Test get_entity_ids method."""
ent_ids = self.states.entity_ids()
self.assertEqual(2, len(ent_ids))
self.assertTrue('light.bowl' in ent_ids)
self.assertTrue('switch.ac' in ent_ids)
ent_ids = self.states.entity_ids('light')
self.assertEqual(1, len(ent_ids))
self.assertTrue('light.bowl' in ent_ids)
def test_all(self):
"""Test everything."""
states = sorted(state.entity_id for state in self.states.all())
self.assertEqual(['light.bowl', 'switch.ac'], states)
def test_remove(self):
"""Test remove method."""
self.pool.add_worker()
events = []
self.bus.listen(EVENT_STATE_CHANGED,
lambda event: events.append(event))
self.assertIn('light.bowl', self.states.entity_ids())
self.assertTrue(self.states.remove('light.bowl'))
self.pool.block_till_done()
self.assertNotIn('light.bowl', self.states.entity_ids())
self.assertEqual(1, len(events))
self.assertEqual('light.bowl', events[0].data.get('entity_id'))
self.assertIsNotNone(events[0].data.get('old_state'))
self.assertEqual('light.bowl', events[0].data['old_state'].entity_id)
self.assertIsNone(events[0].data.get('new_state'))
# If it does not exist, we should get False
self.assertFalse(self.states.remove('light.Bowl'))
self.pool.block_till_done()
self.assertEqual(1, len(events))
def test_case_insensitivty(self):
"""Test insensitivty."""
self.pool.add_worker()
runs = []
self.bus.listen(EVENT_STATE_CHANGED, lambda event: runs.append(event))
self.states.set('light.BOWL', 'off')
self.bus._pool.block_till_done()
self.assertTrue(self.states.is_state('light.bowl', 'off'))
self.assertEqual(1, len(runs))
def test_last_changed_not_updated_on_same_state(self):
"""Test to not update the existing, same state."""
state = self.states.get('light.Bowl')
future = dt_util.utcnow() + timedelta(hours=10)
with patch('homeassistant.util.dt.utcnow', return_value=future):
self.states.set("light.Bowl", "on", {'attr': 'triggers_change'})
self.assertEqual(state.last_changed,
self.states.get('light.Bowl').last_changed)
def test_force_update(self):
"""Test force update option."""
self.pool.add_worker()
events = []
self.bus.listen(EVENT_STATE_CHANGED, events.append)
self.states.set('light.bowl', 'on')
self.bus._pool.block_till_done()
self.assertEqual(0, len(events))
self.states.set('light.bowl', 'on', None, True)
self.bus._pool.block_till_done()
self.assertEqual(1, len(events))
class TestServiceCall(unittest.TestCase):
"""Test ServiceCall class."""
def test_repr(self):
"""Test repr method."""
self.assertEqual(
"<ServiceCall homeassistant.start>",
str(ha.ServiceCall('homeassistant', 'start')))
self.assertEqual(
"<ServiceCall homeassistant.start: fast=yes>",
str(ha.ServiceCall('homeassistant', 'start', {"fast": "yes"})))
class TestServiceRegistry(unittest.TestCase):
"""Test ServicerRegistry methods."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.pool = ha.create_worker_pool(0)
self.bus = ha.EventBus(self.pool)
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)
def tearDown(self): # pylint: disable=invalid-name
"""Stop down stuff we started."""
if self.pool.worker_count:
self.pool.stop()
def test_has_service(self):
"""Test has_service method."""
self.assertTrue(
self.services.has_service("tesT_domaiN", "tesT_servicE"))
self.assertFalse(
self.services.has_service("test_domain", "non_existing"))
self.assertFalse(
self.services.has_service("non_existing", "test_service"))
def test_services(self):
"""Test services."""
expected = {
'test_domain': {'test_service': {'description': '', 'fields': {}}}
}
self.assertEqual(expected, self.services.services)
def test_call_with_blocking_done_in_time(self):
"""Test call with blocking."""
self.pool.add_worker()
self.pool.add_worker()
calls = []
self.services.register("test_domain", "register_calls",
lambda x: calls.append(1))
self.assertTrue(
self.services.call('test_domain', 'REGISTER_CALLS', blocking=True))
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):
"""Test non-existing with blocking."""
self.pool.add_worker()
self.pool.add_worker()
orig_limit = ha.SERVICE_CALL_LIMIT
ha.SERVICE_CALL_LIMIT = 0.01
self.assertFalse(
self.services.call('test_domain', 'i_do_not_exist', blocking=True))
ha.SERVICE_CALL_LIMIT = orig_limit
class TestConfig(unittest.TestCase):
"""Test configuration methods."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.config = ha.Config()
self.assertIsNone(self.config.config_dir)
def test_path_with_file(self):
"""Test get_config_path method."""
self.config.config_dir = '/tmp/ha-config'
self.assertEqual("/tmp/ha-config/test.conf",
self.config.path("test.conf"))
def test_path_with_dir_and_file(self):
"""Test get_config_path method."""
self.config.config_dir = '/tmp/ha-config'
self.assertEqual("/tmp/ha-config/dir/test.conf",
self.config.path("dir", "test.conf"))
def test_as_dict(self):
"""Test as dict."""
expected = {
'latitude': None,
'longitude': None,
CONF_UNIT_SYSTEM: METRIC_SYSTEM.as_dict(),
'location_name': None,
'time_zone': 'UTC',
'components': [],
'version': __version__,
}
self.assertEqual(expected, self.config.as_dict())
class TestWorkerPool(unittest.TestCase):
"""Test WorkerPool methods."""
def test_exception_during_job(self):
"""Test exception during a job."""
pool = ha.create_worker_pool(1)
def malicious_job(_):
raise Exception("Test breaking worker pool")
calls = []
def register_call(_):
calls.append(1)
pool.add_job(ha.JobPriority.EVENT_DEFAULT, (malicious_job, None))
pool.add_job(ha.JobPriority.EVENT_DEFAULT, (register_call, None))
pool.block_till_done()
self.assertEqual(1, len(calls))