Consolidate all platforms that have tests (#22109)

* Moved climate components with tests into platform dirs.

* Updated tests from climate component.

* Moved binary_sensor components with tests into platform dirs.

* Updated tests from binary_sensor component.

* Moved calendar components with tests into platform dirs.

* Updated tests from calendar component.

* Moved camera components with tests into platform dirs.

* Updated tests from camera component.

* Moved cover components with tests into platform dirs.

* Updated tests from cover component.

* Moved device_tracker components with tests into platform dirs.

* Updated tests from device_tracker component.

* Moved fan components with tests into platform dirs.

* Updated tests from fan component.

* Moved geo_location components with tests into platform dirs.

* Updated tests from geo_location component.

* Moved image_processing components with tests into platform dirs.

* Updated tests from image_processing component.

* Moved light components with tests into platform dirs.

* Updated tests from light component.

* Moved lock components with tests into platform dirs.

* Moved media_player components with tests into platform dirs.

* Updated tests from media_player component.

* Moved scene components with tests into platform dirs.

* Moved sensor components with tests into platform dirs.

* Updated tests from sensor component.

* Moved switch components with tests into platform dirs.

* Updated tests from sensor component.

* Moved vacuum components with tests into platform dirs.

* Updated tests from vacuum component.

* Moved weather components with tests into platform dirs.

* Fixed __init__.py files

* Fixes for stuff moved as part of this branch.

* Fix stuff needed to merge with balloob's branch.

* Formatting issues.

* Missing __init__.py files.

* Fix-ups

* Fixup

* Regenerated requirements.

* Linting errors fixed.

* Fixed more broken tests.

* Missing init files.

* Fix broken tests.

* More broken tests

* There seems to be a thread race condition.
I suspect the logger stuff is running in another thread, which means waiting until the aio loop is done is missing the log messages.
Used sleep instead because that allows the logger thread to run. I think the api_streams sensor might not be thread safe.

* Disabled tests, will remove sensor in #22147

* Updated coverage and codeowners.
This commit is contained in:
Penny Wood 2019-03-19 14:07:39 +08:00 committed by Paulus Schoutsen
parent 46ece3603f
commit f195ecca4b
486 changed files with 662 additions and 455 deletions

View file

@ -1,91 +0,0 @@
"""The tests for the Aurora sensor platform."""
import re
import unittest
import requests_mock
from homeassistant.components.binary_sensor import aurora
from tests.common import load_fixture, get_test_home_assistant
class TestAuroraSensorSetUp(unittest.TestCase):
"""Test the aurora platform."""
def setUp(self):
"""Initialize values for this testcase class."""
self.hass = get_test_home_assistant()
self.lat = 37.8267
self.lon = -122.423
self.hass.config.latitude = self.lat
self.hass.config.longitude = self.lon
self.entities = []
def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started."""
self.hass.stop()
@requests_mock.Mocker()
def test_setup_and_initial_state(self, mock_req):
"""Test that the component is created and initialized as expected."""
uri = re.compile(
r"http://services\.swpc\.noaa\.gov/text/aurora-nowcast-map\.txt"
)
mock_req.get(uri, text=load_fixture('aurora.txt'))
entities = []
def mock_add_entities(new_entities, update_before_add=False):
"""Mock add entities."""
if update_before_add:
for entity in new_entities:
entity.update()
for entity in new_entities:
entities.append(entity)
config = {
"name": "Test",
"forecast_threshold": 75
}
aurora.setup_platform(self.hass, config, mock_add_entities)
aurora_component = entities[0]
assert len(entities) == 1
assert aurora_component.name == "Test"
assert \
aurora_component.device_state_attributes["visibility_level"] == '0'
assert aurora_component.device_state_attributes["message"] == \
"nothing's out"
assert not aurora_component.is_on
@requests_mock.Mocker()
def test_custom_threshold_works(self, mock_req):
"""Test that the config can take a custom forecast threshold."""
uri = re.compile(
r"http://services\.swpc\.noaa\.gov/text/aurora-nowcast-map\.txt"
)
mock_req.get(uri, text=load_fixture('aurora.txt'))
entities = []
def mock_add_entities(new_entities, update_before_add=False):
"""Mock add entities."""
if update_before_add:
for entity in new_entities:
entity.update()
for entity in new_entities:
entities.append(entity)
config = {
"name": "Test",
"forecast_threshold": 1
}
self.hass.config.longitude = 5
self.hass.config.latitude = 5
aurora.setup_platform(self.hass, config, mock_add_entities)
aurora_component = entities[0]
assert aurora_component.aurora_data.visibility_level == '5'
assert aurora_component.is_on

View file

@ -1,271 +0,0 @@
"""The test for the bayesian sensor platform."""
import unittest
from homeassistant.setup import setup_component
from homeassistant.components.binary_sensor import bayesian
from tests.common import get_test_home_assistant
class TestBayesianBinarySensor(unittest.TestCase):
"""Test the threshold sensor."""
def setup_method(self, method):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def teardown_method(self, method):
"""Stop everything that was started."""
self.hass.stop()
def test_sensor_numeric_state(self):
"""Test sensor on numeric state platform observations."""
config = {
'binary_sensor': {
'platform':
'bayesian',
'name':
'Test_Binary',
'observations': [{
'platform': 'numeric_state',
'entity_id': 'sensor.test_monitored',
'below': 10,
'above': 5,
'prob_given_true': 0.6
}, {
'platform': 'numeric_state',
'entity_id': 'sensor.test_monitored1',
'below': 7,
'above': 5,
'prob_given_true': 0.9,
'prob_given_false': 0.1
}],
'prior':
0.2,
}
}
assert setup_component(self.hass, 'binary_sensor', config)
self.hass.states.set('sensor.test_monitored', 4)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_binary')
assert [] == state.attributes.get('observations')
assert 0.2 == state.attributes.get('probability')
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 6)
self.hass.block_till_done()
self.hass.states.set('sensor.test_monitored', 4)
self.hass.block_till_done()
self.hass.states.set('sensor.test_monitored', 6)
self.hass.states.set('sensor.test_monitored1', 6)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_binary')
assert [{
'prob_false': 0.4,
'prob_true': 0.6
}, {
'prob_false': 0.1,
'prob_true': 0.9
}] == state.attributes.get('observations')
assert round(abs(0.77-state.attributes.get('probability')), 7) == 0
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 6)
self.hass.states.set('sensor.test_monitored1', 0)
self.hass.block_till_done()
self.hass.states.set('sensor.test_monitored', 4)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_binary')
assert 0.2 == state.attributes.get('probability')
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 15)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_binary')
assert state.state == 'off'
def test_sensor_state(self):
"""Test sensor on state platform observations."""
config = {
'binary_sensor': {
'name':
'Test_Binary',
'platform':
'bayesian',
'observations': [{
'platform': 'state',
'entity_id': 'sensor.test_monitored',
'to_state': 'off',
'prob_given_true': 0.8,
'prob_given_false': 0.4
}],
'prior':
0.2,
'probability_threshold':
0.32,
}
}
assert setup_component(self.hass, 'binary_sensor', config)
self.hass.states.set('sensor.test_monitored', 'on')
state = self.hass.states.get('binary_sensor.test_binary')
assert [] == state.attributes.get('observations')
assert 0.2 == state.attributes.get('probability')
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 'off')
self.hass.block_till_done()
self.hass.states.set('sensor.test_monitored', 'on')
self.hass.block_till_done()
self.hass.states.set('sensor.test_monitored', 'off')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_binary')
assert [{
'prob_true': 0.8,
'prob_false': 0.4
}] == state.attributes.get('observations')
assert round(abs(0.33-state.attributes.get('probability')), 7) == 0
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 'off')
self.hass.block_till_done()
self.hass.states.set('sensor.test_monitored', 'on')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_binary')
assert round(abs(0.2-state.attributes.get('probability')), 7) == 0
assert state.state == 'off'
def test_threshold(self):
"""Test sensor on probabilty threshold limits."""
config = {
'binary_sensor': {
'name':
'Test_Binary',
'platform':
'bayesian',
'observations': [{
'platform': 'state',
'entity_id': 'sensor.test_monitored',
'to_state': 'on',
'prob_given_true': 1.0,
}],
'prior':
0.5,
'probability_threshold':
1.0,
}
}
assert setup_component(self.hass, 'binary_sensor', config)
self.hass.states.set('sensor.test_monitored', 'on')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_binary')
assert round(abs(1.0-state.attributes.get('probability')), 7) == 0
assert state.state == 'on'
def test_multiple_observations(self):
"""Test sensor with multiple observations of same entity."""
config = {
'binary_sensor': {
'name':
'Test_Binary',
'platform':
'bayesian',
'observations': [{
'platform': 'state',
'entity_id': 'sensor.test_monitored',
'to_state': 'blue',
'prob_given_true': 0.8,
'prob_given_false': 0.4
}, {
'platform': 'state',
'entity_id': 'sensor.test_monitored',
'to_state': 'red',
'prob_given_true': 0.2,
'prob_given_false': 0.4
}],
'prior':
0.2,
'probability_threshold':
0.32,
}
}
assert setup_component(self.hass, 'binary_sensor', config)
self.hass.states.set('sensor.test_monitored', 'off')
state = self.hass.states.get('binary_sensor.test_binary')
assert [] == state.attributes.get('observations')
assert 0.2 == state.attributes.get('probability')
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 'blue')
self.hass.block_till_done()
self.hass.states.set('sensor.test_monitored', 'off')
self.hass.block_till_done()
self.hass.states.set('sensor.test_monitored', 'blue')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_binary')
assert [{
'prob_true': 0.8,
'prob_false': 0.4
}] == state.attributes.get('observations')
assert round(abs(0.33-state.attributes.get('probability')), 7) == 0
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 'blue')
self.hass.block_till_done()
self.hass.states.set('sensor.test_monitored', 'red')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_binary')
assert round(abs(0.11-state.attributes.get('probability')), 7) == 0
assert state.state == 'off'
def test_probability_updates(self):
"""Test probability update function."""
prob_true = [0.3, 0.6, 0.8]
prob_false = [0.7, 0.4, 0.2]
prior = 0.5
for pt, pf in zip(prob_true, prob_false):
prior = bayesian.update_probability(prior, pt, pf)
assert round(abs(0.720000-prior), 7) == 0
prob_true = [0.8, 0.3, 0.9]
prob_false = [0.6, 0.4, 0.2]
prior = 0.7
for pt, pf in zip(prob_true, prob_false):
prior = bayesian.update_probability(prior, pt, pf)
assert round(abs(0.9130434782608695-prior), 7) == 0

View file

@ -1,63 +0,0 @@
"""The tests for the Command line Binary sensor platform."""
import unittest
from homeassistant.const import (STATE_ON, STATE_OFF)
from homeassistant.components.binary_sensor import command_line
from homeassistant.helpers import template
from tests.common import get_test_home_assistant
class TestCommandSensorBinarySensor(unittest.TestCase):
"""Test the Command line Binary sensor."""
def setUp(self):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self):
"""Stop everything that was started."""
self.hass.stop()
def test_setup(self):
"""Test sensor setup."""
config = {'name': 'Test',
'command': 'echo 1',
'payload_on': '1',
'payload_off': '0',
'command_timeout': 15
}
devices = []
def add_dev_callback(devs, update):
"""Add callback to add devices."""
for dev in devs:
devices.append(dev)
command_line.setup_platform(self.hass, config, add_dev_callback)
assert 1 == len(devices)
entity = devices[0]
entity.update()
assert 'Test' == entity.name
assert STATE_ON == entity.state
def test_template(self):
"""Test setting the state with a template."""
data = command_line.CommandSensorData(self.hass, 'echo 10', 15)
entity = command_line.CommandBinarySensor(
self.hass, data, 'test', None, '1.0', '0',
template.Template('{{ value | multiply(0.1) }}', self.hass))
entity.update()
assert STATE_ON == entity.state
def test_sensor_off(self):
"""Test setting the state with a template."""
data = command_line.CommandSensorData(self.hass, 'echo 0', 15)
entity = command_line.CommandBinarySensor(
self.hass, data, 'test', None, '1', '0', None)
entity.update()
assert STATE_OFF == entity.state

View file

@ -1,215 +0,0 @@
"""The tests for the nx584 sensor platform."""
import requests
import unittest
from unittest import mock
from nx584 import client as nx584_client
from homeassistant.components.binary_sensor import nx584
from homeassistant.setup import setup_component
from tests.common import get_test_home_assistant
import pytest
class StopMe(Exception):
"""Stop helper."""
pass
class TestNX584SensorSetup(unittest.TestCase):
"""Test the NX584 sensor platform."""
def setUp(self):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self._mock_client = mock.patch.object(nx584_client, 'Client')
self._mock_client.start()
self.fake_zones = [
{'name': 'front', 'number': 1},
{'name': 'back', 'number': 2},
{'name': 'inside', 'number': 3},
]
client = nx584_client.Client.return_value
client.list_zones.return_value = self.fake_zones
client.get_version.return_value = '1.1'
def tearDown(self):
"""Stop everything that was started."""
self.hass.stop()
self._mock_client.stop()
@mock.patch('homeassistant.components.binary_sensor.nx584.NX584Watcher')
@mock.patch('homeassistant.components.binary_sensor.nx584.NX584ZoneSensor')
def test_setup_defaults(self, mock_nx, mock_watcher):
"""Test the setup with no configuration."""
add_entities = mock.MagicMock()
config = {
'host': nx584.DEFAULT_HOST,
'port': nx584.DEFAULT_PORT,
'exclude_zones': [],
'zone_types': {},
}
assert nx584.setup_platform(self.hass, config, add_entities)
mock_nx.assert_has_calls(
[mock.call(zone, 'opening') for zone in self.fake_zones])
assert add_entities.called
assert nx584_client.Client.call_count == 1
assert nx584_client.Client.call_args == \
mock.call('http://localhost:5007')
@mock.patch('homeassistant.components.binary_sensor.nx584.NX584Watcher')
@mock.patch('homeassistant.components.binary_sensor.nx584.NX584ZoneSensor')
def test_setup_full_config(self, mock_nx, mock_watcher):
"""Test the setup with full configuration."""
config = {
'host': 'foo',
'port': 123,
'exclude_zones': [2],
'zone_types': {3: 'motion'},
}
add_entities = mock.MagicMock()
assert nx584.setup_platform(self.hass, config, add_entities)
mock_nx.assert_has_calls([
mock.call(self.fake_zones[0], 'opening'),
mock.call(self.fake_zones[2], 'motion'),
])
assert add_entities.called
assert nx584_client.Client.call_count == 1
assert nx584_client.Client.call_args == mock.call('http://foo:123')
assert mock_watcher.called
def _test_assert_graceful_fail(self, config):
"""Test the failing."""
assert not setup_component(
self.hass, 'binary_sensor.nx584', config)
def test_setup_bad_config(self):
"""Test the setup with bad configuration."""
bad_configs = [
{'exclude_zones': ['a']},
{'zone_types': {'a': 'b'}},
{'zone_types': {1: 'notatype'}},
{'zone_types': {'notazone': 'motion'}},
]
for config in bad_configs:
self._test_assert_graceful_fail(config)
def test_setup_connect_failed(self):
"""Test the setup with connection failure."""
nx584_client.Client.return_value.list_zones.side_effect = \
requests.exceptions.ConnectionError
self._test_assert_graceful_fail({})
def test_setup_no_partitions(self):
"""Test the setup with connection failure."""
nx584_client.Client.return_value.list_zones.side_effect = \
IndexError
self._test_assert_graceful_fail({})
def test_setup_version_too_old(self):
"""Test if version is too old."""
nx584_client.Client.return_value.get_version.return_value = '1.0'
self._test_assert_graceful_fail({})
def test_setup_no_zones(self):
"""Test the setup with no zones."""
nx584_client.Client.return_value.list_zones.return_value = []
add_entities = mock.MagicMock()
assert nx584.setup_platform(self.hass, {}, add_entities)
assert not add_entities.called
class TestNX584ZoneSensor(unittest.TestCase):
"""Test for the NX584 zone sensor."""
def test_sensor_normal(self):
"""Test the sensor."""
zone = {'number': 1, 'name': 'foo', 'state': True}
sensor = nx584.NX584ZoneSensor(zone, 'motion')
assert 'foo' == sensor.name
assert not sensor.should_poll
assert sensor.is_on
zone['state'] = False
assert not sensor.is_on
class TestNX584Watcher(unittest.TestCase):
"""Test the NX584 watcher."""
@mock.patch.object(nx584.NX584ZoneSensor, 'schedule_update_ha_state')
def test_process_zone_event(self, mock_update):
"""Test the processing of zone events."""
zone1 = {'number': 1, 'name': 'foo', 'state': True}
zone2 = {'number': 2, 'name': 'bar', 'state': True}
zones = {
1: nx584.NX584ZoneSensor(zone1, 'motion'),
2: nx584.NX584ZoneSensor(zone2, 'motion'),
}
watcher = nx584.NX584Watcher(None, zones)
watcher._process_zone_event({'zone': 1, 'zone_state': False})
assert not zone1['state']
assert 1 == mock_update.call_count
@mock.patch.object(nx584.NX584ZoneSensor, 'schedule_update_ha_state')
def test_process_zone_event_missing_zone(self, mock_update):
"""Test the processing of zone events with missing zones."""
watcher = nx584.NX584Watcher(None, {})
watcher._process_zone_event({'zone': 1, 'zone_state': False})
assert not mock_update.called
def test_run_with_zone_events(self):
"""Test the zone events."""
empty_me = [1, 2]
def fake_get_events():
"""Return nothing twice, then some events."""
if empty_me:
empty_me.pop()
else:
return fake_events
client = mock.MagicMock()
fake_events = [
{'zone': 1, 'zone_state': True, 'type': 'zone_status'},
{'zone': 2, 'foo': False},
]
client.get_events.side_effect = fake_get_events
watcher = nx584.NX584Watcher(client, {})
@mock.patch.object(watcher, '_process_zone_event')
def run(fake_process):
"""Run a fake process."""
fake_process.side_effect = StopMe
with pytest.raises(StopMe):
watcher._run()
assert fake_process.call_count == 1
assert fake_process.call_args == mock.call(fake_events[0])
run()
assert 3 == client.get_events.call_count
@mock.patch('time.sleep')
def test_run_retries_failures(self, mock_sleep):
"""Test the retries with failures."""
empty_me = [1, 2]
def fake_run():
"""Fake runner."""
if empty_me:
empty_me.pop()
raise requests.exceptions.ConnectionError()
else:
raise StopMe()
watcher = nx584.NX584Watcher(None, {})
with mock.patch.object(watcher, '_run') as mock_inner:
mock_inner.side_effect = fake_run
with pytest.raises(StopMe):
watcher.run()
assert 3 == mock_inner.call_count
mock_sleep.assert_has_calls([mock.call(10), mock.call(10)])

View file

@ -1,51 +0,0 @@
"""The test for the Random binary sensor platform."""
import unittest
from unittest.mock import patch
from homeassistant.setup import setup_component
from tests.common import get_test_home_assistant
class TestRandomSensor(unittest.TestCase):
"""Test the Random binary sensor."""
def setup_method(self, method):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def teardown_method(self, method):
"""Stop everything that was started."""
self.hass.stop()
@patch('random.getrandbits', return_value=1)
def test_random_binary_sensor_on(self, mocked):
"""Test the Random binary sensor."""
config = {
'binary_sensor': {
'platform': 'random',
'name': 'test',
}
}
assert setup_component(self.hass, 'binary_sensor', config)
state = self.hass.states.get('binary_sensor.test')
assert state.state == 'on'
@patch('random.getrandbits', return_value=False)
def test_random_binary_sensor_off(self, mocked):
"""Test the Random binary sensor."""
config = {
'binary_sensor': {
'platform': 'random',
'name': 'test',
}
}
assert setup_component(self.hass, 'binary_sensor', config)
state = self.hass.states.get('binary_sensor.test')
assert state.state == 'off'

View file

@ -1,206 +0,0 @@
"""The tests for the REST binary sensor platform."""
import unittest
from pytest import raises
from unittest.mock import patch, Mock
import requests
from requests.exceptions import Timeout, MissingSchema
import requests_mock
from homeassistant.exceptions import PlatformNotReady
from homeassistant.setup import setup_component
import homeassistant.components.binary_sensor as binary_sensor
import homeassistant.components.binary_sensor.rest as rest
from homeassistant.const import STATE_ON, STATE_OFF
from homeassistant.helpers import template
from tests.common import get_test_home_assistant, assert_setup_component
import pytest
class TestRestBinarySensorSetup(unittest.TestCase):
"""Tests for setting up the REST binary sensor platform."""
DEVICES = []
def add_devices(self, devices, update_before_add=False):
"""Mock add devices."""
for device in devices:
self.DEVICES.append(device)
def setUp(self):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
# Reset for this test.
self.DEVICES = []
def tearDown(self):
"""Stop everything that was started."""
self.hass.stop()
def test_setup_missing_config(self):
"""Test setup with configuration missing required entries."""
with assert_setup_component(0):
assert setup_component(self.hass, binary_sensor.DOMAIN, {
'binary_sensor': {'platform': 'rest'}})
def test_setup_missing_schema(self):
"""Test setup with resource missing schema."""
with pytest.raises(MissingSchema):
rest.setup_platform(self.hass, {
'platform': 'rest',
'resource': 'localhost',
'method': 'GET'
}, None)
@patch('requests.Session.send',
side_effect=requests.exceptions.ConnectionError())
def test_setup_failed_connect(self, mock_req):
"""Test setup when connection error occurs."""
with raises(PlatformNotReady):
rest.setup_platform(self.hass, {
'platform': 'rest',
'resource': 'http://localhost',
}, self.add_devices, None)
assert len(self.DEVICES) == 0
@patch('requests.Session.send', side_effect=Timeout())
def test_setup_timeout(self, mock_req):
"""Test setup when connection timeout occurs."""
with raises(PlatformNotReady):
rest.setup_platform(self.hass, {
'platform': 'rest',
'resource': 'http://localhost',
}, self.add_devices, None)
assert len(self.DEVICES) == 0
@requests_mock.Mocker()
def test_setup_minimum(self, mock_req):
"""Test setup with minimum configuration."""
mock_req.get('http://localhost', status_code=200)
with assert_setup_component(1, 'binary_sensor'):
assert setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'rest',
'resource': 'http://localhost'
}
})
assert 1 == mock_req.call_count
@requests_mock.Mocker()
def test_setup_get(self, mock_req):
"""Test setup with valid configuration."""
mock_req.get('http://localhost', status_code=200)
with assert_setup_component(1, 'binary_sensor'):
assert setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'rest',
'resource': 'http://localhost',
'method': 'GET',
'value_template': '{{ value_json.key }}',
'name': 'foo',
'verify_ssl': 'true',
'authentication': 'basic',
'username': 'my username',
'password': 'my password',
'headers': {'Accept': 'application/json'}
}
})
assert 1 == mock_req.call_count
@requests_mock.Mocker()
def test_setup_post(self, mock_req):
"""Test setup with valid configuration."""
mock_req.post('http://localhost', status_code=200)
with assert_setup_component(1, 'binary_sensor'):
assert setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'rest',
'resource': 'http://localhost',
'method': 'POST',
'value_template': '{{ value_json.key }}',
'payload': '{ "device": "toaster"}',
'name': 'foo',
'verify_ssl': 'true',
'authentication': 'basic',
'username': 'my username',
'password': 'my password',
'headers': {'Accept': 'application/json'}
}
})
assert 1 == mock_req.call_count
class TestRestBinarySensor(unittest.TestCase):
"""Tests for REST binary sensor platform."""
def setUp(self):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.rest = Mock('RestData')
self.rest.update = Mock('RestData.update',
side_effect=self.update_side_effect(
'{ "key": false }'))
self.name = 'foo'
self.device_class = 'light'
self.value_template = \
template.Template('{{ value_json.key }}', self.hass)
self.binary_sensor = rest.RestBinarySensor(
self.hass, self.rest, self.name, self.device_class,
self.value_template)
def tearDown(self):
"""Stop everything that was started."""
self.hass.stop()
def update_side_effect(self, data):
"""Side effect function for mocking RestData.update()."""
self.rest.data = data
def test_name(self):
"""Test the name."""
assert self.name == self.binary_sensor.name
def test_device_class(self):
"""Test the device class."""
assert self.device_class == self.binary_sensor.device_class
def test_initial_state(self):
"""Test the initial state."""
self.binary_sensor.update()
assert STATE_OFF == self.binary_sensor.state
def test_update_when_value_is_none(self):
"""Test state gets updated to unknown when sensor returns no data."""
self.rest.update = Mock(
'RestData.update',
side_effect=self.update_side_effect(None))
self.binary_sensor.update()
assert not self.binary_sensor.available
def test_update_when_value_changed(self):
"""Test state gets updated when sensor returns a new status."""
self.rest.update = Mock('rest.RestData.update',
side_effect=self.update_side_effect(
'{ "key": true }'))
self.binary_sensor.update()
assert STATE_ON == self.binary_sensor.state
assert self.binary_sensor.available
def test_update_when_failed_request(self):
"""Test state gets updated when sensor returns a new status."""
self.rest.update = Mock('rest.RestData.update',
side_effect=self.update_side_effect(None))
self.binary_sensor.update()
assert not self.binary_sensor.available
def test_update_with_no_template(self):
"""Test update when there is no value template."""
self.rest.update = Mock('rest.RestData.update',
side_effect=self.update_side_effect('true'))
self.binary_sensor = rest.RestBinarySensor(
self.hass, self.rest, self.name, self.device_class, None)
self.binary_sensor.update()
assert STATE_ON == self.binary_sensor.state
assert self.binary_sensor.available

View file

@ -1,178 +0,0 @@
"""
Test for RFlink sensor components.
Test setup of rflink sensor component/platform. Verify manual and
automatic sensor creation.
"""
from datetime import timedelta
from unittest.mock import patch
from homeassistant.components.rflink import (
CONF_RECONNECT_INTERVAL)
import homeassistant.core as ha
from homeassistant.const import (
EVENT_STATE_CHANGED, STATE_ON, STATE_OFF, STATE_UNAVAILABLE)
import homeassistant.util.dt as dt_util
from tests.common import async_fire_time_changed
from tests.components.rflink.test_init import mock_rflink
DOMAIN = 'binary_sensor'
CONFIG = {
'rflink': {
'port': '/dev/ttyABC0',
'ignore_devices': ['ignore_wildcard_*', 'ignore_sensor'],
},
DOMAIN: {
'platform': 'rflink',
'devices': {
'test': {
'name': 'test',
'device_class': 'door',
},
'test2': {
'name': 'test2',
'device_class': 'motion',
'off_delay': 30,
'force_update': True,
},
},
},
}
async def test_default_setup(hass, monkeypatch):
"""Test all basic functionality of the rflink sensor component."""
# setup mocking rflink module
event_callback, create, _, _ = await mock_rflink(
hass, CONFIG, DOMAIN, monkeypatch)
# make sure arguments are passed
assert create.call_args_list[0][1]['ignore']
# test default state of sensor loaded from config
config_sensor = hass.states.get('binary_sensor.test')
assert config_sensor
assert config_sensor.state == STATE_OFF
assert config_sensor.attributes['device_class'] == 'door'
# test event for config sensor
event_callback({
'id': 'test',
'command': 'on',
})
await hass.async_block_till_done()
assert hass.states.get('binary_sensor.test').state == STATE_ON
# test event for config sensor
event_callback({
'id': 'test',
'command': 'off',
})
await hass.async_block_till_done()
assert hass.states.get('binary_sensor.test').state == STATE_OFF
async def test_entity_availability(hass, monkeypatch):
"""If Rflink device is disconnected, entities should become unavailable."""
# Make sure Rflink mock does not 'recover' to quickly from the
# disconnect or else the unavailability cannot be measured
config = CONFIG
failures = [True, True]
config[CONF_RECONNECT_INTERVAL] = 60
# Create platform and entities
_, _, _, disconnect_callback = await mock_rflink(
hass, config, DOMAIN, monkeypatch, failures=failures)
# Entities are available by default
assert hass.states.get('binary_sensor.test').state == STATE_OFF
# Mock a disconnect of the Rflink device
disconnect_callback()
# Wait for dispatch events to propagate
await hass.async_block_till_done()
# Entity should be unavailable
assert hass.states.get('binary_sensor.test').state == STATE_UNAVAILABLE
# Reconnect the Rflink device
disconnect_callback()
# Wait for dispatch events to propagate
await hass.async_block_till_done()
# Entities should be available again
assert hass.states.get('binary_sensor.test').state == STATE_OFF
async def test_off_delay(hass, monkeypatch):
"""Test off_delay option."""
# setup mocking rflink module
event_callback, create, _, _ = await mock_rflink(
hass, CONFIG, DOMAIN, monkeypatch)
# make sure arguments are passed
assert create.call_args_list[0][1]['ignore']
events = []
on_event = {
'id': 'test2',
'command': 'on',
}
@ha.callback
def callback(event):
"""Verify event got called."""
events.append(event)
hass.bus.async_listen(EVENT_STATE_CHANGED, callback)
now = dt_util.utcnow()
# fake time and turn on sensor
future = now + timedelta(seconds=0)
with patch(('homeassistant.helpers.event.'
'dt_util.utcnow'), return_value=future):
async_fire_time_changed(hass, future)
event_callback(on_event)
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.test2')
assert state.state == STATE_ON
assert len(events) == 1
# fake time and turn on sensor again
future = now + timedelta(seconds=15)
with patch(('homeassistant.helpers.event.'
'dt_util.utcnow'), return_value=future):
async_fire_time_changed(hass, future)
event_callback(on_event)
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.test2')
assert state.state == STATE_ON
assert len(events) == 2
# fake time and verify sensor still on (de-bounce)
future = now + timedelta(seconds=35)
with patch(('homeassistant.helpers.event.'
'dt_util.utcnow'), return_value=future):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.test2')
assert state.state == STATE_ON
assert len(events) == 2
# fake time and verify sensor is off
future = now + timedelta(seconds=45)
with patch(('homeassistant.helpers.event.'
'dt_util.utcnow'), return_value=future):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.test2')
assert state.state == STATE_OFF
assert len(events) == 3

View file

@ -1,76 +0,0 @@
"""The tests for the Ring binary sensor platform."""
import os
import unittest
import requests_mock
from homeassistant.components.binary_sensor import ring
from homeassistant.components import ring as base_ring
from tests.components.ring.test_init import ATTRIBUTION, VALID_CONFIG
from tests.common import (
get_test_config_dir, get_test_home_assistant, load_fixture)
class TestRingBinarySensorSetup(unittest.TestCase):
"""Test the Ring Binary Sensor platform."""
DEVICES = []
def add_entities(self, devices, action):
"""Mock add devices."""
for device in devices:
self.DEVICES.append(device)
def cleanup(self):
"""Cleanup any data created from the tests."""
if os.path.isfile(self.cache):
os.remove(self.cache)
def setUp(self):
"""Initialize values for this testcase class."""
self.hass = get_test_home_assistant()
self.cache = get_test_config_dir(base_ring.DEFAULT_CACHEDB)
self.config = {
'username': 'foo',
'password': 'bar',
'monitored_conditions': ['ding', 'motion'],
}
def tearDown(self):
"""Stop everything that was started."""
self.hass.stop()
self.cleanup()
@requests_mock.Mocker()
def test_binary_sensor(self, mock):
"""Test the Ring sensor class and methods."""
mock.post('https://oauth.ring.com/oauth/token',
text=load_fixture('ring_oauth.json'))
mock.post('https://api.ring.com/clients_api/session',
text=load_fixture('ring_session.json'))
mock.get('https://api.ring.com/clients_api/ring_devices',
text=load_fixture('ring_devices.json'))
mock.get('https://api.ring.com/clients_api/dings/active',
text=load_fixture('ring_ding_active.json'))
mock.get('https://api.ring.com/clients_api/doorbots/987652/health',
text=load_fixture('ring_doorboot_health_attrs.json'))
base_ring.setup(self.hass, VALID_CONFIG)
ring.setup_platform(self.hass,
self.config,
self.add_entities,
None)
for device in self.DEVICES:
device.update()
if device.name == 'Front Door Ding':
assert 'on' == device.state
assert 'America/New_York' == \
device.device_state_attributes['timezone']
elif device.name == 'Front Door Motion':
assert 'off' == device.state
assert 'motion' == device.device_class
assert device.entity_picture is None
assert ATTRIBUTION == \
device.device_state_attributes['attribution']

View file

@ -1,58 +0,0 @@
"""The tests for SleepIQ binary sensor platform."""
import unittest
from unittest.mock import MagicMock
import requests_mock
from homeassistant.setup import setup_component
from homeassistant.components.binary_sensor import sleepiq
from tests.components.sleepiq.test_init import mock_responses
from tests.common import get_test_home_assistant
class TestSleepIQBinarySensorSetup(unittest.TestCase):
"""Tests the SleepIQ Binary Sensor platform."""
DEVICES = []
def add_entities(self, devices):
"""Mock add devices."""
for device in devices:
self.DEVICES.append(device)
def setUp(self):
"""Initialize values for this testcase class."""
self.hass = get_test_home_assistant()
self.username = 'foo'
self.password = 'bar'
self.config = {
'username': self.username,
'password': self.password,
}
def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started."""
self.hass.stop()
@requests_mock.Mocker()
def test_setup(self, mock):
"""Test for successfully setting up the SleepIQ platform."""
mock_responses(mock)
setup_component(self.hass, 'sleepiq', {
'sleepiq': self.config})
sleepiq.setup_platform(self.hass,
self.config,
self.add_entities,
MagicMock())
assert 2 == len(self.DEVICES)
left_side = self.DEVICES[1]
assert 'SleepNumber ILE Test1 Is In Bed' == left_side.name
assert 'on' == left_side.state
right_side = self.DEVICES[0]
assert 'SleepNumber ILE Test2 Is In Bed' == right_side.name
assert 'off' == right_side.state

View file

@ -1,65 +0,0 @@
"""The tests for the TCP binary sensor platform."""
import unittest
from unittest.mock import patch, Mock
from homeassistant.setup import setup_component
from homeassistant.components.binary_sensor import tcp as bin_tcp
from homeassistant.components.sensor import tcp
from tests.common import (get_test_home_assistant, assert_setup_component)
from tests.components.sensor import test_tcp
class TestTCPBinarySensor(unittest.TestCase):
"""Test the TCP Binary Sensor."""
def setup_method(self, method):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def teardown_method(self, method):
"""Stop down everything that was started."""
self.hass.stop()
def test_setup_platform_valid_config(self):
"""Check a valid configuration."""
with assert_setup_component(0, 'binary_sensor'):
assert setup_component(
self.hass, 'binary_sensor', test_tcp.TEST_CONFIG)
def test_setup_platform_invalid_config(self):
"""Check the invalid configuration."""
with assert_setup_component(0):
assert setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'tcp',
'porrt': 1234,
}
})
@patch('homeassistant.components.sensor.tcp.TcpSensor.update')
def test_setup_platform_devices(self, mock_update):
"""Check the supplied config and call add_entities with sensor."""
add_entities = Mock()
ret = bin_tcp.setup_platform(None, test_tcp.TEST_CONFIG, add_entities)
assert ret is None
assert add_entities.called
assert isinstance(
add_entities.call_args[0][0][0], bin_tcp.TcpBinarySensor)
@patch('homeassistant.components.sensor.tcp.TcpSensor.update')
def test_is_on_true(self, mock_update):
"""Check the return that _state is value_on."""
sensor = bin_tcp.TcpBinarySensor(
self.hass, test_tcp.TEST_CONFIG['sensor'])
sensor._state = test_tcp.TEST_CONFIG['sensor'][tcp.CONF_VALUE_ON]
print(sensor._state)
assert sensor.is_on
@patch('homeassistant.components.sensor.tcp.TcpSensor.update')
def test_is_on_false(self, mock_update):
"""Check the return that _state is not the same as value_on."""
sensor = bin_tcp.TcpBinarySensor(
self.hass, test_tcp.TEST_CONFIG['sensor'])
sensor._state = '{} abc'.format(
test_tcp.TEST_CONFIG['sensor'][tcp.CONF_VALUE_ON])
assert not sensor.is_on

View file

@ -1,436 +0,0 @@
"""The tests for the Template Binary sensor platform."""
from datetime import timedelta
import unittest
from unittest import mock
from homeassistant.const import MATCH_ALL, EVENT_HOMEASSISTANT_START
from homeassistant import setup
from homeassistant.components.binary_sensor import template
from homeassistant.exceptions import TemplateError
from homeassistant.helpers import template as template_hlpr
from homeassistant.util.async_ import run_callback_threadsafe
import homeassistant.util.dt as dt_util
from tests.common import (
get_test_home_assistant, assert_setup_component, async_fire_time_changed)
class TestBinarySensorTemplate(unittest.TestCase):
"""Test for Binary sensor template platform."""
hass = None
# pylint: disable=invalid-name
def setup_method(self, method):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def teardown_method(self, method):
"""Stop everything that was started."""
self.hass.stop()
def test_setup(self):
"""Test the setup."""
config = {
'binary_sensor': {
'platform': 'template',
'sensors': {
'test': {
'friendly_name': 'virtual thingy',
'value_template': '{{ foo }}',
'device_class': 'motion',
},
},
},
}
with assert_setup_component(1):
assert setup.setup_component(
self.hass, 'binary_sensor', config)
def test_setup_no_sensors(self):
"""Test setup with no sensors."""
with assert_setup_component(0):
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'template'
}
})
def test_setup_invalid_device(self):
"""Test the setup with invalid devices."""
with assert_setup_component(0):
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'template',
'sensors': {
'foo bar': {},
},
}
})
def test_setup_invalid_device_class(self):
"""Test setup with invalid sensor class."""
with assert_setup_component(0):
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'template',
'sensors': {
'test': {
'value_template': '{{ foo }}',
'device_class': 'foobarnotreal',
},
},
}
})
def test_setup_invalid_missing_template(self):
"""Test setup with invalid and missing template."""
with assert_setup_component(0):
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'template',
'sensors': {
'test': {
'device_class': 'motion',
},
}
}
})
def test_icon_template(self):
"""Test icon template."""
with assert_setup_component(1):
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'template',
'sensors': {
'test_template_sensor': {
'value_template': "{{ states.sensor.xyz.state }}",
'icon_template':
"{% if "
"states.binary_sensor.test_state.state == "
"'Works' %}"
"mdi:check"
"{% endif %}"
}
}
}
})
self.hass.start()
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_template_sensor')
assert state.attributes.get('icon') == ''
self.hass.states.set('binary_sensor.test_state', 'Works')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_template_sensor')
assert state.attributes['icon'] == 'mdi:check'
def test_entity_picture_template(self):
"""Test entity_picture template."""
with assert_setup_component(1):
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'template',
'sensors': {
'test_template_sensor': {
'value_template': "{{ states.sensor.xyz.state }}",
'entity_picture_template':
"{% if "
"states.binary_sensor.test_state.state == "
"'Works' %}"
"/local/sensor.png"
"{% endif %}"
}
}
}
})
self.hass.start()
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_template_sensor')
assert state.attributes.get('entity_picture') == ''
self.hass.states.set('binary_sensor.test_state', 'Works')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_template_sensor')
assert state.attributes['entity_picture'] == '/local/sensor.png'
@mock.patch('homeassistant.components.binary_sensor.template.'
'BinarySensorTemplate._async_render')
def test_match_all(self, _async_render):
"""Test MATCH_ALL in template."""
with assert_setup_component(1):
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'template',
'sensors': {
'match_all_template_sensor': {
'value_template': "{{ 42 }}",
},
}
}
})
self.hass.start()
self.hass.block_till_done()
init_calls = len(_async_render.mock_calls)
self.hass.states.set('sensor.any_state', 'update')
self.hass.block_till_done()
assert len(_async_render.mock_calls) == init_calls
def test_attributes(self):
"""Test the attributes."""
vs = run_callback_threadsafe(
self.hass.loop, template.BinarySensorTemplate,
self.hass, 'parent', 'Parent', 'motion',
template_hlpr.Template('{{ 1 > 1 }}', self.hass),
None, None, MATCH_ALL, None, None
).result()
assert not vs.should_poll
assert 'motion' == vs.device_class
assert 'Parent' == vs.name
run_callback_threadsafe(self.hass.loop, vs.async_check_state).result()
assert not vs.is_on
# pylint: disable=protected-access
vs._template = template_hlpr.Template("{{ 2 > 1 }}", self.hass)
run_callback_threadsafe(self.hass.loop, vs.async_check_state).result()
assert vs.is_on
def test_event(self):
"""Test the event."""
config = {
'binary_sensor': {
'platform': 'template',
'sensors': {
'test': {
'friendly_name': 'virtual thingy',
'value_template':
"{{ states.sensor.test_state.state == 'on' }}",
'device_class': 'motion',
},
},
},
}
with assert_setup_component(1):
assert setup.setup_component(
self.hass, 'binary_sensor', config)
self.hass.start()
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test')
assert state.state == 'off'
self.hass.states.set('sensor.test_state', 'on')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test')
assert state.state == 'on'
@mock.patch('homeassistant.helpers.template.Template.render')
def test_update_template_error(self, mock_render):
"""Test the template update error."""
vs = run_callback_threadsafe(
self.hass.loop, template.BinarySensorTemplate,
self.hass, 'parent', 'Parent', 'motion',
template_hlpr.Template('{{ 1 > 1 }}', self.hass),
None, None, MATCH_ALL, None, None
).result()
mock_render.side_effect = TemplateError('foo')
run_callback_threadsafe(self.hass.loop, vs.async_check_state).result()
mock_render.side_effect = TemplateError(
"UndefinedError: 'None' has no attribute")
run_callback_threadsafe(self.hass.loop, vs.async_check_state).result()
async def test_template_delay_on(hass):
"""Test binary sensor template delay on."""
config = {
'binary_sensor': {
'platform': 'template',
'sensors': {
'test': {
'friendly_name': 'virtual thingy',
'value_template':
"{{ states.sensor.test_state.state == 'on' }}",
'device_class': 'motion',
'delay_on': 5
},
},
},
}
await setup.async_setup_component(hass, 'binary_sensor', config)
await hass.async_start()
hass.states.async_set('sensor.test_state', 'on')
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.test')
assert state.state == 'off'
future = dt_util.utcnow() + timedelta(seconds=5)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.test')
assert state.state == 'on'
# check with time changes
hass.states.async_set('sensor.test_state', 'off')
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.test')
assert state.state == 'off'
hass.states.async_set('sensor.test_state', 'on')
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.test')
assert state.state == 'off'
hass.states.async_set('sensor.test_state', 'off')
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.test')
assert state.state == 'off'
future = dt_util.utcnow() + timedelta(seconds=5)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.test')
assert state.state == 'off'
async def test_template_delay_off(hass):
"""Test binary sensor template delay off."""
config = {
'binary_sensor': {
'platform': 'template',
'sensors': {
'test': {
'friendly_name': 'virtual thingy',
'value_template':
"{{ states.sensor.test_state.state == 'on' }}",
'device_class': 'motion',
'delay_off': 5
},
},
},
}
hass.states.async_set('sensor.test_state', 'on')
await setup.async_setup_component(hass, 'binary_sensor', config)
await hass.async_start()
hass.states.async_set('sensor.test_state', 'off')
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.test')
assert state.state == 'on'
future = dt_util.utcnow() + timedelta(seconds=5)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.test')
assert state.state == 'off'
# check with time changes
hass.states.async_set('sensor.test_state', 'on')
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.test')
assert state.state == 'on'
hass.states.async_set('sensor.test_state', 'off')
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.test')
assert state.state == 'on'
hass.states.async_set('sensor.test_state', 'on')
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.test')
assert state.state == 'on'
future = dt_util.utcnow() + timedelta(seconds=5)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.test')
assert state.state == 'on'
async def test_no_update_template_match_all(hass, caplog):
"""Test that we do not update sensors that match on all."""
hass.states.async_set('binary_sensor.test_sensor', 'true')
await setup.async_setup_component(hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'template',
'sensors': {
'all_state': {
'value_template': '{{ "true" }}',
},
'all_icon': {
'value_template':
'{{ states.binary_sensor.test_sensor.state }}',
'icon_template': '{{ 1 + 1 }}',
},
'all_entity_picture': {
'value_template':
'{{ states.binary_sensor.test_sensor.state }}',
'entity_picture_template': '{{ 1 + 1 }}',
},
}
}
})
await hass.async_block_till_done()
assert len(hass.states.async_all()) == 4
assert ('Template binary sensor all_state has no entity ids '
'configured to track nor were we able to extract the entities to '
'track from the value template') in caplog.text
assert ('Template binary sensor all_icon has no entity ids '
'configured to track nor were we able to extract the entities to '
'track from the icon template') in caplog.text
assert ('Template binary sensor all_entity_picture has no entity ids '
'configured to track nor were we able to extract the entities to '
'track from the entity_picture template') in caplog.text
assert hass.states.get('binary_sensor.all_state').state == 'off'
assert hass.states.get('binary_sensor.all_icon').state == 'off'
assert hass.states.get('binary_sensor.all_entity_picture').state == 'off'
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
assert hass.states.get('binary_sensor.all_state').state == 'on'
assert hass.states.get('binary_sensor.all_icon').state == 'on'
assert hass.states.get('binary_sensor.all_entity_picture').state == 'on'
hass.states.async_set('binary_sensor.test_sensor', 'false')
await hass.async_block_till_done()
assert hass.states.get('binary_sensor.all_state').state == 'on'
assert hass.states.get('binary_sensor.all_icon').state == 'on'
assert hass.states.get('binary_sensor.all_entity_picture').state == 'on'
await hass.helpers.entity_component.async_update_entity(
'binary_sensor.all_state')
await hass.helpers.entity_component.async_update_entity(
'binary_sensor.all_icon')
await hass.helpers.entity_component.async_update_entity(
'binary_sensor.all_entity_picture')
assert hass.states.get('binary_sensor.all_state').state == 'on'
assert hass.states.get('binary_sensor.all_icon').state == 'off'
assert hass.states.get('binary_sensor.all_entity_picture').state == 'off'

View file

@ -1,395 +0,0 @@
"""The test for the threshold sensor platform."""
import unittest
from homeassistant.setup import setup_component
from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT, STATE_UNKNOWN, TEMP_CELSIUS)
from tests.common import get_test_home_assistant
class TestThresholdSensor(unittest.TestCase):
"""Test the threshold sensor."""
def setup_method(self, method):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def teardown_method(self, method):
"""Stop everything that was started."""
self.hass.stop()
def test_sensor_upper(self):
"""Test if source is above threshold."""
config = {
'binary_sensor': {
'platform': 'threshold',
'upper': '15',
'entity_id': 'sensor.test_monitored',
}
}
assert setup_component(self.hass, 'binary_sensor', config)
self.hass.states.set('sensor.test_monitored', 16,
{ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'sensor.test_monitored' == \
state.attributes.get('entity_id')
assert 16 == state.attributes.get('sensor_value')
assert 'above' == state.attributes.get('position')
assert float(config['binary_sensor']['upper']) == \
state.attributes.get('upper')
assert 0.0 == state.attributes.get('hysteresis')
assert 'upper' == state.attributes.get('type')
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 14)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 15)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert state.state == 'off'
def test_sensor_lower(self):
"""Test if source is below threshold."""
config = {
'binary_sensor': {
'platform': 'threshold',
'lower': '15',
'entity_id': 'sensor.test_monitored',
}
}
assert setup_component(self.hass, 'binary_sensor', config)
self.hass.states.set('sensor.test_monitored', 16)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'above' == state.attributes.get('position')
assert float(config['binary_sensor']['lower']) == \
state.attributes.get('lower')
assert 0.0 == state.attributes.get('hysteresis')
assert 'lower' == state.attributes.get('type')
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 14)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert state.state == 'on'
def test_sensor_hysteresis(self):
"""Test if source is above threshold using hysteresis."""
config = {
'binary_sensor': {
'platform': 'threshold',
'upper': '15',
'hysteresis': '2.5',
'entity_id': 'sensor.test_monitored',
}
}
assert setup_component(self.hass, 'binary_sensor', config)
self.hass.states.set('sensor.test_monitored', 20)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'above' == state.attributes.get('position')
assert float(config['binary_sensor']['upper']) == \
state.attributes.get('upper')
assert 2.5 == state.attributes.get('hysteresis')
assert 'upper' == state.attributes.get('type')
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 13)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 12)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 17)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 18)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert state.state == 'on'
def test_sensor_in_range_no_hysteresis(self):
"""Test if source is within the range."""
config = {
'binary_sensor': {
'platform': 'threshold',
'lower': '10',
'upper': '20',
'entity_id': 'sensor.test_monitored',
}
}
assert setup_component(self.hass, 'binary_sensor', config)
self.hass.states.set('sensor.test_monitored', 16,
{ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'sensor.test_monitored' == \
state.attributes.get('entity_id')
assert 16 == state.attributes.get('sensor_value')
assert 'in_range' == state.attributes.get('position')
assert float(config['binary_sensor']['lower']) == \
state.attributes.get('lower')
assert float(config['binary_sensor']['upper']) == \
state.attributes.get('upper')
assert 0.0 == state.attributes.get('hysteresis')
assert 'range' == state.attributes.get('type')
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 9)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'below' == state.attributes.get('position')
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 21)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'above' == state.attributes.get('position')
assert state.state == 'off'
def test_sensor_in_range_with_hysteresis(self):
"""Test if source is within the range."""
config = {
'binary_sensor': {
'platform': 'threshold',
'lower': '10',
'upper': '20',
'hysteresis': '2',
'entity_id': 'sensor.test_monitored',
}
}
assert setup_component(self.hass, 'binary_sensor', config)
self.hass.states.set('sensor.test_monitored', 16,
{ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'sensor.test_monitored' == \
state.attributes.get('entity_id')
assert 16 == state.attributes.get('sensor_value')
assert 'in_range' == state.attributes.get('position')
assert float(config['binary_sensor']['lower']) == \
state.attributes.get('lower')
assert float(config['binary_sensor']['upper']) == \
state.attributes.get('upper')
assert float(config['binary_sensor']['hysteresis']) == \
state.attributes.get('hysteresis')
assert 'range' == state.attributes.get('type')
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 8)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'in_range' == state.attributes.get('position')
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 7)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'below' == state.attributes.get('position')
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 12)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'below' == state.attributes.get('position')
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 13)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'in_range' == state.attributes.get('position')
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 22)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'in_range' == state.attributes.get('position')
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 23)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'above' == state.attributes.get('position')
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 18)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'above' == state.attributes.get('position')
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 17)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'in_range' == state.attributes.get('position')
assert state.state == 'on'
def test_sensor_in_range_unknown_state(self):
"""Test if source is within the range."""
config = {
'binary_sensor': {
'platform': 'threshold',
'lower': '10',
'upper': '20',
'entity_id': 'sensor.test_monitored',
}
}
assert setup_component(self.hass, 'binary_sensor', config)
self.hass.states.set('sensor.test_monitored', 16,
{ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'sensor.test_monitored' == \
state.attributes.get('entity_id')
assert 16 == state.attributes.get('sensor_value')
assert 'in_range' == state.attributes.get('position')
assert float(config['binary_sensor']['lower']) == \
state.attributes.get('lower')
assert float(config['binary_sensor']['upper']) == \
state.attributes.get('upper')
assert 0.0 == state.attributes.get('hysteresis')
assert 'range' == state.attributes.get('type')
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', STATE_UNKNOWN)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'unknown' == state.attributes.get('position')
assert state.state == 'off'
def test_sensor_lower_zero_threshold(self):
"""Test if a lower threshold of zero is set."""
config = {
'binary_sensor': {
'platform': 'threshold',
'lower': '0',
'entity_id': 'sensor.test_monitored',
}
}
assert setup_component(self.hass, 'binary_sensor', config)
self.hass.states.set('sensor.test_monitored', 16)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'lower' == state.attributes.get('type')
assert float(config['binary_sensor']['lower']) == \
state.attributes.get('lower')
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', -3)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert state.state == 'on'
def test_sensor_upper_zero_threshold(self):
"""Test if an upper threshold of zero is set."""
config = {
'binary_sensor': {
'platform': 'threshold',
'upper': '0',
'entity_id': 'sensor.test_monitored',
}
}
assert setup_component(self.hass, 'binary_sensor', config)
self.hass.states.set('sensor.test_monitored', -10)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert 'upper' == state.attributes.get('type')
assert float(config['binary_sensor']['upper']) == \
state.attributes.get('upper')
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 2)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
assert state.state == 'on'

View file

@ -1,840 +0,0 @@
"""Test Times of the Day Binary Sensor."""
import unittest
from unittest.mock import patch
from datetime import timedelta, datetime
import pytz
from homeassistant import setup
import homeassistant.core as ha
from homeassistant.const import STATE_OFF, STATE_ON
import homeassistant.util.dt as dt_util
from homeassistant.setup import setup_component
from tests.common import (
get_test_home_assistant, assert_setup_component)
from homeassistant.helpers.sun import (
get_astral_event_date, get_astral_event_next)
class TestBinarySensorTod(unittest.TestCase):
"""Test for Binary sensor tod platform."""
hass = None
# pylint: disable=invalid-name
def setup_method(self, method):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.config.latitute = 50.27583
self.hass.config.longitude = 18.98583
def teardown_method(self, method):
"""Stop everything that was started."""
self.hass.stop()
def test_setup(self):
"""Test the setup."""
config = {
'binary_sensor': [
{
'platform': 'tod',
'name': 'Early Morning',
'after': 'sunrise',
'after_offset': '-02:00',
'before': '7:00',
'before_offset': '1:00'
},
{
'platform': 'tod',
'name': 'Morning',
'after': 'sunrise',
'before': '12:00'
}
],
}
with assert_setup_component(2):
assert setup.setup_component(
self.hass, 'binary_sensor', config)
def test_setup_no_sensors(self):
"""Test setup with no sensors."""
with assert_setup_component(0):
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'tod'
}
})
def test_in_period_on_start(self):
"""Test simple setting."""
test_time = datetime(
2019, 1, 10, 18, 43, 0, tzinfo=self.hass.config.time_zone)
config = {
'binary_sensor': [
{
'platform': 'tod',
'name': 'Evening',
'after': '18:00',
'before': '22:00'
}
]
}
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=test_time):
setup_component(self.hass, 'binary_sensor', config)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.evening')
assert state.state == STATE_ON
def test_midnight_turnover_before_midnight_inside_period(self):
"""Test midnight turnover setting before midnight inside period ."""
test_time = datetime(
2019, 1, 10, 22, 30, 0, tzinfo=self.hass.config.time_zone)
config = {
'binary_sensor': [
{
'platform': 'tod',
'name': 'Night',
'after': '22:00',
'before': '5:00'
},
]
}
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=test_time):
setup_component(self.hass, 'binary_sensor', config)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.night')
assert state.state == STATE_ON
def test_midnight_turnover_after_midnight_inside_period(self):
"""Test midnight turnover setting before midnight inside period ."""
test_time = self.hass.config.time_zone.localize(
datetime(2019, 1, 10, 21, 0, 0)).astimezone(pytz.UTC)
config = {
'binary_sensor': [
{
'platform': 'tod',
'name': 'Night',
'after': '22:00',
'before': '5:00'
},
]
}
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=test_time):
setup_component(self.hass, 'binary_sensor', config)
state = self.hass.states.get('binary_sensor.night')
assert state.state == STATE_OFF
self.hass.block_till_done()
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=test_time + timedelta(hours=1)):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: test_time + timedelta(hours=1)})
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.night')
assert state.state == STATE_ON
def test_midnight_turnover_before_midnight_outside_period(self):
"""Test midnight turnover setting before midnight outside period."""
test_time = self.hass.config.time_zone.localize(
datetime(2019, 1, 10, 20, 30, 0)).astimezone(pytz.UTC)
config = {
'binary_sensor': [
{
'platform': 'tod',
'name': 'Night',
'after': '22:00',
'before': '5:00'
}
]
}
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=test_time):
setup_component(self.hass, 'binary_sensor', config)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.night')
assert state.state == STATE_OFF
def test_midnight_turnover_after_midnight_outside_period(self):
"""Test midnight turnover setting before midnight inside period ."""
test_time = self.hass.config.time_zone.localize(
datetime(2019, 1, 10, 20, 0, 0)).astimezone(pytz.UTC)
config = {
'binary_sensor': [
{
'platform': 'tod',
'name': 'Night',
'after': '22:00',
'before': '5:00'
}
]
}
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=test_time):
setup_component(self.hass, 'binary_sensor', config)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.night')
assert state.state == STATE_OFF
switchover_time = self.hass.config.time_zone.localize(
datetime(2019, 1, 11, 4, 59, 0)).astimezone(pytz.UTC)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=switchover_time):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: switchover_time})
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.night')
assert state.state == STATE_ON
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=switchover_time + timedelta(
minutes=1, seconds=1)):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: switchover_time + timedelta(
minutes=1, seconds=1)})
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.night')
assert state.state == STATE_OFF
def test_from_sunrise_to_sunset(self):
"""Test period from sunrise to sunset."""
test_time = self.hass.config.time_zone.localize(
datetime(2019, 1, 12)).astimezone(pytz.UTC)
sunrise = dt_util.as_local(get_astral_event_date(
self.hass, 'sunrise', dt_util.as_utc(test_time)))
sunset = dt_util.as_local(get_astral_event_date(
self.hass, 'sunset', dt_util.as_utc(test_time)))
config = {
'binary_sensor': [
{
'platform': 'tod',
'name': 'Day',
'after': 'sunrise',
'before': 'sunset'
}
]
}
entity_id = 'binary_sensor.day'
testtime = sunrise + timedelta(seconds=-1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
setup_component(self.hass, 'binary_sensor', config)
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
testtime = sunrise
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
testtime = sunrise + timedelta(seconds=1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
self.hass.block_till_done()
testtime = sunset + timedelta(seconds=-1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
self.hass.block_till_done()
testtime = sunset
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
self.hass.block_till_done()
testtime = sunset + timedelta(seconds=1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
def test_from_sunset_to_sunrise(self):
"""Test period from sunset to sunrise."""
test_time = self.hass.config.time_zone.localize(
datetime(2019, 1, 12)).astimezone(pytz.UTC)
sunset = dt_util.as_local(get_astral_event_date(
self.hass, 'sunset', test_time))
sunrise = dt_util.as_local(get_astral_event_next(
self.hass, 'sunrise', sunset))
# assert sunset == sunrise
config = {
'binary_sensor': [
{
'platform': 'tod',
'name': 'Night',
'after': 'sunset',
'before': 'sunrise'
}
]
}
entity_id = 'binary_sensor.night'
testtime = sunset + timedelta(minutes=-1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
setup_component(self.hass, 'binary_sensor', config)
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
testtime = sunset
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
testtime = sunset + timedelta(minutes=1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
testtime = sunrise + timedelta(minutes=-1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
testtime = sunrise
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
self.hass.block_till_done()
# assert state == "dupa"
assert state.state == STATE_OFF
testtime = sunrise + timedelta(minutes=1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
def test_offset(self):
"""Test offset."""
after = self.hass.config.time_zone.localize(
datetime(2019, 1, 10, 18, 0, 0)).astimezone(pytz.UTC) + \
timedelta(hours=1, minutes=34)
before = self.hass.config.time_zone.localize(
datetime(2019, 1, 10, 22, 0, 0)).astimezone(pytz.UTC) + \
timedelta(hours=1, minutes=45)
entity_id = 'binary_sensor.evening'
config = {
'binary_sensor': [
{
'platform': 'tod',
'name': 'Evening',
'after': '18:00',
'after_offset': '1:34',
'before': '22:00',
'before_offset': '1:45'
}
]
}
testtime = after + timedelta(seconds=-1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
setup_component(self.hass, 'binary_sensor', config)
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
testtime = after
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
testtime = before + timedelta(seconds=-1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
testtime = before
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
testtime = before + timedelta(seconds=1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
def test_offset_overnight(self):
"""Test offset overnight."""
after = self.hass.config.time_zone.localize(
datetime(2019, 1, 10, 18, 0, 0)).astimezone(pytz.UTC) + \
timedelta(hours=1, minutes=34)
entity_id = 'binary_sensor.evening'
config = {
'binary_sensor': [
{
'platform': 'tod',
'name': 'Evening',
'after': '18:00',
'after_offset': '1:34',
'before': '22:00',
'before_offset': '3:00'
}
]
}
testtime = after + timedelta(seconds=-1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
setup_component(self.hass, 'binary_sensor', config)
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
testtime = after
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
def test_norwegian_case_winter(self):
"""Test location in Norway where the sun doesn't set in summer."""
self.hass.config.latitude = 69.6
self.hass.config.longitude = 18.8
test_time = self.hass.config.time_zone.localize(
datetime(2010, 1, 1)).astimezone(pytz.UTC)
sunrise = dt_util.as_local(get_astral_event_next(
self.hass, 'sunrise', dt_util.as_utc(test_time)))
sunset = dt_util.as_local(get_astral_event_next(
self.hass, 'sunset', dt_util.as_utc(test_time)))
config = {
'binary_sensor': [
{
'platform': 'tod',
'name': 'Day',
'after': 'sunrise',
'before': 'sunset'
}
]
}
entity_id = 'binary_sensor.day'
testtime = test_time
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
setup_component(self.hass, 'binary_sensor', config)
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
testtime = sunrise + timedelta(seconds=-1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
testtime = sunrise
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
testtime = sunrise + timedelta(seconds=1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
self.hass.block_till_done()
testtime = sunset + timedelta(seconds=-1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
self.hass.block_till_done()
testtime = sunset
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
self.hass.block_till_done()
testtime = sunset + timedelta(seconds=1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
def test_norwegian_case_summer(self):
"""Test location in Norway where the sun doesn't set in summer."""
self.hass.config.latitude = 69.6
self.hass.config.longitude = 18.8
test_time = self.hass.config.time_zone.localize(
datetime(2010, 6, 1)).astimezone(pytz.UTC)
sunrise = dt_util.as_local(get_astral_event_next(
self.hass, 'sunrise', dt_util.as_utc(test_time)))
sunset = dt_util.as_local(get_astral_event_next(
self.hass, 'sunset', dt_util.as_utc(test_time)))
config = {
'binary_sensor': [
{
'platform': 'tod',
'name': 'Day',
'after': 'sunrise',
'before': 'sunset'
}
]
}
entity_id = 'binary_sensor.day'
testtime = test_time
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
setup_component(self.hass, 'binary_sensor', config)
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
testtime = sunrise + timedelta(seconds=-1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
testtime = sunrise
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
testtime = sunrise + timedelta(seconds=1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
self.hass.block_till_done()
testtime = sunset + timedelta(seconds=-1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
self.hass.block_till_done()
testtime = sunset
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
self.hass.block_till_done()
testtime = sunset + timedelta(seconds=1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
def test_sun_offset(self):
"""Test sun event with offset."""
test_time = self.hass.config.time_zone.localize(
datetime(2019, 1, 12)).astimezone(pytz.UTC)
sunrise = dt_util.as_local(get_astral_event_date(
self.hass, 'sunrise', dt_util.as_utc(test_time)) +
timedelta(hours=-1, minutes=-30))
sunset = dt_util.as_local(get_astral_event_date(
self.hass, 'sunset', dt_util.as_utc(test_time)) +
timedelta(hours=1, minutes=30))
config = {
'binary_sensor': [
{
'platform': 'tod',
'name': 'Day',
'after': 'sunrise',
'after_offset': '-1:30',
'before': 'sunset',
'before_offset': '1:30'
}
]
}
entity_id = 'binary_sensor.day'
testtime = sunrise + timedelta(seconds=-1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
setup_component(self.hass, 'binary_sensor', config)
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
testtime = sunrise
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
testtime = sunrise + timedelta(seconds=1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
self.hass.block_till_done()
testtime = sunset + timedelta(seconds=-1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
self.hass.block_till_done()
testtime = sunset
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
self.hass.block_till_done()
testtime = sunset + timedelta(seconds=1)
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_OFF
test_time = test_time + timedelta(days=1)
sunrise = dt_util.as_local(get_astral_event_date(
self.hass, 'sunrise', dt_util.as_utc(test_time)) +
timedelta(hours=-1, minutes=-30))
testtime = sunrise
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
ha.ATTR_NOW: testtime})
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
assert state.state == STATE_ON
def test_dst(self):
"""Test sun event with offset."""
self.hass.config.time_zone = pytz.timezone('CET')
test_time = self.hass.config.time_zone.localize(
datetime(2019, 3, 30, 3, 0, 0)).astimezone(pytz.UTC)
config = {
'binary_sensor': [
{
'platform': 'tod',
'name': 'Day',
'after': '2:30',
'before': '2:40'
}
]
}
# after 2019-03-30 03:00 CET the next update should ge scheduled
# at 3:30 not 2:30 local time
# Internally the
entity_id = 'binary_sensor.day'
testtime = test_time
with patch('homeassistant.components.binary_sensor.tod.dt_util.utcnow',
return_value=testtime):
setup_component(self.hass, 'binary_sensor', config)
self.hass.block_till_done()
state = self.hass.states.get(entity_id)
state.attributes['after'] == '2019-03-31T03:30:00+02:00'
state.attributes['before'] == '2019-03-31T03:40:00+02:00'
state.attributes['next_update'] == '2019-03-31T03:30:00+02:00'
assert state.state == STATE_OFF

View file

@ -1,316 +0,0 @@
"""The test for the Trend sensor platform."""
from homeassistant import setup
from tests.common import get_test_home_assistant, assert_setup_component
class TestTrendBinarySensor:
"""Test the Trend sensor."""
hass = None
def setup_method(self, method):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def teardown_method(self, method):
"""Stop everything that was started."""
self.hass.stop()
def test_up(self):
"""Test up trend."""
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'trend',
'sensors': {
'test_trend_sensor': {
'entity_id':
"sensor.test_state"
}
}
}
})
self.hass.states.set('sensor.test_state', '1')
self.hass.block_till_done()
self.hass.states.set('sensor.test_state', '2')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'on'
def test_up_using_trendline(self):
"""Test up trend using multiple samples and trendline calculation."""
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'trend',
'sensors': {
'test_trend_sensor': {
'entity_id': "sensor.test_state",
'sample_duration': 300,
'min_gradient': 1,
'max_samples': 25,
}
}
}
})
for val in [1, 0, 2, 3]:
self.hass.states.set('sensor.test_state', val)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'on'
for val in [0, 1, 0, 0]:
self.hass.states.set('sensor.test_state', val)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'off'
def test_down_using_trendline(self):
"""Test down trend using multiple samples and trendline calculation."""
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'trend',
'sensors': {
'test_trend_sensor': {
'entity_id': "sensor.test_state",
'sample_duration': 300,
'min_gradient': 1,
'max_samples': 25,
'invert': 'Yes'
}
}
}
})
for val in [3, 2, 3, 1]:
self.hass.states.set('sensor.test_state', val)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'on'
for val in [4, 2, 4, 4]:
self.hass.states.set('sensor.test_state', val)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'off'
def test_down(self):
"""Test down trend."""
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'trend',
'sensors': {
'test_trend_sensor': {
'entity_id':
"sensor.test_state"
}
}
}
})
self.hass.states.set('sensor.test_state', '2')
self.hass.block_till_done()
self.hass.states.set('sensor.test_state', '1')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'off'
def test_invert_up(self):
"""Test up trend with custom message."""
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'trend',
'sensors': {
'test_trend_sensor': {
'entity_id':
"sensor.test_state",
'invert': "Yes"
}
}
}
})
self.hass.states.set('sensor.test_state', '1')
self.hass.block_till_done()
self.hass.states.set('sensor.test_state', '2')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'off'
def test_invert_down(self):
"""Test down trend with custom message."""
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'trend',
'sensors': {
'test_trend_sensor': {
'entity_id':
"sensor.test_state",
'invert': "Yes"
}
}
}
})
self.hass.states.set('sensor.test_state', '2')
self.hass.block_till_done()
self.hass.states.set('sensor.test_state', '1')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'on'
def test_attribute_up(self):
"""Test attribute up trend."""
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'trend',
'sensors': {
'test_trend_sensor': {
'entity_id':
"sensor.test_state",
'attribute': 'attr'
}
}
}
})
self.hass.states.set('sensor.test_state', 'State', {'attr': '1'})
self.hass.block_till_done()
self.hass.states.set('sensor.test_state', 'State', {'attr': '2'})
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'on'
def test_attribute_down(self):
"""Test attribute down trend."""
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'trend',
'sensors': {
'test_trend_sensor': {
'entity_id':
"sensor.test_state",
'attribute': 'attr'
}
}
}
})
self.hass.states.set('sensor.test_state', 'State', {'attr': '2'})
self.hass.block_till_done()
self.hass.states.set('sensor.test_state', 'State', {'attr': '1'})
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'off'
def test_max_samples(self):
"""Test that sample count is limited correctly."""
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'trend',
'sensors': {
'test_trend_sensor': {
'entity_id': "sensor.test_state",
'max_samples': 3,
'min_gradient': -1,
}
}
}
})
for val in [0, 1, 2, 3, 2, 1]:
self.hass.states.set('sensor.test_state', val)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'on'
assert state.attributes['sample_count'] == 3
def test_non_numeric(self):
"""Test up trend."""
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'trend',
'sensors': {
'test_trend_sensor': {
'entity_id':
"sensor.test_state"
}
}
}
})
self.hass.states.set('sensor.test_state', 'Non')
self.hass.block_till_done()
self.hass.states.set('sensor.test_state', 'Numeric')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'off'
def test_missing_attribute(self):
"""Test attribute down trend."""
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'trend',
'sensors': {
'test_trend_sensor': {
'entity_id':
"sensor.test_state",
'attribute': 'missing'
}
}
}
})
self.hass.states.set('sensor.test_state', 'State', {'attr': '2'})
self.hass.block_till_done()
self.hass.states.set('sensor.test_state', 'State', {'attr': '1'})
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_trend_sensor')
assert state.state == 'off'
def test_invalid_name_does_not_create(self):
"""Test invalid name."""
with assert_setup_component(0):
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'template',
'sensors': {
'test INVALID sensor': {
'entity_id':
"sensor.test_state"
}
}
}
})
assert self.hass.states.all() == []
def test_invalid_sensor_does_not_create(self):
"""Test invalid sensor."""
with assert_setup_component(0):
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'template',
'sensors': {
'test_trend_sensor': {
'not_entity_id':
"sensor.test_state"
}
}
}
})
assert self.hass.states.all() == []
def test_no_sensors_does_not_create(self):
"""Test no sensors."""
with assert_setup_component(0):
assert setup.setup_component(self.hass, 'binary_sensor', {
'binary_sensor': {
'platform': 'trend'
}
})
assert self.hass.states.all() == []

View file

@ -1,165 +0,0 @@
"""Test the Vultr binary sensor platform."""
import json
import unittest
from unittest.mock import patch
import requests_mock
import pytest
import voluptuous as vol
from homeassistant.components.binary_sensor import vultr
from homeassistant.components import vultr as base_vultr
from homeassistant.components.vultr import (
ATTR_ALLOWED_BANDWIDTH, ATTR_AUTO_BACKUPS, ATTR_IPV4_ADDRESS,
ATTR_COST_PER_MONTH, ATTR_CREATED_AT, ATTR_SUBSCRIPTION_ID,
CONF_SUBSCRIPTION)
from homeassistant.const import (
CONF_PLATFORM, CONF_NAME)
from tests.components.vultr.test_init import VALID_CONFIG
from tests.common import (
get_test_home_assistant, load_fixture)
class TestVultrBinarySensorSetup(unittest.TestCase):
"""Test the Vultr binary sensor platform."""
DEVICES = []
def add_entities(self, devices, action):
"""Mock add devices."""
for device in devices:
self.DEVICES.append(device)
def setUp(self):
"""Init values for this testcase class."""
self.hass = get_test_home_assistant()
self.configs = [
{
CONF_SUBSCRIPTION: '576965',
CONF_NAME: "A Server"
},
{
CONF_SUBSCRIPTION: '123456',
CONF_NAME: "Failed Server"
},
{
CONF_SUBSCRIPTION: '555555',
CONF_NAME: vultr.DEFAULT_NAME
}
]
def tearDown(self):
"""Stop our started services."""
self.hass.stop()
@requests_mock.Mocker()
def test_binary_sensor(self, mock):
"""Test successful instance."""
mock.get(
'https://api.vultr.com/v1/account/info?api_key=ABCDEFG1234567',
text=load_fixture('vultr_account_info.json'))
with patch(
'vultr.Vultr.server_list',
return_value=json.loads(
load_fixture('vultr_server_list.json'))):
# Setup hub
base_vultr.setup(self.hass, VALID_CONFIG)
# Setup each of our test configs
for config in self.configs:
vultr.setup_platform(self.hass,
config,
self.add_entities,
None)
assert len(self.DEVICES) == 3
for device in self.DEVICES:
# Test pre data retrieval
if device.subscription == '555555':
assert 'Vultr {}' == device.name
device.update()
device_attrs = device.device_state_attributes
if device.subscription == '555555':
assert 'Vultr Another Server' == device.name
if device.name == 'A Server':
assert device.is_on is True
assert 'power' == device.device_class
assert 'on' == device.state
assert 'mdi:server' == device.icon
assert '1000' == \
device_attrs[ATTR_ALLOWED_BANDWIDTH]
assert 'yes' == \
device_attrs[ATTR_AUTO_BACKUPS]
assert '123.123.123.123' == \
device_attrs[ATTR_IPV4_ADDRESS]
assert '10.05' == \
device_attrs[ATTR_COST_PER_MONTH]
assert '2013-12-19 14:45:41' == \
device_attrs[ATTR_CREATED_AT]
assert '576965' == \
device_attrs[ATTR_SUBSCRIPTION_ID]
elif device.name == 'Failed Server':
assert device.is_on is False
assert 'off' == device.state
assert 'mdi:server-off' == device.icon
assert '1000' == \
device_attrs[ATTR_ALLOWED_BANDWIDTH]
assert 'no' == \
device_attrs[ATTR_AUTO_BACKUPS]
assert '192.168.100.50' == \
device_attrs[ATTR_IPV4_ADDRESS]
assert '73.25' == \
device_attrs[ATTR_COST_PER_MONTH]
assert '2014-10-13 14:45:41' == \
device_attrs[ATTR_CREATED_AT]
assert '123456' == \
device_attrs[ATTR_SUBSCRIPTION_ID]
def test_invalid_sensor_config(self):
"""Test config type failures."""
with pytest.raises(vol.Invalid): # No subs
vultr.PLATFORM_SCHEMA({
CONF_PLATFORM: base_vultr.DOMAIN,
})
@requests_mock.Mocker()
def test_invalid_sensors(self, mock):
"""Test the VultrBinarySensor fails."""
mock.get(
'https://api.vultr.com/v1/account/info?api_key=ABCDEFG1234567',
text=load_fixture('vultr_account_info.json'))
with patch(
'vultr.Vultr.server_list',
return_value=json.loads(
load_fixture('vultr_server_list.json'))):
# Setup hub
base_vultr.setup(self.hass, VALID_CONFIG)
bad_conf = {} # No subscription
no_subs_setup = vultr.setup_platform(self.hass,
bad_conf,
self.add_entities,
None)
assert not no_subs_setup
bad_conf = {
CONF_NAME: "Missing Server",
CONF_SUBSCRIPTION: '555555'
} # Sub not associated with API key (not in server_list)
wrong_subs_setup = vultr.setup_platform(self.hass,
bad_conf,
self.add_entities,
None)
assert not wrong_subs_setup

View file

@ -1,259 +0,0 @@
"""Tests the HASS workday binary sensor."""
from datetime import date
from unittest.mock import patch
from homeassistant.components.binary_sensor.workday import day_to_string
from homeassistant.setup import setup_component
from tests.common import (
get_test_home_assistant, assert_setup_component)
FUNCTION_PATH = 'homeassistant.components.binary_sensor.workday.get_date'
class TestWorkdaySetup:
"""Test class for workday sensor."""
def setup_method(self):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
# Set valid default config for test
self.config_province = {
'binary_sensor': {
'platform': 'workday',
'country': 'DE',
'province': 'BW'
},
}
self.config_noprovince = {
'binary_sensor': {
'platform': 'workday',
'country': 'DE',
},
}
self.config_invalidprovince = {
'binary_sensor': {
'platform': 'workday',
'country': 'DE',
'province': 'invalid'
},
}
self.config_state = {
'binary_sensor': {
'platform': 'workday',
'country': 'US',
'province': 'CA'
},
}
self.config_nostate = {
'binary_sensor': {
'platform': 'workday',
'country': 'US',
},
}
self.config_includeholiday = {
'binary_sensor': {
'platform': 'workday',
'country': 'DE',
'province': 'BW',
'workdays': ['holiday'],
'excludes': ['sat', 'sun']
},
}
self.config_tomorrow = {
'binary_sensor': {
'platform': 'workday',
'country': 'DE',
'days_offset': 1
},
}
self.config_day_after_tomorrow = {
'binary_sensor': {
'platform': 'workday',
'country': 'DE',
'days_offset': 2
},
}
self.config_yesterday = {
'binary_sensor': {
'platform': 'workday',
'country': 'DE',
'days_offset': -1
},
}
def teardown_method(self):
"""Stop everything that was started."""
self.hass.stop()
def test_setup_component_province(self):
"""Set up workday component."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor',
self.config_province)
entity = self.hass.states.get('binary_sensor.workday_sensor')
assert entity is not None
# Freeze time to a workday - Mar 15th, 2017
@patch(FUNCTION_PATH, return_value=date(2017, 3, 15))
def test_workday_province(self, mock_date):
"""Test if workdays are reported correctly."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor',
self.config_province)
self.hass.start()
entity = self.hass.states.get('binary_sensor.workday_sensor')
assert entity.state == 'on'
# Freeze time to a weekend - Mar 12th, 2017
@patch(FUNCTION_PATH, return_value=date(2017, 3, 12))
def test_weekend_province(self, mock_date):
"""Test if weekends are reported correctly."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor',
self.config_province)
self.hass.start()
entity = self.hass.states.get('binary_sensor.workday_sensor')
assert entity.state == 'off'
# Freeze time to a public holiday in province BW - Jan 6th, 2017
@patch(FUNCTION_PATH, return_value=date(2017, 1, 6))
def test_public_holiday_province(self, mock_date):
"""Test if public holidays are reported correctly."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor',
self.config_province)
self.hass.start()
entity = self.hass.states.get('binary_sensor.workday_sensor')
assert entity.state == 'off'
def test_setup_component_noprovince(self):
"""Set up workday component."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor',
self.config_noprovince)
entity = self.hass.states.get('binary_sensor.workday_sensor')
assert entity is not None
# Freeze time to a public holiday in province BW - Jan 6th, 2017
@patch(FUNCTION_PATH, return_value=date(2017, 1, 6))
def test_public_holiday_noprovince(self, mock_date):
"""Test if public holidays are reported correctly."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor',
self.config_noprovince)
self.hass.start()
entity = self.hass.states.get('binary_sensor.workday_sensor')
assert entity.state == 'on'
# Freeze time to a public holiday in state CA - Mar 31st, 2017
@patch(FUNCTION_PATH, return_value=date(2017, 3, 31))
def test_public_holiday_state(self, mock_date):
"""Test if public holidays are reported correctly."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor', self.config_state)
self.hass.start()
entity = self.hass.states.get('binary_sensor.workday_sensor')
assert entity.state == 'off'
# Freeze time to a public holiday in state CA - Mar 31st, 2017
@patch(FUNCTION_PATH, return_value=date(2017, 3, 31))
def test_public_holiday_nostate(self, mock_date):
"""Test if public holidays are reported correctly."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor', self.config_nostate)
self.hass.start()
entity = self.hass.states.get('binary_sensor.workday_sensor')
assert entity.state == 'on'
def test_setup_component_invalidprovince(self):
"""Set up workday component."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor',
self.config_invalidprovince)
entity = self.hass.states.get('binary_sensor.workday_sensor')
assert entity is None
# Freeze time to a public holiday in province BW - Jan 6th, 2017
@patch(FUNCTION_PATH, return_value=date(2017, 1, 6))
def test_public_holiday_includeholiday(self, mock_date):
"""Test if public holidays are reported correctly."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor',
self.config_includeholiday)
self.hass.start()
entity = self.hass.states.get('binary_sensor.workday_sensor')
assert entity.state == 'on'
# Freeze time to a saturday to test offset - Aug 5th, 2017
@patch(FUNCTION_PATH, return_value=date(2017, 8, 5))
def test_tomorrow(self, mock_date):
"""Test if tomorrow are reported correctly."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor',
self.config_tomorrow)
self.hass.start()
entity = self.hass.states.get('binary_sensor.workday_sensor')
assert entity.state == 'off'
# Freeze time to a saturday to test offset - Aug 5th, 2017
@patch(FUNCTION_PATH, return_value=date(2017, 8, 5))
def test_day_after_tomorrow(self, mock_date):
"""Test if the day after tomorrow are reported correctly."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor',
self.config_day_after_tomorrow)
self.hass.start()
entity = self.hass.states.get('binary_sensor.workday_sensor')
assert entity.state == 'on'
# Freeze time to a saturday to test offset - Aug 5th, 2017
@patch(FUNCTION_PATH, return_value=date(2017, 8, 5))
def test_yesterday(self, mock_date):
"""Test if yesterday are reported correctly."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor',
self.config_yesterday)
self.hass.start()
entity = self.hass.states.get('binary_sensor.workday_sensor')
assert entity.state == 'on'
def test_day_to_string(self):
"""Test if day_to_string is behaving correctly."""
assert day_to_string(0) == 'mon'
assert day_to_string(1) == 'tue'
assert day_to_string(7) == 'holiday'
assert day_to_string(8) is None