From 9838697d2b27e605abce0b368af19b8fe37bc4d3 Mon Sep 17 00:00:00 2001 From: Fabian Affolter Date: Wed, 9 Mar 2016 10:25:50 +0100 Subject: [PATCH] Fix PEP257 issues --- tests/__init__.py | 7 +- tests/common.py | 46 ++++---- tests/components/__init__.py | 1 + .../alarm_control_panel/__init__.py | 1 + .../alarm_control_panel/test_manual.py | 30 +++-- .../alarm_control_panel/test_mqtt.py | 24 ++-- tests/components/automation/__init__.py | 1 + tests/components/automation/test_event.py | 19 ++-- tests/components/automation/test_init.py | 29 +++-- tests/components/automation/test_mqtt.py | 18 +-- .../automation/test_numeric_state.py | 35 ++++-- tests/components/automation/test_state.py | 38 +++++-- tests/components/automation/test_sun.py | 22 ++-- tests/components/automation/test_template.py | 29 +++-- tests/components/automation/test_time.py | 39 +++++-- tests/components/automation/test_zone.py | 17 +-- tests/components/binary_sensor/__init__.py | 1 + .../binary_sensor/test_binary_sensor.py | 6 +- .../binary_sensor/test_command_line.py | 24 ++-- tests/components/binary_sensor/test_mqtt.py | 13 +-- tests/components/binary_sensor/test_nx584.py | 31 ++++-- tests/components/binary_sensor/test_tcp.py | 21 ++-- .../components/binary_sensor/test_template.py | 18 ++- tests/components/camera/__init__.py | 1 + tests/components/camera/test_uvc.py | 27 ++++- tests/components/device_tracker/__init__.py | 1 + tests/components/device_tracker/test_init.py | 19 +++- .../device_tracker/test_locative.py | 27 ++--- tests/components/device_tracker/test_mqtt.py | 14 +-- .../device_tracker/test_owntracks.py | 39 +++++-- tests/components/device_tracker/test_unifi.py | 17 ++- tests/components/garage_door/__init__.py | 1 + tests/components/garage_door/test_demo.py | 17 ++- tests/components/light/__init__.py | 1 + tests/components/light/test_init.py | 20 ++-- tests/components/light/test_mqtt.py | 21 ++-- tests/components/light/test_rfxtrx.py | 38 +++---- tests/components/lock/__init__.py | 1 + tests/components/lock/test_demo.py | 17 ++- tests/components/lock/test_mqtt.py | 11 +- tests/components/media_player/__init__.py | 1 + tests/components/media_player/test_cast.py | 10 +- tests/components/media_player/test_demo.py | 17 +-- .../components/media_player/test_universal.py | 84 +++++++------- tests/components/notify/__init__.py | 1 + tests/components/notify/test_command_line.py | 15 +-- tests/components/notify/test_demo.py | 14 +-- tests/components/rollershutter/__init__.py | 1 + .../rollershutter/test_command_line.py | 14 ++- tests/components/rollershutter/test_mqtt.py | 17 +-- tests/components/sensor/__init__.py | 1 + tests/components/sensor/test_command_line.py | 24 ++-- tests/components/sensor/test_mfi.py | 32 ++++-- tests/components/sensor/test_mqtt.py | 14 +-- tests/components/sensor/test_rfxtrx.py | 34 +++--- tests/components/sensor/test_tcp.py | 87 +++++---------- tests/components/sensor/test_template.py | 19 ++-- tests/components/sensor/test_yr.py | 14 +-- tests/components/switch/__init__.py | 1 + tests/components/switch/test_command_line.py | 16 +-- tests/components/switch/test_init.py | 18 +-- tests/components/switch/test_mfi.py | 23 ++-- tests/components/switch/test_mqtt.py | 15 ++- tests/components/switch/test_rfxtrx.py | 42 +++---- tests/components/switch/test_template.py | 25 +++-- tests/components/test_alexa.py | 20 ++-- tests/components/test_api.py | 83 +++++++------- tests/components/test_configurator.py | 39 ++----- tests/components/test_conversation.py | 25 ++--- tests/components/test_demo.py | 18 ++- .../test_device_sun_light_trigger.py | 18 ++- tests/components/test_frontend.py | 21 ++-- tests/components/test_graphite.py | 26 +++-- tests/components/test_group.py | 66 +++++------ tests/components/test_history.py | 33 +++--- tests/components/test_influx.py | 18 ++- tests/components/test_init.py | 22 ++-- tests/components/test_input_boolean.py | 15 +-- tests/components/test_input_select.py | 15 +-- tests/components/test_introduction.py | 14 +-- tests/components/test_logbook.py | 30 ++--- tests/components/test_logger.py | 25 ++--- tests/components/test_mqtt.py | 46 +++++--- tests/components/test_mqtt_eventstream.py | 20 ++-- tests/components/test_proximity.py | 30 +++-- tests/components/test_recorder.py | 18 ++- tests/components/test_rfxtrx.py | 19 ++-- tests/components/test_scene.py | 19 ++-- tests/components/test_script.py | 35 +++--- tests/components/test_shell_command.py | 19 ++-- tests/components/test_splunk.py | 13 ++- tests/components/test_statsd.py | 12 +- tests/components/test_sun.py | 18 ++- tests/components/test_updater.py | 18 ++- tests/components/test_weblink.py | 13 +-- tests/components/test_zone.py | 16 +-- tests/components/thermostat/__init__.py | 1 + .../thermostat/test_heat_control.py | 26 +++-- tests/components/thermostat/test_honeywell.py | 37 +++++- .../custom_components/device_tracker/test.py | 28 ++--- tests/config/custom_components/light/test.py | 9 +- tests/config/custom_components/switch/test.py | 9 +- tests/helpers/test_entity.py | 19 ++-- tests/helpers/test_entity_component.py | 7 +- tests/helpers/test_event.py | 44 ++++---- tests/helpers/test_event_decorators.py | 37 +++--- tests/helpers/test_init.py | 14 +-- tests/helpers/test_location.py | 7 ++ tests/helpers/test_service.py | 20 ++-- tests/helpers/test_state.py | 22 ++-- tests/helpers/test_template.py | 45 +++++++- tests/test_bootstrap.py | 19 ++-- tests/test_config.py | 41 +++---- tests/test_core.py | 105 +++++++++++------- tests/test_loader.py | 20 ++-- tests/test_remote.py | 63 +++++------ tests/util/test_color.py | 2 +- tests/util/test_dt.py | 42 +++---- tests/util/test_init.py | 45 ++++---- tests/util/test_package.py | 17 +-- 120 files changed, 1447 insertions(+), 1297 deletions(-) create mode 100644 tests/components/camera/__init__.py diff --git a/tests/__init__.py b/tests/__init__.py index 1f18116b24b..c1f50d86dfb 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1,9 +1,4 @@ -""" -tests.__init__ -~~~~~~~~~~~~~~ - -Tests initialization. -""" +"""Test the initialization.""" import betamax from homeassistant import util diff --git a/tests/common.py b/tests/common.py index 806416a3f0d..812f53ad53a 100644 --- a/tests/common.py +++ b/tests/common.py @@ -1,9 +1,4 @@ -""" -tests.common -~~~~~~~~~~~~ - -Helper method for writing tests. -""" +"""Test the helper method for writing tests.""" import os from datetime import timedelta from unittest import mock @@ -20,12 +15,12 @@ _TEST_INSTANCE_PORT = SERVER_PORT def get_test_config_dir(): - """ Returns a path to a test config dir. """ + """Return a path to a test config dir.""" return os.path.join(os.path.dirname(__file__), "config") def get_test_home_assistant(num_threads=None): - """ Returns a Home Assistant object pointing at test config dir. """ + """Return a Home Assistant object pointing at test config dir.""" if num_threads: orig_num_threads = ha.MIN_WORKER_THREAD ha.MIN_WORKER_THREAD = num_threads @@ -58,9 +53,9 @@ def get_test_instance_port(): def mock_service(hass, domain, service): - """ - Sets up a fake service. - Returns a list that logs all calls to fake service. + """Setup a fake service. + + Return a list that logs all calls to fake service. """ calls = [] @@ -71,6 +66,7 @@ def mock_service(hass, domain, service): def fire_mqtt_message(hass, topic, payload, qos=0): + """Fire the MQTT message.""" hass.bus.fire(mqtt.EVENT_MQTT_MESSAGE_RECEIVED, { mqtt.ATTR_TOPIC: topic, mqtt.ATTR_PAYLOAD: payload, @@ -79,10 +75,12 @@ def fire_mqtt_message(hass, topic, payload, qos=0): def fire_time_changed(hass, time): + """Fire a time changes event.""" hass.bus.fire(EVENT_TIME_CHANGED, {'now': time}) def fire_service_discovered(hass, service, info): + """Fire the MQTT message.""" hass.bus.fire(EVENT_PLATFORM_DISCOVERED, { ATTR_SERVICE: service, ATTR_DISCOVERED: info @@ -90,14 +88,14 @@ def fire_service_discovered(hass, service, info): def ensure_sun_risen(hass): - """ Trigger sun to rise if below horizon. """ + """Trigger sun to rise if below horizon.""" if sun.is_on(hass): return fire_time_changed(hass, sun.next_rising_utc(hass) + timedelta(seconds=10)) def ensure_sun_set(hass): - """ Trigger sun to set if above horizon. """ + """Trigger sun to set if above horizon.""" if not sun.is_on(hass): return fire_time_changed(hass, sun.next_setting_utc(hass) + timedelta(seconds=10)) @@ -116,12 +114,14 @@ def mock_state_change_event(hass, new_state, old_state=None): def mock_http_component(hass): + """Mock the HTTP component.""" hass.http = MockHTTP() hass.config.components.append('http') @mock.patch('homeassistant.components.mqtt.MQTT') def mock_mqtt_component(hass, mock_mqtt): + """Mock the MQTT component.""" mqtt.setup(hass, { mqtt.DOMAIN: { mqtt.CONF_BROKER: 'mock-broker', @@ -132,8 +132,7 @@ def mock_mqtt_component(hass, mock_mqtt): class MockHTTP(object): - """ Mocks the HTTP module. """ - + """Mock the HTTP module.""" def register_path(self, method, url, callback, require_auth=True): pass @@ -152,19 +151,21 @@ class MockModule(object): class MockPlatform(object): - """ Provides a fake platform. """ + """Provide a fake platform.""" def __init__(self, setup_platform=None, dependencies=[]): + """Initialize the platform.""" self.DEPENDENCIES = dependencies self._setup_platform = setup_platform def setup_platform(self, hass, config, add_devices, discovery_info=None): + """Setup the platform.""" if self._setup_platform is not None: self._setup_platform(hass, config, add_devices, discovery_info) class MockToggleDevice(ToggleEntity): - """ Provides a mock toggle device. """ + """Provide a mock toggle device.""" def __init__(self, name, state): self._name = name or DEVICE_DEFAULT_NAME self._state = state @@ -172,33 +173,34 @@ class MockToggleDevice(ToggleEntity): @property def name(self): - """ Returns the name of the device if any. """ + """Return the name of the device if any.""" self.calls.append(('name', {})) return self._name @property def state(self): - """ Returns the name of the device if any. """ + """Returns the name of the device if any.""" self.calls.append(('state', {})) return self._state @property def is_on(self): - """ True if device is on. """ + """Return true if device is on.""" self.calls.append(('is_on', {})) return self._state == STATE_ON def turn_on(self, **kwargs): - """ Turn the device on. """ + """Turn the device on.""" self.calls.append(('turn_on', kwargs)) self._state = STATE_ON def turn_off(self, **kwargs): - """ Turn the device off. """ + """Turn the device off.""" self.calls.append(('turn_off', kwargs)) self._state = STATE_OFF def last_call(self, method=None): + """Return the last call.""" if not self.calls: return None elif method is None: diff --git a/tests/components/__init__.py b/tests/components/__init__.py index e69de29bb2d..2ec564a74ce 100644 --- a/tests/components/__init__.py +++ b/tests/components/__init__.py @@ -0,0 +1 @@ +"""The tests for components.""" diff --git a/tests/components/alarm_control_panel/__init__.py b/tests/components/alarm_control_panel/__init__.py index e69de29bb2d..1ef1161edd0 100644 --- a/tests/components/alarm_control_panel/__init__.py +++ b/tests/components/alarm_control_panel/__init__.py @@ -0,0 +1 @@ +"""The tests for Alarm control panel platforms.""" diff --git a/tests/components/alarm_control_panel/test_manual.py b/tests/components/alarm_control_panel/test_manual.py index dc5cf8dbd7d..55bb6b36646 100644 --- a/tests/components/alarm_control_panel/test_manual.py +++ b/tests/components/alarm_control_panel/test_manual.py @@ -1,9 +1,4 @@ -""" -tests.components.alarm_control_panel.test_manual -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests manual alarm control panel component. -""" +"""The tests for the manual Alarm Control Panel component.""" from datetime import timedelta import unittest from unittest.mock import patch @@ -20,17 +15,18 @@ CODE = 'HELLO_CODE' class TestAlarmControlPanelManual(unittest.TestCase): - """ Test the manual alarm module. """ + """Test the manual alarm module.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop down everything that was started.""" self.hass.stop() def test_arm_home_no_pending(self): - """ Test arm home method. """ + """Test arm home method.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'manual', @@ -51,7 +47,7 @@ class TestAlarmControlPanelManual(unittest.TestCase): self.hass.states.get(entity_id).state) def test_arm_home_with_pending(self): - """ Test arm home method. """ + """Test arm home method.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'manual', @@ -81,7 +77,7 @@ class TestAlarmControlPanelManual(unittest.TestCase): self.hass.states.get(entity_id).state) def test_arm_home_with_invalid_code(self): - """ Attempt to arm home without a valid code. """ + """Attempt to arm home without a valid code.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'manual', @@ -102,7 +98,7 @@ class TestAlarmControlPanelManual(unittest.TestCase): self.hass.states.get(entity_id).state) def test_arm_away_no_pending(self): - """ Test arm home method. """ + """Test arm home method.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'manual', @@ -123,7 +119,7 @@ class TestAlarmControlPanelManual(unittest.TestCase): self.hass.states.get(entity_id).state) def test_arm_away_with_pending(self): - """ Test arm home method. """ + """Test arm home method.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'manual', @@ -153,7 +149,7 @@ class TestAlarmControlPanelManual(unittest.TestCase): self.hass.states.get(entity_id).state) def test_arm_away_with_invalid_code(self): - """ Attempt to arm away without a valid code. """ + """Attempt to arm away without a valid code.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'manual', @@ -174,7 +170,7 @@ class TestAlarmControlPanelManual(unittest.TestCase): self.hass.states.get(entity_id).state) def test_trigger_no_pending(self): - """ Test arm home method. """ + """Test arm home method.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'manual', @@ -194,7 +190,7 @@ class TestAlarmControlPanelManual(unittest.TestCase): self.hass.states.get(entity_id).state) def test_trigger_with_pending(self): - """ Test arm home method. """ + """Test arm home method.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'manual', @@ -233,6 +229,7 @@ class TestAlarmControlPanelManual(unittest.TestCase): self.hass.states.get(entity_id).state) def test_disarm_while_pending_trigger(self): + """Test disarming while pending state.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'manual', @@ -267,6 +264,7 @@ class TestAlarmControlPanelManual(unittest.TestCase): self.hass.states.get(entity_id).state) def test_disarm_during_trigger_with_invalid_code(self): + """Test disarming while code is invalid.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'manual', diff --git a/tests/components/alarm_control_panel/test_mqtt.py b/tests/components/alarm_control_panel/test_mqtt.py index 5af6664b52f..c44a2f3a120 100644 --- a/tests/components/alarm_control_panel/test_mqtt.py +++ b/tests/components/alarm_control_panel/test_mqtt.py @@ -1,9 +1,4 @@ -""" -tests.components.alarm_control_panel.test_manual -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests manual alarm control panel component. -""" +"""The tests the MQTT alarm control panel component.""" import unittest from unittest.mock import patch @@ -19,18 +14,20 @@ CODE = 'HELLO_CODE' class TestAlarmControlPanelMQTT(unittest.TestCase): - """ Test the manual alarm module. """ + """Test the manual alarm module.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.mock_publish = mock_mqtt_component(self.hass) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop down stuff we started.""" self.hass.stop() @patch('homeassistant.components.alarm_control_panel.mqtt._LOGGER.error') def test_fail_setup_without_state_topic(self, mock_error): + """Test for failing with no state topic.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'mqtt', @@ -41,6 +38,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase): @patch('homeassistant.components.alarm_control_panel.mqtt._LOGGER.error') def test_fail_setup_without_command_topic(self, mock_error): + """Test failing with no command topic.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'mqtt', @@ -50,7 +48,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase): self.assertEqual(1, mock_error.call_count) def test_update_state_via_state_topic(self): - """ Test arm home method. """ + """Test updating with via state topic.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'mqtt', @@ -72,7 +70,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase): self.assertEqual(state, self.hass.states.get(entity_id).state) def test_ignore_update_state_if_unknown_via_state_topic(self): - """ Test arm home method. """ + """Test ignoring updates via state topic.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'mqtt', @@ -91,6 +89,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase): self.assertEqual(STATE_UNKNOWN, self.hass.states.get(entity_id).state) def test_arm_home_publishes_mqtt(self): + """Test publishing of MQTT messages while armed.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'mqtt', @@ -105,6 +104,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase): self.mock_publish.mock_calls[-1][1]) def test_arm_home_not_publishes_mqtt_with_invalid_code(self): + """Test not publishing of MQTT messages with invalid code.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'mqtt', @@ -120,6 +120,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase): self.assertEqual(call_count, self.mock_publish.call_count) def test_arm_away_publishes_mqtt(self): + """Test publishing of MQTT messages while armed.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'mqtt', @@ -134,6 +135,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase): self.mock_publish.mock_calls[-1][1]) def test_arm_away_not_publishes_mqtt_with_invalid_code(self): + """Test not publishing of MQTT messages with invalid code.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'mqtt', @@ -149,6 +151,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase): self.assertEqual(call_count, self.mock_publish.call_count) def test_disarm_publishes_mqtt(self): + """Test publishing of MQTT messages while disarmed.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'mqtt', @@ -163,6 +166,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase): self.mock_publish.mock_calls[-1][1]) def test_disarm_not_publishes_mqtt_with_invalid_code(self): + """Test not publishing of MQTT messages with invalid code.""" self.assertTrue(alarm_control_panel.setup(self.hass, { 'alarm_control_panel': { 'platform': 'mqtt', diff --git a/tests/components/automation/__init__.py b/tests/components/automation/__init__.py index e69de29bb2d..8b2e5c1084a 100644 --- a/tests/components/automation/__init__.py +++ b/tests/components/automation/__init__.py @@ -0,0 +1 @@ +"""The tests for Automation.""" diff --git a/tests/components/automation/test_event.py b/tests/components/automation/test_event.py index 893fd47a639..e67402820a6 100644 --- a/tests/components/automation/test_event.py +++ b/tests/components/automation/test_event.py @@ -1,9 +1,4 @@ -""" -tests.components.automation.test_event -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests event automation. -""" +"""The tests for the Event automation.""" import unittest import homeassistant.components.automation as automation @@ -12,22 +7,25 @@ from tests.common import get_test_home_assistant class TestAutomationEvent(unittest.TestCase): - """ Test the event automation. """ + """Test the event automation.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.calls = [] def record_call(service): + """Helper for recording the call.""" self.calls.append(service) self.hass.services.register('test', 'automation', record_call) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """"Stop everything that was started.""" self.hass.stop() def test_old_config_if_fires_on_event(self): + """.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'event', @@ -41,6 +39,7 @@ class TestAutomationEvent(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_old_config_if_fires_on_event_with_data(self): + """Test old configuration .""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'event', @@ -55,6 +54,7 @@ class TestAutomationEvent(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_old_config_if_not_fires_if_event_data_not_matches(self): + """test old configuration.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'event', @@ -69,6 +69,7 @@ class TestAutomationEvent(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_fires_on_event(self): + """Test the firing of events.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -86,6 +87,7 @@ class TestAutomationEvent(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_on_event_with_data(self): + """Test the firing of events with data.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -105,6 +107,7 @@ class TestAutomationEvent(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_not_fires_if_event_data_not_matches(self): + """Test firing of event if no match.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { diff --git a/tests/components/automation/test_init.py b/tests/components/automation/test_init.py index 938ec6b6eac..14cbf025a56 100644 --- a/tests/components/automation/test_init.py +++ b/tests/components/automation/test_init.py @@ -1,9 +1,4 @@ -""" -tests.components.automation.test_init -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests automation component. -""" +"""The tests for the automation component.""" import unittest import homeassistant.components.automation as automation @@ -13,9 +8,10 @@ from tests.common import get_test_home_assistant class TestAutomation(unittest.TestCase): - """ Test the event automation. """ + """Test the event automation.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.calls = [] @@ -25,10 +21,11 @@ class TestAutomation(unittest.TestCase): self.hass.services.register('test', 'automation', record_call) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_old_config_service_data_not_a_dict(self): + """Test old configuration service data.""" automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'event', @@ -43,6 +40,7 @@ class TestAutomation(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_old_config_service_specify_data(self): + """Test old configuration service data.""" automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'event', @@ -58,6 +56,7 @@ class TestAutomation(unittest.TestCase): self.assertEqual('data', self.calls[0].data['some']) def test_old_config_service_specify_entity_id(self): + """Test old configuration service data.""" automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'event', @@ -74,6 +73,7 @@ class TestAutomation(unittest.TestCase): self.calls[0].data.get(ATTR_ENTITY_ID)) def test_old_config_service_specify_entity_id_list(self): + """Test old configuration service data.""" automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'event', @@ -90,6 +90,7 @@ class TestAutomation(unittest.TestCase): self.calls[0].data.get(ATTR_ENTITY_ID)) def test_service_data_not_a_dict(self): + """Test service data not dict.""" automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -108,6 +109,7 @@ class TestAutomation(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_service_specify_data(self): + """Test service data.""" automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -127,6 +129,7 @@ class TestAutomation(unittest.TestCase): self.assertEqual('data', self.calls[0].data['some']) def test_service_specify_entity_id(self): + """Test service data.""" automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -147,6 +150,7 @@ class TestAutomation(unittest.TestCase): self.calls[0].data.get(ATTR_ENTITY_ID)) def test_service_specify_entity_id_list(self): + """Test service data.""" automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -167,6 +171,7 @@ class TestAutomation(unittest.TestCase): self.calls[0].data.get(ATTR_ENTITY_ID)) def test_two_triggers(self): + """Test triggers.""" automation.setup(self.hass, { automation.DOMAIN: { 'trigger': [ @@ -193,6 +198,7 @@ class TestAutomation(unittest.TestCase): self.assertEqual(2, len(self.calls)) def test_two_conditions_with_and(self): + """Test two and conditions.""" entity_id = 'test.entity' automation.setup(self.hass, { automation.DOMAIN: { @@ -236,6 +242,7 @@ class TestAutomation(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_two_conditions_with_or(self): + """Test two or conditions.""" entity_id = 'test.entity' automation.setup(self.hass, { automation.DOMAIN: { @@ -280,7 +287,7 @@ class TestAutomation(unittest.TestCase): self.assertEqual(2, len(self.calls)) def test_using_trigger_as_condition(self): - """ """ + """Test triggers as condition.""" entity_id = 'test.entity' automation.setup(self.hass, { automation.DOMAIN: { @@ -316,7 +323,7 @@ class TestAutomation(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_using_trigger_as_condition_with_invalid_condition(self): - """ Event is not a valid condition. Will it still work? """ + """Event is not a valid condition.""" entity_id = 'test.entity' self.hass.states.set(entity_id, 100) automation.setup(self.hass, { @@ -344,7 +351,7 @@ class TestAutomation(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_automation_list_setting(self): - """ Event is not a valid condition. Will it still work? """ + """Event is not a valid condition.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: [{ 'trigger': { diff --git a/tests/components/automation/test_mqtt.py b/tests/components/automation/test_mqtt.py index 2c0a5612213..bb90d66a61f 100644 --- a/tests/components/automation/test_mqtt.py +++ b/tests/components/automation/test_mqtt.py @@ -1,9 +1,4 @@ -""" -tests.components.automation.test_mqtt -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests mqtt automation. -""" +"""The tests for the MQTT automation.""" import unittest import homeassistant.components.automation as automation @@ -12,9 +7,10 @@ from tests.common import ( class TestAutomationMQTT(unittest.TestCase): - """ Test the event automation. """ + """Test the event automation.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() mock_mqtt_component(self.hass) self.calls = [] @@ -25,10 +21,11 @@ class TestAutomationMQTT(unittest.TestCase): self.hass.services.register('test', 'automation', record_call) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_old_config_if_fires_on_topic_match(self): + """Test if message is fired on topic match.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'mqtt', @@ -42,6 +39,7 @@ class TestAutomationMQTT(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_old_config_if_fires_on_topic_and_payload_match(self): + """Test if message is fired on topic and payload match.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'mqtt', @@ -56,6 +54,7 @@ class TestAutomationMQTT(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_old_config_if_not_fires_on_topic_but_no_payload_match(self): + """Test if message is not fired on topic but no payload.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'mqtt', @@ -70,6 +69,7 @@ class TestAutomationMQTT(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_fires_on_topic_match(self): + """Test if message is fired on topic match.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -87,6 +87,7 @@ class TestAutomationMQTT(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_on_topic_and_payload_match(self): + """Test if message is fired on topic and payload match.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -105,6 +106,7 @@ class TestAutomationMQTT(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_not_fires_on_topic_but_no_payload_match(self): + """Test if message is not fired on topic but no payload.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { diff --git a/tests/components/automation/test_numeric_state.py b/tests/components/automation/test_numeric_state.py index 0960acbdcce..111230f81ab 100644 --- a/tests/components/automation/test_numeric_state.py +++ b/tests/components/automation/test_numeric_state.py @@ -1,9 +1,4 @@ -""" -tests.components.automation.test_numeric_state -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests numeric state automation. -""" +"""The tests for numeric state automation.""" import unittest import homeassistant.components.automation as automation @@ -12,22 +7,25 @@ from tests.common import get_test_home_assistant class TestAutomationNumericState(unittest.TestCase): - """ Test the event automation. """ + """Test the event automation.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.calls = [] def record_call(service): + """Helper to record calls.""" self.calls.append(service) self.hass.services.register('test', 'automation', record_call) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_if_fires_on_entity_change_below(self): + """"Test the firing with changed entity.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -46,6 +44,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_on_entity_change_over_to_below(self): + """"Test the firing with changed entity.""" self.hass.states.set('test.entity', 11) self.hass.pool.block_till_done() @@ -68,6 +67,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_not_fires_on_entity_change_below_to_below(self): + """"Test the firing with changed entity.""" self.hass.states.set('test.entity', 9) self.hass.pool.block_till_done() @@ -90,6 +90,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_fires_on_entity_change_above(self): + """"Test the firing with changed entity.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -108,6 +109,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_on_entity_change_below_to_above(self): + """"Test the firing with changed entity.""" # set initial state self.hass.states.set('test.entity', 9) self.hass.pool.block_till_done() @@ -131,6 +133,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_not_fires_on_entity_change_above_to_above(self): + """"Test the firing with changed entity.""" # set initial state self.hass.states.set('test.entity', 11) self.hass.pool.block_till_done() @@ -154,6 +157,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_fires_on_entity_change_below_range(self): + """"Test the firing with changed entity.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -173,6 +177,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_on_entity_change_below_above_range(self): + """"Test the firing with changed entity.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -192,6 +197,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_fires_on_entity_change_over_to_below_range(self): + """"Test the firing with changed entity.""" self.hass.states.set('test.entity', 11) self.hass.pool.block_till_done() @@ -215,6 +221,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_on_entity_change_over_to_below_above_range(self): + """"Test the firing with changed entity.""" self.hass.states.set('test.entity', 11) self.hass.pool.block_till_done() @@ -238,6 +245,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_not_fires_if_entity_not_match(self): + """"Test if not fired with non matching entity.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -255,6 +263,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_fires_on_entity_change_below_with_attribute(self): + """"Test attributes change.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -273,6 +282,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_not_fires_on_entity_change_not_below_with_attribute(self): + """"Test attributes.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -291,6 +301,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_fires_on_attribute_change_with_attribute_below(self): + """"Test attributes change.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -310,6 +321,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_not_fires_on_attribute_change_with_attribute_not_below(self): + """"Test attributes change.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -329,6 +341,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_not_fires_on_entity_change_with_attribute_below(self): + """"Test attributes change.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -348,6 +361,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_not_fires_on_entity_change_with_not_attribute_below(self): + """"Test attributes change.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -367,6 +381,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_fires_on_attr_change_with_attribute_below_and_multiple_attr(self): + """"Test attributes change.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -387,6 +402,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_template_list(self): + """"Test template list.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -408,6 +424,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_template_string(self): + """"Test template string.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -429,6 +446,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_not_fires_on_attr_change_with_attr_not_below_multiple_attr(self): + """"Test if not fired changed attributes.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -449,6 +467,7 @@ class TestAutomationNumericState(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_action(self): + """"Test if action.""" entity_id = 'domain.test_entity' test_state = 10 automation.setup(self.hass, { diff --git a/tests/components/automation/test_state.py b/tests/components/automation/test_state.py index d9c458a151d..17b5f52ebfa 100644 --- a/tests/components/automation/test_state.py +++ b/tests/components/automation/test_state.py @@ -1,9 +1,4 @@ -""" -tests.components.automation.test_state -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests state automation. -""" +"""The test for state automation.""" import unittest from datetime import timedelta from unittest.mock import patch @@ -16,9 +11,10 @@ from tests.common import fire_time_changed, get_test_home_assistant class TestAutomationState(unittest.TestCase): - """ Test the event automation. """ + """Test the event automation.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.states.set('test.entity', 'hello') self.calls = [] @@ -29,10 +25,11 @@ class TestAutomationState(unittest.TestCase): self.hass.services.register('test', 'automation', record_call) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_old_config_if_fires_on_entity_change(self): + """Test for firing if entity change .""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'state', @@ -46,6 +43,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_old_config_if_fires_on_entity_change_with_from_filter(self): + """Test for firing on entity change with filter.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'state', @@ -60,6 +58,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_old_config_if_fires_on_entity_change_with_to_filter(self): + """Test for firing on entity change no filter.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'state', @@ -74,6 +73,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_old_config_if_fires_on_entity_change_with_both_filters(self): + """Test for firing on entity change with both filters.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'state', @@ -89,6 +89,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_old_config_if_not_fires_if_to_filter_not_match(self): + """Test for not firing if no match.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'state', @@ -104,6 +105,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_old_config_if_not_fires_if_from_filter_not_match(self): + """Test for no firing if no match.""" self.hass.states.set('test.entity', 'bye') self.assertTrue(automation.setup(self.hass, { @@ -121,6 +123,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_old_config_if_not_fires_if_entity_not_match(self): + """Test for not firing if no match.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'state', @@ -134,6 +137,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_old_config_if_action(self): + """Test for if action.""" entity_id = 'domain.test_entity' test_state = 'new_state' automation.setup(self.hass, { @@ -162,6 +166,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_on_entity_change(self): + """Test for firing on entity change.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -179,6 +184,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_on_entity_change_with_from_filter(self): + """Test for firing on entity change with filter.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -197,6 +203,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_on_entity_change_with_to_filter(self): + """Test for firing on entity change with no filter.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -215,6 +222,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_on_entity_change_with_state_filter(self): + """Test for firing on entity change with state filter.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -233,6 +241,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_on_entity_change_with_both_filters(self): + """Test for firing if both filters are a non match.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -252,6 +261,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_not_fires_if_to_filter_not_match(self): + """Test for not firing if to filter is not a match.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -271,6 +281,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_not_fires_if_from_filter_not_match(self): + """Test for not firing if from filter is not a match.""" self.hass.states.set('test.entity', 'bye') self.assertTrue(automation.setup(self.hass, { @@ -292,6 +303,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_not_fires_if_entity_not_match(self): + """Test for not firing if entity is not matching.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -309,6 +321,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_action(self): + """Test for to action.""" entity_id = 'domain.test_entity' test_state = 'new_state' automation.setup(self.hass, { @@ -341,6 +354,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fails_setup_if_to_boolean_value(self): + """Test for setup failure for boolean to.""" self.assertFalse(state.trigger( self.hass, { 'platform': 'state', @@ -349,6 +363,7 @@ class TestAutomationState(unittest.TestCase): }, lambda x: x)) def test_if_fails_setup_if_from_boolean_value(self): + """Test for setup failure for boolean from.""" self.assertFalse(state.trigger( self.hass, { 'platform': 'state', @@ -357,6 +372,7 @@ class TestAutomationState(unittest.TestCase): }, lambda x: x)) def test_if_fails_setup_bad_for(self): + """Test for setup failure for bad for.""" self.assertFalse(state.trigger( self.hass, { 'platform': 'state', @@ -368,6 +384,7 @@ class TestAutomationState(unittest.TestCase): }, lambda x: x)) def test_if_fails_setup_for_without_to(self): + """Test for setup failures for missing to.""" self.assertFalse(state.trigger( self.hass, { 'platform': 'state', @@ -378,6 +395,7 @@ class TestAutomationState(unittest.TestCase): }, lambda x: x)) def test_if_not_fires_on_entity_change_with_for(self): + """Test for not firing on entity change with for.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -403,6 +421,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_fires_on_entity_change_with_for(self): + """Test for firing on entity change with for.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -426,6 +445,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_on_for_condition(self): + """Test for firing if contition is on.""" point1 = dt_util.utcnow() point2 = point1 + timedelta(seconds=10) with patch('homeassistant.core.dt_util.utcnow') as mock_utcnow: @@ -464,6 +484,7 @@ class TestAutomationState(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fails_setup_for_without_time(self): + """Test for setup failure if no time is provided.""" self.assertIsNone(state.if_action( self.hass, { 'platform': 'state', @@ -473,6 +494,7 @@ class TestAutomationState(unittest.TestCase): })) def test_if_fails_setup_for_without_entity(self): + """Test for setup failure if no entity is provided.""" self.assertIsNone(state.if_action( self.hass, { 'platform': 'state', diff --git a/tests/components/automation/test_sun.py b/tests/components/automation/test_sun.py index 4083500c293..6b1212b70a6 100644 --- a/tests/components/automation/test_sun.py +++ b/tests/components/automation/test_sun.py @@ -1,9 +1,4 @@ -""" -tests.components.automation.test_sun -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests sun automation. -""" +"""The tests for the sun automation.""" from datetime import datetime import unittest from unittest.mock import patch @@ -16,9 +11,10 @@ from tests.common import fire_time_changed, get_test_home_assistant class TestAutomationSun(unittest.TestCase): - """ Test the sun automation. """ + """Test the sun automation.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.config.components.append('sun') @@ -30,10 +26,11 @@ class TestAutomationSun(unittest.TestCase): self.hass.services.register('test', 'automation', record_call) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_sunset_trigger(self): + """Test the sunset trigger.""" self.hass.states.set(sun.ENTITY_ID, sun.STATE_ABOVE_HORIZON, { sun.STATE_ATTR_NEXT_SETTING: '02:00:00 16-09-2015', }) @@ -60,6 +57,7 @@ class TestAutomationSun(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_sunrise_trigger(self): + """Test the sunrise trigger.""" self.hass.states.set(sun.ENTITY_ID, sun.STATE_ABOVE_HORIZON, { sun.STATE_ATTR_NEXT_RISING: '14:00:00 16-09-2015', }) @@ -86,6 +84,7 @@ class TestAutomationSun(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_sunset_trigger_with_offset(self): + """Test the sunset trigger with offset.""" self.hass.states.set(sun.ENTITY_ID, sun.STATE_ABOVE_HORIZON, { sun.STATE_ATTR_NEXT_SETTING: '02:00:00 16-09-2015', }) @@ -113,6 +112,7 @@ class TestAutomationSun(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_sunrise_trigger_with_offset(self): + """Test the runrise trigger with offset.""" self.hass.states.set(sun.ENTITY_ID, sun.STATE_ABOVE_HORIZON, { sun.STATE_ATTR_NEXT_RISING: '14:00:00 16-09-2015', }) @@ -140,6 +140,7 @@ class TestAutomationSun(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_action_before(self): + """Test if action was before.""" self.hass.states.set(sun.ENTITY_ID, sun.STATE_ABOVE_HORIZON, { sun.STATE_ATTR_NEXT_RISING: '14:00:00 16-09-2015', }) @@ -175,6 +176,7 @@ class TestAutomationSun(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_action_after(self): + """Test if action was after.""" self.hass.states.set(sun.ENTITY_ID, sun.STATE_ABOVE_HORIZON, { sun.STATE_ATTR_NEXT_RISING: '14:00:00 16-09-2015', }) @@ -210,6 +212,7 @@ class TestAutomationSun(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_action_before_with_offset(self): + """Test if action was before offset.""" self.hass.states.set(sun.ENTITY_ID, sun.STATE_ABOVE_HORIZON, { sun.STATE_ATTR_NEXT_RISING: '14:00:00 16-09-2015', }) @@ -246,6 +249,7 @@ class TestAutomationSun(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_action_after_with_offset(self): + """Test if action was after offset.""" self.hass.states.set(sun.ENTITY_ID, sun.STATE_ABOVE_HORIZON, { sun.STATE_ATTR_NEXT_RISING: '14:00:00 16-09-2015', }) @@ -282,6 +286,7 @@ class TestAutomationSun(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_action_before_and_after_during(self): + """Test if action was before and after during.""" self.hass.states.set(sun.ENTITY_ID, sun.STATE_ABOVE_HORIZON, { sun.STATE_ATTR_NEXT_RISING: '10:00:00 16-09-2015', sun.STATE_ATTR_NEXT_SETTING: '15:00:00 16-09-2015', @@ -326,6 +331,7 @@ class TestAutomationSun(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_action_after_different_tz(self): + """Test if action was after in a different timezone.""" import pytz self.hass.states.set(sun.ENTITY_ID, sun.STATE_ABOVE_HORIZON, { diff --git a/tests/components/automation/test_template.py b/tests/components/automation/test_template.py index 489187a496b..315ff37f1ff 100644 --- a/tests/components/automation/test_template.py +++ b/tests/components/automation/test_template.py @@ -1,9 +1,4 @@ -""" -tests.components.automation.test_template -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests template automation. -""" +"""The tests fr the Template automation.""" import unittest import homeassistant.components.automation as automation @@ -12,23 +7,26 @@ from tests.common import get_test_home_assistant class TestAutomationTemplate(unittest.TestCase): - """ Test the event automation. """ + """Test the event automation.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.states.set('test.entity', 'hello') self.calls = [] def record_call(service): + """helper for recording calls.""" self.calls.append(service) self.hass.services.register('test', 'automation', record_call) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_if_fires_on_change_bool(self): + """Test for firing on boolean change.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -46,6 +44,7 @@ class TestAutomationTemplate(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_on_change_str(self): + """Test for firing on change.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -63,6 +62,7 @@ class TestAutomationTemplate(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_on_change_str_crazy(self): + """Test for firing on change.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -80,6 +80,7 @@ class TestAutomationTemplate(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_not_fires_on_change_bool(self): + """Test for not firing on boolean change.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -97,6 +98,7 @@ class TestAutomationTemplate(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_not_fires_on_change_str(self): + """Test for not firing on string change.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -114,6 +116,7 @@ class TestAutomationTemplate(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_not_fires_on_change_str_crazy(self): + """Test for not firing on string change.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -131,6 +134,7 @@ class TestAutomationTemplate(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_fires_on_no_change(self): + """Test for firing on no change.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -148,6 +152,7 @@ class TestAutomationTemplate(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_fires_on_two_change(self): + """Test for firing on two changes.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -171,6 +176,7 @@ class TestAutomationTemplate(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_on_change_with_template(self): + """Test for firing on change with template.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -188,6 +194,7 @@ class TestAutomationTemplate(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_not_fires_on_change_with_template(self): + """Test for not firing on change with template.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -205,6 +212,7 @@ class TestAutomationTemplate(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_fires_on_change_with_template_advanced(self): + """Test for firing on change with template advanced.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -226,6 +234,7 @@ class TestAutomationTemplate(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_on_no_change_with_template_advanced(self): + """Test for firing on no change with template advanced.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -253,6 +262,7 @@ class TestAutomationTemplate(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_fires_on_change_with_template_2(self): + """Test for firing on change with template.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -291,6 +301,7 @@ class TestAutomationTemplate(unittest.TestCase): self.assertEqual(2, len(self.calls)) def test_if_action(self): + """Test for firing if action.""" automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -323,6 +334,7 @@ class TestAutomationTemplate(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_on_change_with_bad_template(self): + """Test for firing on change with bad template.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -340,6 +352,7 @@ class TestAutomationTemplate(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_fires_on_change_with_bad_template_2(self): + """Test for firing on change with bad template.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { diff --git a/tests/components/automation/test_time.py b/tests/components/automation/test_time.py index 41e200a5731..824d611f4fb 100644 --- a/tests/components/automation/test_time.py +++ b/tests/components/automation/test_time.py @@ -1,9 +1,4 @@ -""" -tests.components.automation.test_time -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests time automation. -""" +"""The tests for the time automation.""" from datetime import timedelta import unittest from unittest.mock import patch @@ -17,9 +12,10 @@ from tests.common import fire_time_changed, get_test_home_assistant class TestAutomationTime(unittest.TestCase): - """ Test the event automation. """ + """Test the event automation.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.calls = [] @@ -29,10 +25,11 @@ class TestAutomationTime(unittest.TestCase): self.hass.services.register('test', 'automation', record_call) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_old_config_if_fires_when_hour_matches(self): + """Test for firing if hours are matching.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'time', @@ -48,6 +45,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_old_config_if_fires_when_minute_matches(self): + """Test for firing if minutes are matching.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'time', @@ -63,6 +61,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_old_config_if_fires_when_second_matches(self): + """Test for firing if seconds are matching.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'platform': 'time', @@ -78,6 +77,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_old_config_if_fires_when_all_matches(self): + """Test for firing if everything matches.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { CONF_PLATFORM: 'time', @@ -96,6 +96,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_old_config_if_action_before(self): + """Test for action before.""" automation.setup(self.hass, { automation.DOMAIN: { CONF_PLATFORM: 'event', @@ -126,6 +127,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_old_config_if_action_after(self): + """Test for action after.""" automation.setup(self.hass, { automation.DOMAIN: { CONF_PLATFORM: 'event', @@ -156,6 +158,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_old_config_if_action_one_weekday(self): + """Test for action with one weekday.""" automation.setup(self.hass, { automation.DOMAIN: { CONF_PLATFORM: 'event', @@ -187,6 +190,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_old_config_if_action_list_weekday(self): + """Test for action with a list of weekdays.""" automation.setup(self.hass, { automation.DOMAIN: { CONF_PLATFORM: 'event', @@ -226,6 +230,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(2, len(self.calls)) def test_if_fires_when_hour_matches(self): + """Test for firing if hour is matching.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -244,6 +249,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_when_minute_matches(self): + """Test for firing if minutes are matching.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -262,6 +268,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_when_second_matches(self): + """Test for firing if seconds are matching.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -280,6 +287,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_when_all_matches(self): + """Test for firing if everything matches.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -301,6 +309,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_periodic_seconds(self): + """Test for firing periodically every second.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -320,6 +329,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_periodic_minutes(self): + """Test for firing periodically every minute.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -339,6 +349,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_periodic_hours(self): + """Test for firing periodically every hour.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -358,6 +369,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_fires_using_after(self): + """Test for firing after.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -377,6 +389,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_not_working_if_no_values_in_conf_provided(self): + """Test for failure if no configuration.""" self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -396,8 +409,10 @@ class TestAutomationTime(unittest.TestCase): @patch('homeassistant.components.automation.time._LOGGER.error') def test_if_not_fires_using_wrong_after(self, mock_error): - """ YAML translates time values to total seconds. This should break the - before rule. """ + """YAML translates time values to total seconds. + + This should break the before rule. + """ self.assertTrue(automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -419,6 +434,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(2, mock_error.call_count) def test_if_action_before(self): + """Test for if action before.""" automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -453,6 +469,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_action_after(self): + """Test for if action after.""" automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -487,6 +504,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_action_one_weekday(self): + """Test for if action with one weekday.""" automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { @@ -522,6 +540,7 @@ class TestAutomationTime(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_action_list_weekday(self): + """Test for action with a list of weekdays.""" automation.setup(self.hass, { automation.DOMAIN: { 'trigger': { diff --git a/tests/components/automation/test_zone.py b/tests/components/automation/test_zone.py index 12bd35c8ae4..b9ec1c9e727 100644 --- a/tests/components/automation/test_zone.py +++ b/tests/components/automation/test_zone.py @@ -1,9 +1,4 @@ -""" -tests.components.automation.test_zone -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests location automation. -""" +"""The tests for the location automation.""" import unittest from homeassistant.components import automation, zone @@ -12,9 +7,10 @@ from tests.common import get_test_home_assistant class TestAutomationZone(unittest.TestCase): - """ Test the event automation. """ + """Test the event automation.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() zone.setup(self.hass, { 'zone': { @@ -33,10 +29,11 @@ class TestAutomationZone(unittest.TestCase): self.hass.services.register('test', 'automation', record_call) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_if_fires_on_zone_enter(self): + """Test for firing on zone enter.""" self.hass.states.set('test.entity', 'hello', { 'latitude': 32.881011, 'longitude': -117.234758 @@ -66,6 +63,7 @@ class TestAutomationZone(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_not_fires_for_enter_on_zone_leave(self): + """Test for not firing on zone leave.""" self.hass.states.set('test.entity', 'hello', { 'latitude': 32.880586, 'longitude': -117.237564 @@ -95,6 +93,7 @@ class TestAutomationZone(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_if_fires_on_zone_leave(self): + """Test for firing on zone leave.""" self.hass.states.set('test.entity', 'hello', { 'latitude': 32.880586, 'longitude': -117.237564 @@ -124,6 +123,7 @@ class TestAutomationZone(unittest.TestCase): self.assertEqual(1, len(self.calls)) def test_if_not_fires_for_leave_on_zone_enter(self): + """Test for not firing on zone enter.""" self.hass.states.set('test.entity', 'hello', { 'latitude': 32.881011, 'longitude': -117.234758 @@ -153,6 +153,7 @@ class TestAutomationZone(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_zone_condition(self): + """Test for zone condition.""" self.hass.states.set('test.entity', 'hello', { 'latitude': 32.880586, 'longitude': -117.237564 diff --git a/tests/components/binary_sensor/__init__.py b/tests/components/binary_sensor/__init__.py index e69de29bb2d..93fe178e2d4 100644 --- a/tests/components/binary_sensor/__init__.py +++ b/tests/components/binary_sensor/__init__.py @@ -0,0 +1 @@ +"""The tests for Binary sensor platforms.""" diff --git a/tests/components/binary_sensor/test_binary_sensor.py b/tests/components/binary_sensor/test_binary_sensor.py index db5f09fdf6d..96dda5ab3bb 100644 --- a/tests/components/binary_sensor/test_binary_sensor.py +++ b/tests/components/binary_sensor/test_binary_sensor.py @@ -1,8 +1,4 @@ -""" -tests.components.binary_sensor.test_binary_sensor -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Test the binary_sensor base class -""" +"""The tests for the Binary sensor component.""" import unittest from unittest import mock diff --git a/tests/components/binary_sensor/test_command_line.py b/tests/components/binary_sensor/test_command_line.py index 2e3dfb2795b..4aae3079a07 100644 --- a/tests/components/binary_sensor/test_command_line.py +++ b/tests/components/binary_sensor/test_command_line.py @@ -1,9 +1,4 @@ -""" -tests.components.binary_sensor.command_line -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests command binary sensor. -""" +"""The tests fr the Command line Binary sensor platform.""" import unittest from homeassistant.const import (STATE_ON, STATE_OFF) @@ -13,17 +8,18 @@ from tests.common import get_test_home_assistant class TestCommandSensorBinarySensor(unittest.TestCase): - """ Test the Template sensor. """ + """Test the Command line Binary sensor.""" def setUp(self): + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def tearDown(self): - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_setup(self): - """ Test sensor setup """ + """Test sensor setup.""" config = {'name': 'Test', 'command': 'echo 1', 'payload_on': '1', @@ -31,7 +27,7 @@ class TestCommandSensorBinarySensor(unittest.TestCase): devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add callback to add devices.""" for dev in devs: devices.append(dev) @@ -44,13 +40,13 @@ class TestCommandSensorBinarySensor(unittest.TestCase): self.assertEqual(STATE_ON, entity.state) def test_setup_bad_config(self): - """ Test setup with a bad config """ + """Test the setup with a bad configuration.""" config = {} devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add callback to add devices.""" for dev in devs: devices.append(dev) @@ -60,7 +56,7 @@ class TestCommandSensorBinarySensor(unittest.TestCase): self.assertEqual(0, len(devices)) def test_template(self): - """ Test command sensor with template """ + """Test setting the state with a template.""" data = command_line.CommandSensorData('echo 10') entity = command_line.CommandBinarySensor( @@ -69,7 +65,7 @@ class TestCommandSensorBinarySensor(unittest.TestCase): self.assertEqual(STATE_ON, entity.state) def test_sensor_off(self): - """ Test command sensor with template """ + """Test setting the state with a template.""" data = command_line.CommandSensorData('echo 0') entity = command_line.CommandBinarySensor( diff --git a/tests/components/binary_sensor/test_mqtt.py b/tests/components/binary_sensor/test_mqtt.py index f030800e95b..27ecad2e566 100644 --- a/tests/components/binary_sensor/test_mqtt.py +++ b/tests/components/binary_sensor/test_mqtt.py @@ -1,9 +1,4 @@ -""" -tests.components.binary_sensor.test_mqtt -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests MQTT binary sensor. -""" +"""The tests for the MQTT binary sensor platform.""" import unittest import homeassistant.components.binary_sensor as binary_sensor @@ -14,17 +9,19 @@ from tests.common import get_test_home_assistant class TestSensorMQTT(unittest.TestCase): - """ Test the MQTT sensor. """ + """Test the MQTT sensor.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() mock_mqtt_component(self.hass) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_setting_sensor_value_via_mqtt_message(self): + """Test the setting of the value via MQTT.""" self.assertTrue(binary_sensor.setup(self.hass, { 'binary_sensor': { 'platform': 'mqtt', diff --git a/tests/components/binary_sensor/test_nx584.py b/tests/components/binary_sensor/test_nx584.py index dcf35850044..21323702447 100644 --- a/tests/components/binary_sensor/test_nx584.py +++ b/tests/components/binary_sensor/test_nx584.py @@ -1,9 +1,4 @@ -""" -tests.components.binary_sensor.nx584 -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Tests for nx584 sensor. -""" - +"""The tests for the nx584 sensor platform.""" import requests import unittest from unittest import mock @@ -13,11 +8,16 @@ from nx584 import client as nx584_client class StopMe(Exception): + """Stop helper.""" + pass class TestNX584SensorSetup(unittest.TestCase): + """Test the nx584 sensor platform.""" + def setUp(self): + """Setup things to be run when tests are started.""" self._mock_client = mock.patch.object(nx584_client, 'Client') self._mock_client.start() @@ -32,11 +32,13 @@ class TestNX584SensorSetup(unittest.TestCase): client.get_version.return_value = '1.1' def tearDown(self): + """Stop everything that was started.""" self._mock_client.stop() @mock.patch('homeassistant.components.binary_sensor.nx584.NX584Watcher') @mock.patch('homeassistant.components.binary_sensor.nx584.NX584ZoneSensor') def test_setup_no_config(self, mock_nx, mock_watcher): + """Test the setup with no configuration.""" add_devices = mock.MagicMock() hass = mock.MagicMock() self.assertTrue(nx584.setup_platform(hass, {}, add_devices)) @@ -49,6 +51,7 @@ class TestNX584SensorSetup(unittest.TestCase): @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:123', 'exclude_zones': [2], @@ -66,12 +69,14 @@ class TestNX584SensorSetup(unittest.TestCase): self.assertTrue(mock_watcher.called) def _test_assert_graceful_fail(self, config): + """Test the failing.""" hass = add_devices = mock.MagicMock() self.assertFalse(nx584.setup_platform(hass, config, add_devices)) self.assertFalse(add_devices.called) def test_setup_bad_config(self): + """Test the setup with bad configuration.""" bad_configs = [ {'exclude_zones': ['a']}, {'zone_types': {'a': 'b'}}, @@ -82,15 +87,18 @@ class TestNX584SensorSetup(unittest.TestCase): 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_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 = [] hass = add_devices = mock.MagicMock() self.assertTrue(nx584.setup_platform(hass, {}, @@ -99,7 +107,10 @@ class TestNX584SensorSetup(unittest.TestCase): 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') self.assertEqual('foo', sensor.name) @@ -111,8 +122,11 @@ class TestNX584ZoneSensor(unittest.TestCase): class TestNX584Watcher(unittest.TestCase): + """Test the nx584 watcher.""" + @mock.patch.object(nx584.NX584ZoneSensor, '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 = { @@ -126,15 +140,17 @@ class TestNX584Watcher(unittest.TestCase): @mock.patch.object(nx584.NX584ZoneSensor, '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}) self.assertFalse(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""" + """Return nothing twice, then some events.""" if empty_me: empty_me.pop() else: @@ -159,6 +175,7 @@ class TestNX584Watcher(unittest.TestCase): @mock.patch('time.sleep') def test_run_retries_failures(self, mock_sleep): + """Test the retries with failures.""" empty_me = [1, 2] def fake_run(): diff --git a/tests/components/binary_sensor/test_tcp.py b/tests/components/binary_sensor/test_tcp.py index ad2b97510bf..ea06d69bebc 100644 --- a/tests/components/binary_sensor/test_tcp.py +++ b/tests/components/binary_sensor/test_tcp.py @@ -1,9 +1,4 @@ -""" -tests.components.sensor.tcp -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests TCP sensor. -""" +"""The tests for the TCP binary sensor platform.""" from copy import copy from unittest.mock import patch, Mock @@ -15,7 +10,7 @@ from tests.components.sensor import test_tcp @patch('homeassistant.components.sensor.tcp.Sensor.update') def test_setup_platform_valid_config(mock_update): - """ Should check the supplied config and call add_entities with Sensor. """ + """Should 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, "setup_platform() should return None if successful." @@ -24,23 +19,25 @@ def test_setup_platform_valid_config(mock_update): def test_setup_platform_invalid_config(): - """ Should check the supplied config and return False if it is invalid. """ + """Should check the supplied config and return False if it is invalid.""" config = copy(test_tcp.TEST_CONFIG) del config[tcp.CONF_HOST] assert bin_tcp.setup_platform(None, config, None) is False class TestTCPBinarySensor(): - """ Test the TCP Binary Sensor. """ + """Test the TCP Binary Sensor.""" def setup_class(cls): + """Setup things to be run when tests are started.""" cls.hass = get_test_home_assistant() def teardown_class(cls): + """Stop down everything that was started.""" cls.hass.stop() def test_requires_additional_values(self): - """ Should require the additional config values specified. """ + """Should require the additional config values specified.""" config = copy(test_tcp.TEST_CONFIG) for key in bin_tcp.BinarySensor.required: del config[key] @@ -49,14 +46,14 @@ class TestTCPBinarySensor(): @patch('homeassistant.components.sensor.tcp.Sensor.update') def test_is_on_true(self, mock_update): - """ Should return True if _state is the same as value_on. """ + """Should return True if _state is the same as value_on.""" sensor = bin_tcp.BinarySensor(self.hass, test_tcp.TEST_CONFIG) sensor._state = test_tcp.TEST_CONFIG[tcp.CONF_VALUE_ON] assert sensor.is_on @patch('homeassistant.components.sensor.tcp.Sensor.update') def test_is_on_false(self, mock_update): - """ Should return False if _state is not the same as value_on. """ + """Should return False if _state is not the same as value_on.""" sensor = bin_tcp.BinarySensor(self.hass, test_tcp.TEST_CONFIG) sensor._state = "%s abc" % test_tcp.TEST_CONFIG[tcp.CONF_VALUE_ON] assert not sensor.is_on diff --git a/tests/components/binary_sensor/test_template.py b/tests/components/binary_sensor/test_template.py index 7fc18a930f1..411cf1b4fa3 100644 --- a/tests/components/binary_sensor/test_template.py +++ b/tests/components/binary_sensor/test_template.py @@ -1,9 +1,4 @@ -""" -tests.components.binary_sensor.test_template -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Tests for template binary_sensor. -""" - +"""The tests for the Template Binary sensor platform.""" import unittest from unittest import mock @@ -12,8 +7,11 @@ from homeassistant.exceptions import TemplateError class TestBinarySensorTemplate(unittest.TestCase): + """Test for Binary sensor template platform.""" + @mock.patch.object(template, 'BinarySensorTemplate') def test_setup(self, mock_template): + """"Test the setup.""" config = { 'sensors': { 'test': { @@ -32,11 +30,13 @@ class TestBinarySensorTemplate(unittest.TestCase): add_devices.assert_called_once_with([mock_template.return_value]) def test_setup_no_sensors(self): + """"Test setup with no sensors.""" config = {} result = template.setup_platform(None, config, None) self.assertFalse(result) def test_setup_invalid_device(self): + """"Test the setup with invalid devices.""" config = { 'sensors': { 'foo bar': {}, @@ -46,6 +46,7 @@ class TestBinarySensorTemplate(unittest.TestCase): self.assertFalse(result) def test_setup_invalid_sensor_class(self): + """"Test setup with invalid sensor class.""" config = { 'sensors': { 'test': { @@ -58,6 +59,7 @@ class TestBinarySensorTemplate(unittest.TestCase): self.assertFalse(result) def test_setup_invalid_missing_template(self): + """"Test setup with invalid and missing template.""" config = { 'sensors': { 'test': { @@ -69,6 +71,7 @@ class TestBinarySensorTemplate(unittest.TestCase): self.assertFalse(result) def test_attributes(self): + """"Test the attributes.""" hass = mock.MagicMock() vs = template.BinarySensorTemplate(hass, 'parent', 'Parent', 'motion', '{{ 1 > 1 }}') @@ -84,6 +87,7 @@ class TestBinarySensorTemplate(unittest.TestCase): self.assertTrue(vs.is_on) def test_event(self): + """"Test the event.""" hass = mock.MagicMock() vs = template.BinarySensorTemplate(hass, 'parent', 'Parent', 'motion', '{{ 1 > 1 }}') @@ -92,6 +96,7 @@ class TestBinarySensorTemplate(unittest.TestCase): mock_update.assert_called_once_with(True) def test_update(self): + """"Test the update.""" hass = mock.MagicMock() vs = template.BinarySensorTemplate(hass, 'parent', 'Parent', 'motion', '{{ 2 > 1 }}') @@ -101,6 +106,7 @@ class TestBinarySensorTemplate(unittest.TestCase): @mock.patch('homeassistant.helpers.template.render') def test_update_template_error(self, mock_render): + """"Test the template update error.""" hass = mock.MagicMock() vs = template.BinarySensorTemplate(hass, 'parent', 'Parent', 'motion', '{{ 1 > 1 }}') diff --git a/tests/components/camera/__init__.py b/tests/components/camera/__init__.py new file mode 100644 index 00000000000..c3bebfeb2f0 --- /dev/null +++ b/tests/components/camera/__init__.py @@ -0,0 +1 @@ +"""The tests for camera platforms.""" diff --git a/tests/components/camera/test_uvc.py b/tests/components/camera/test_uvc.py index 199fec4cc04..ccc50523589 100644 --- a/tests/components/camera/test_uvc.py +++ b/tests/components/camera/test_uvc.py @@ -1,9 +1,4 @@ -""" -tests.components.camera.test_uvc -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Tests for uvc camera module. -""" - +"""The tests for UVC camera module.""" import socket import unittest from unittest import mock @@ -16,9 +11,12 @@ from homeassistant.components.camera import uvc class TestUVCSetup(unittest.TestCase): + """Test the UVC camera platform.""" + @mock.patch('uvcclient.nvr.UVCRemote') @mock.patch.object(uvc, 'UnifiVideoCamera') def test_setup_full_config(self, mock_uvc, mock_remote): + """"Test the setup with full configuration.""" config = { 'nvr': 'foo', 'port': 123, @@ -31,6 +29,7 @@ class TestUVCSetup(unittest.TestCase): ] def fake_get_camera(uuid): + """"Create a fake camera.""" if uuid == 'three': return {'model': 'airCam'} else: @@ -52,6 +51,7 @@ class TestUVCSetup(unittest.TestCase): @mock.patch('uvcclient.nvr.UVCRemote') @mock.patch.object(uvc, 'UnifiVideoCamera') def test_setup_partial_config(self, mock_uvc, mock_remote): + """"Test the setup with partial configuration.""" config = { 'nvr': 'foo', 'key': 'secret', @@ -74,6 +74,7 @@ class TestUVCSetup(unittest.TestCase): ]) def test_setup_incomplete_config(self): + """"Test the setup with incomplete configuration.""" self.assertFalse(uvc.setup_platform( None, {'nvr': 'foo'}, None)) self.assertFalse(uvc.setup_platform( @@ -83,6 +84,7 @@ class TestUVCSetup(unittest.TestCase): @mock.patch('uvcclient.nvr.UVCRemote') def test_setup_nvr_errors(self, mock_remote): + """"Test for NVR errors.""" errors = [nvr.NotAuthorized, nvr.NvrError, requests.exceptions.ConnectionError] config = { @@ -95,7 +97,10 @@ class TestUVCSetup(unittest.TestCase): class TestUVC(unittest.TestCase): + """Test class for UVC.""" + def setup_method(self, method): + """"Setup the mock camera.""" self.nvr = mock.MagicMock() self.uuid = 'uuid' self.name = 'name' @@ -111,6 +116,7 @@ class TestUVC(unittest.TestCase): } def test_properties(self): + """"Test the properties.""" self.assertEqual(self.name, self.uvc.name) self.assertTrue(self.uvc.is_recording) self.assertEqual('Ubiquiti', self.uvc.brand) @@ -119,6 +125,7 @@ class TestUVC(unittest.TestCase): @mock.patch('uvcclient.store.get_info_store') @mock.patch('uvcclient.camera.UVCCameraClient') def test_login(self, mock_camera, mock_store): + """"Test the login.""" mock_store.return_value.get_camera_password.return_value = 'seekret' self.uvc._login() mock_camera.assert_called_once_with('host-a', 'admin', 'seekret') @@ -127,6 +134,7 @@ class TestUVC(unittest.TestCase): @mock.patch('uvcclient.store.get_info_store') @mock.patch('uvcclient.camera.UVCCameraClient') def test_login_no_password(self, mock_camera, mock_store): + """"Test the login with no password.""" mock_store.return_value.get_camera_password.return_value = None self.uvc._login() mock_camera.assert_called_once_with('host-a', 'admin', 'ubnt') @@ -135,6 +143,7 @@ class TestUVC(unittest.TestCase): @mock.patch('uvcclient.store.get_info_store') @mock.patch('uvcclient.camera.UVCCameraClient') def test_login_tries_both_addrs_and_caches(self, mock_camera, mock_store): + """"Test the login tries.""" responses = [0] def fake_login(*a): @@ -158,27 +167,32 @@ class TestUVC(unittest.TestCase): @mock.patch('uvcclient.store.get_info_store') @mock.patch('uvcclient.camera.UVCCameraClient') def test_login_fails_both_properly(self, mock_camera, mock_store): + """"Test if login fails properly.""" mock_camera.return_value.login.side_effect = socket.error self.assertEqual(None, self.uvc._login()) self.assertEqual(None, self.uvc._connect_addr) def test_camera_image_tries_login_bails_on_failure(self): + """"Test retrieving failure.""" with mock.patch.object(self.uvc, '_login') as mock_login: mock_login.return_value = False self.assertEqual(None, self.uvc.camera_image()) mock_login.assert_called_once_with() def test_camera_image_logged_in(self): + """"Test the login state.""" self.uvc._camera = mock.MagicMock() self.assertEqual(self.uvc._camera.get_snapshot.return_value, self.uvc.camera_image()) def test_camera_image_error(self): + """"Test the camera image error.""" self.uvc._camera = mock.MagicMock() self.uvc._camera.get_snapshot.side_effect = camera.CameraConnectError self.assertEqual(None, self.uvc.camera_image()) def test_camera_image_reauths(self): + """"Test the re-authentication.""" responses = [0] def fake_snapshot(): @@ -197,6 +211,7 @@ class TestUVC(unittest.TestCase): self.assertEqual([], responses) def test_camera_image_reauths_only_once(self): + """"Test if the re-authentication only happens once.""" self.uvc._camera = mock.MagicMock() self.uvc._camera.get_snapshot.side_effect = camera.CameraAuthError with mock.patch.object(self.uvc, '_login') as mock_login: diff --git a/tests/components/device_tracker/__init__.py b/tests/components/device_tracker/__init__.py index e69de29bb2d..33ba33e2645 100644 --- a/tests/components/device_tracker/__init__.py +++ b/tests/components/device_tracker/__init__.py @@ -0,0 +1 @@ +"""The tests for Device tracker platforms.""" diff --git a/tests/components/device_tracker/test_init.py b/tests/components/device_tracker/test_init.py index c106163d0d1..8cd3df96198 100644 --- a/tests/components/device_tracker/test_init.py +++ b/tests/components/device_tracker/test_init.py @@ -1,4 +1,4 @@ -"""Tests for the device tracker compoment.""" +"""The tests for the device tracker component.""" # pylint: disable=protected-access,too-many-public-methods import unittest from unittest.mock import patch @@ -17,15 +17,15 @@ from tests.common import ( class TestComponentsDeviceTracker(unittest.TestCase): - """ Tests homeassistant.components.device_tracker module. """ + """Test the Device tracker.""" def setUp(self): # pylint: disable=invalid-name - """ Init needed objects. """ + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.yaml_devices = self.hass.config.path(device_tracker.YAML_DEVICES) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" try: os.remove(self.yaml_devices) except FileNotFoundError: @@ -34,7 +34,7 @@ class TestComponentsDeviceTracker(unittest.TestCase): self.hass.stop() def test_is_on(self): - """ Test is_on method. """ + """Test is_on method.""" entity_id = device_tracker.ENTITY_ID_FORMAT.format('test') self.hass.states.set(entity_id, STATE_HOME) @@ -46,6 +46,7 @@ class TestComponentsDeviceTracker(unittest.TestCase): self.assertFalse(device_tracker.is_on(self.hass, entity_id)) def test_reading_yaml_config(self): + """Test the rendering of the YAML configuration.""" dev_id = 'test' device = device_tracker.Device( self.hass, timedelta(seconds=180), 0, True, dev_id, @@ -62,9 +63,11 @@ class TestComponentsDeviceTracker(unittest.TestCase): self.assertEqual(device.consider_home, config.consider_home) def test_setup_without_yaml_file(self): + """Test with no YAML file.""" self.assertTrue(device_tracker.setup(self.hass, {})) def test_adding_unknown_device_to_config(self): + """Test the adding of unknown devices to configuration file.""" scanner = get_component('device_tracker.test').SCANNER scanner.reset() scanner.come_home('DEV1') @@ -78,6 +81,7 @@ class TestComponentsDeviceTracker(unittest.TestCase): assert config[0].track def test_discovery(self): + """Test discovery.""" scanner = get_component('device_tracker.test').SCANNER with patch.dict(device_tracker.DISCOVERY_PLATFORMS, {'test': 'test'}): @@ -88,6 +92,7 @@ class TestComponentsDeviceTracker(unittest.TestCase): self.assertTrue(mock_scan.called) def test_update_stale(self): + """Test stalled update.""" scanner = get_component('device_tracker.test').SCANNER scanner.reset() scanner.come_home('DEV1') @@ -117,6 +122,7 @@ class TestComponentsDeviceTracker(unittest.TestCase): self.hass.states.get('device_tracker.dev1').state) def test_entity_attributes(self): + """Test the entity attributes.""" dev_id = 'test_entity' entity_id = device_tracker.ENTITY_ID_FORMAT.format(dev_id) friendly_name = 'Paulus' @@ -135,6 +141,7 @@ class TestComponentsDeviceTracker(unittest.TestCase): self.assertEqual(picture, attrs.get(ATTR_ENTITY_PICTURE)) def test_device_hidden(self): + """Test hidden devices.""" dev_id = 'test_entity' entity_id = device_tracker.ENTITY_ID_FORMAT.format(dev_id) device = device_tracker.Device( @@ -152,6 +159,7 @@ class TestComponentsDeviceTracker(unittest.TestCase): .attributes.get(ATTR_HIDDEN)) def test_group_all_devices(self): + """Test grouping of devices.""" dev_id = 'test_entity' entity_id = device_tracker.ENTITY_ID_FORMAT.format(dev_id) device = device_tracker.Device( @@ -173,6 +181,7 @@ class TestComponentsDeviceTracker(unittest.TestCase): @patch('homeassistant.components.device_tracker.DeviceTracker.see') def test_see_service(self, mock_see): + """Test the see service.""" self.assertTrue(device_tracker.setup(self.hass, {})) mac = 'AB:CD:EF:GH' dev_id = 'some_device' diff --git a/tests/components/device_tracker/test_locative.py b/tests/components/device_tracker/test_locative.py index 5e8babca2d9..811e9df4314 100644 --- a/tests/components/device_tracker/test_locative.py +++ b/tests/components/device_tracker/test_locative.py @@ -1,9 +1,4 @@ -""" -tests.components.device_tracker.test_locative -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests the locative device tracker component. -""" +"""The tests the for Locative device tracker platform.""" import unittest from unittest.mock import patch @@ -22,19 +17,17 @@ hass = None def _url(data={}): - """ Helper method to generate urls. """ + """Helper method to generate URLs.""" data = "&".join(["{}={}".format(name, value) for name, value in data.items()]) return "{}{}locative?{}".format(HTTP_BASE_URL, const.URL_API, data) def setUpModule(): # pylint: disable=invalid-name - """ Initalizes a Home Assistant server. """ + """Initalize a Home Assistant server.""" global hass hass = get_test_home_assistant() - - # Set up server bootstrap.setup_component(hass, http.DOMAIN, { http.DOMAIN: { http.CONF_SERVER_PORT: SERVER_PORT @@ -55,19 +48,21 @@ def setUpModule(): # pylint: disable=invalid-name def tearDownModule(): # pylint: disable=invalid-name - """ Stops the Home Assistant server. """ + """Stop the Home Assistant server.""" hass.stop() # Stub out update_config or else Travis CI raises an exception @patch('homeassistant.components.device_tracker.update_config') class TestLocative(unittest.TestCase): - """ Test Locative """ + """Test Locative platform.""" def tearDown(self): + """Stop everything that was started.""" hass.pool.block_till_done() def test_missing_data(self, update_config): + """Test missing data.""" data = { 'latitude': 1.0, 'longitude': 1.1, @@ -117,7 +112,7 @@ class TestLocative(unittest.TestCase): self.assertEqual(422, req.status_code) def test_enter_and_exit(self, update_config): - """ Test when there is a known zone """ + """Test when there is a known zone.""" data = { 'latitude': 40.7855, 'longitude': -111.7367, @@ -173,8 +168,7 @@ class TestLocative(unittest.TestCase): self.assertEqual(state_name, 'work') def test_exit_after_enter(self, update_config): - """ Test when an exit message comes after an enter message """ - + """Test when an exit message comes after an enter message.""" data = { 'latitude': 40.7855, 'longitude': -111.7367, @@ -213,8 +207,7 @@ class TestLocative(unittest.TestCase): self.assertEqual(state.state, 'work') def test_exit_first(self, update_config): - """ Test when an exit message is sent first on a new device """ - + """Test when an exit message is sent first on a new device.""" data = { 'latitude': 40.7855, 'longitude': -111.7367, diff --git a/tests/components/device_tracker/test_mqtt.py b/tests/components/device_tracker/test_mqtt.py index 8a00ed7dae1..7b6024c60f1 100644 --- a/tests/components/device_tracker/test_mqtt.py +++ b/tests/components/device_tracker/test_mqtt.py @@ -1,9 +1,4 @@ -""" -tests.components.device_tracker.test_mqtt -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests the MQTT device tracker component. -""" +"""The tests for the MQTT device tracker platform.""" import unittest import os @@ -15,19 +10,22 @@ from tests.common import ( class TestComponentsDeviceTrackerMQTT(unittest.TestCase): + """Test MQTT device tracker platform.""" + def setUp(self): # pylint: disable=invalid-name - """ Init needed objects. """ + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() mock_mqtt_component(self.hass) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" try: os.remove(self.hass.config.path(device_tracker.YAML_DEVICES)) except FileNotFoundError: pass def test_new_message(self): + """Test new message.""" dev_id = 'paulus' enttiy_id = device_tracker.ENTITY_ID_FORMAT.format(dev_id) topic = '/location/paulus' diff --git a/tests/components/device_tracker/test_owntracks.py b/tests/components/device_tracker/test_owntracks.py index 4886d02c860..98e9349ca00 100644 --- a/tests/components/device_tracker/test_owntracks.py +++ b/tests/components/device_tracker/test_owntracks.py @@ -1,9 +1,4 @@ -""" -tests.components.device_tracker.test_owntracks -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests Owntracks device tracker. -""" +"""The tests for the Owntracks device tracker.""" import json import os import unittest @@ -11,9 +6,7 @@ import unittest from collections import defaultdict from homeassistant.components import device_tracker - from homeassistant.const import (STATE_NOT_HOME, CONF_PLATFORM) - import homeassistant.components.device_tracker.owntracks as owntracks from tests.common import ( @@ -101,10 +94,10 @@ REGION_LEAVE_INACCURATE_MESSAGE = { class TestDeviceTrackerOwnTracks(unittest.TestCase): - """ Test the Template sensor. """ + """Test the OwnTrack sensor.""" def setup_method(self, method): - """ Init needed objects. """ + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() mock_mqtt_component(self.hass) self.assertTrue(device_tracker.setup(self.hass, { @@ -155,7 +148,7 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase): owntracks.MOBILE_BEACONS_ACTIVE = defaultdict(list) def teardown_method(self, method): - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() try: @@ -164,39 +157,48 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase): pass def send_message(self, topic, message): + """Test the sending of a message.""" fire_mqtt_message( self.hass, topic, json.dumps(message)) self.hass.pool.block_till_done() def assert_location_state(self, location): + """Test the assertion of a location state.""" state = self.hass.states.get(DEVICE_TRACKER_STATE) self.assertEqual(state.state, location) def assert_location_latitude(self, latitude): + """Test the assertion of a location latitude.""" state = self.hass.states.get(DEVICE_TRACKER_STATE) self.assertEqual(state.attributes.get('latitude'), latitude) def assert_location_longitude(self, longitude): + """Test the assertion of a location longitude.""" state = self.hass.states.get(DEVICE_TRACKER_STATE) self.assertEqual(state.attributes.get('longitude'), longitude) def assert_location_accuracy(self, accuracy): + """Test the assertion of a location accuracy.""" state = self.hass.states.get(DEVICE_TRACKER_STATE) self.assertEqual(state.attributes.get('gps_accuracy'), accuracy) def assert_tracker_state(self, location): + """Test the assertion of a tracker state.""" state = self.hass.states.get(REGION_TRACKER_STATE) self.assertEqual(state.state, location) def assert_tracker_latitude(self, latitude): + """Test the assertion of a tracker latitude.""" state = self.hass.states.get(REGION_TRACKER_STATE) self.assertEqual(state.attributes.get('latitude'), latitude) def assert_tracker_accuracy(self, accuracy): + """Test the assertion of a tracker accuracy.""" state = self.hass.states.get(REGION_TRACKER_STATE) self.assertEqual(state.attributes.get('gps_accuracy'), accuracy) def test_location_update(self): + """Test the update of a location.""" self.send_message(LOCATION_TOPIC, LOCATION_MESSAGE) self.assert_location_latitude(2.0) @@ -204,6 +206,7 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase): self.assert_location_state('outer') def test_location_inaccurate_gps(self): + """Test the location for inaccurate GPS information.""" self.send_message(LOCATION_TOPIC, LOCATION_MESSAGE) self.send_message(LOCATION_TOPIC, LOCATION_MESSAGE_INACCURATE) @@ -211,6 +214,7 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase): self.assert_location_longitude(1.0) def test_event_entry_exit(self): + """Test the entry event.""" self.send_message(EVENT_TOPIC, REGION_ENTER_MESSAGE) # Enter uses the zone's gps co-ords @@ -236,6 +240,7 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase): self.assertFalse(owntracks.REGIONS_ENTERED[USER]) def test_event_entry_exit_inaccurate(self): + """Test the event for inaccurate exit.""" self.send_message(EVENT_TOPIC, REGION_ENTER_MESSAGE) # Enter uses the zone's gps co-ords @@ -254,6 +259,7 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase): self.assertFalse(owntracks.REGIONS_ENTERED[USER]) def test_event_exit_outside_zone_sets_away(self): + """Test the event for exit zone.""" self.send_message(EVENT_TOPIC, REGION_ENTER_MESSAGE) self.assert_location_state('inner') @@ -267,6 +273,7 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase): self.assert_location_state(STATE_NOT_HOME) def test_event_entry_exit_right_order(self): + """Test the event for ordering.""" # Enter inner zone self.send_message(EVENT_TOPIC, REGION_ENTER_MESSAGE) @@ -297,6 +304,7 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase): self.assert_location_accuracy(60.0) def test_event_entry_exit_wrong_order(self): + """Test the event for wrong order.""" # Enter inner zone self.send_message(EVENT_TOPIC, REGION_ENTER_MESSAGE) self.assert_location_state('inner') @@ -318,6 +326,7 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase): self.assert_location_state('outer') def test_event_entry_exit_passive_zone(self): + """Test the event for passive zone exits.""" # Enter passive zone message = REGION_ENTER_MESSAGE.copy() message['desc'] = "passive" @@ -354,6 +363,7 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase): self.assert_location_accuracy(60.0) def test_event_entry_unknown_zone(self): + """Test the event for unknown zone.""" # Just treat as location update message = REGION_ENTER_MESSAGE.copy() message['desc'] = "unknown" @@ -362,6 +372,7 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase): self.assert_location_state('outer') def test_event_exit_unknown_zone(self): + """Test the event for unknown zone.""" # Just treat as location update message = REGION_LEAVE_MESSAGE.copy() message['desc'] = "unknown" @@ -370,6 +381,7 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase): self.assert_location_state('outer') def test_event_entry_zone_loading_dash(self): + """Test the event for zone landing.""" # Make sure the leading - is ignored # Ownracks uses this to switch on hold message = REGION_ENTER_MESSAGE.copy() @@ -379,6 +391,7 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase): self.assert_location_state('inner') def test_mobile_enter_move_beacon(self): + """Test the movement of a beacon.""" # Enter mobile beacon, should set location message = REGION_ENTER_MESSAGE.copy() message['desc'] = IBEACON_DEVICE @@ -396,6 +409,7 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase): self.assert_tracker_state(STATE_NOT_HOME) def test_mobile_enter_exit_region_beacon(self): + """Test the enter and the exit of a region beacon.""" # Start tracking beacon message = REGION_ENTER_MESSAGE.copy() message['desc'] = IBEACON_DEVICE @@ -418,6 +432,7 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase): self.assert_tracker_latitude(2.0) def test_mobile_exit_move_beacon(self): + """Test the exit move of a beacon.""" # Start tracking beacon message = REGION_ENTER_MESSAGE.copy() message['desc'] = IBEACON_DEVICE @@ -440,6 +455,7 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase): self.assert_tracker_latitude(3.0) def test_mobile_multiple_async_enter_exit(self): + """Test the multiple entering.""" # Test race condition enter_message = REGION_ENTER_MESSAGE.copy() enter_message['desc'] = IBEACON_DEVICE @@ -460,6 +476,7 @@ class TestDeviceTrackerOwnTracks(unittest.TestCase): self.assertEqual(owntracks.MOBILE_BEACONS_ACTIVE['greg_phone'], []) def test_mobile_multiple_enter_exit(self): + """Test the multiple entering.""" # Should only happen if the iphone dies enter_message = REGION_ENTER_MESSAGE.copy() enter_message['desc'] = IBEACON_DEVICE diff --git a/tests/components/device_tracker/test_unifi.py b/tests/components/device_tracker/test_unifi.py index aed89dc4d8c..913097d17f1 100644 --- a/tests/components/device_tracker/test_unifi.py +++ b/tests/components/device_tracker/test_unifi.py @@ -1,8 +1,4 @@ -""" -homeassistant.components.device_tracker.unifi -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Device tracker platform that supports scanning a Unifi WAP controller -""" +"""The tests for the Unifi WAP device tracker platform.""" import unittest from unittest import mock import urllib @@ -13,9 +9,12 @@ from unifi import controller class TestUnifiScanner(unittest.TestCase): + """Test the Unifiy platform.""" + @mock.patch('homeassistant.components.device_tracker.unifi.UnifiScanner') @mock.patch.object(controller, 'Controller') def test_config_minimal(self, mock_ctrl, mock_scanner): + """Test the setup with minimal configuration.""" config = { 'device_tracker': { CONF_USERNAME: 'foo', @@ -31,6 +30,7 @@ class TestUnifiScanner(unittest.TestCase): @mock.patch('homeassistant.components.device_tracker.unifi.UnifiScanner') @mock.patch.object(controller, 'Controller') def test_config_full(self, mock_ctrl, mock_scanner): + """Test the setup with full configuration.""" config = { 'device_tracker': { CONF_USERNAME: 'foo', @@ -48,6 +48,7 @@ class TestUnifiScanner(unittest.TestCase): @mock.patch('homeassistant.components.device_tracker.unifi.UnifiScanner') @mock.patch.object(controller, 'Controller') def test_config_error(self, mock_ctrl, mock_scanner): + """Test for configuration errors.""" config = { 'device_tracker': { CONF_HOST: 'myhost', @@ -61,6 +62,7 @@ class TestUnifiScanner(unittest.TestCase): @mock.patch('homeassistant.components.device_tracker.unifi.UnifiScanner') @mock.patch.object(controller, 'Controller') def test_config_badport(self, mock_ctrl, mock_scanner): + """Test the setup with a bad port.""" config = { 'device_tracker': { CONF_USERNAME: 'foo', @@ -76,6 +78,7 @@ class TestUnifiScanner(unittest.TestCase): @mock.patch('homeassistant.components.device_tracker.unifi.UnifiScanner') @mock.patch.object(controller, 'Controller') def test_config_controller_failed(self, mock_ctrl, mock_scanner): + """Test for controller failure.""" config = { 'device_tracker': { CONF_USERNAME: 'foo', @@ -88,6 +91,7 @@ class TestUnifiScanner(unittest.TestCase): self.assertFalse(result) def test_scanner_update(self): + """Test the scanner update.""" ctrl = mock.MagicMock() fake_clients = [ {'mac': '123'}, @@ -98,12 +102,14 @@ class TestUnifiScanner(unittest.TestCase): ctrl.get_clients.assert_called_once_with() def test_scanner_update_error(self): + """Test the scanner update for error.""" ctrl = mock.MagicMock() ctrl.get_clients.side_effect = urllib.error.HTTPError( '/', 500, 'foo', {}, None) unifi.UnifiScanner(ctrl) def test_scan_devices(self): + """Test the scanning for devices.""" ctrl = mock.MagicMock() fake_clients = [ {'mac': '123'}, @@ -114,6 +120,7 @@ class TestUnifiScanner(unittest.TestCase): self.assertEqual(set(['123', '234']), set(scanner.scan_devices())) def test_get_device_name(self): + """Test the getting of device names.""" ctrl = mock.MagicMock() fake_clients = [ {'mac': '123', 'hostname': 'foobar'}, diff --git a/tests/components/garage_door/__init__.py b/tests/components/garage_door/__init__.py index e69de29bb2d..0523d661222 100644 --- a/tests/components/garage_door/__init__.py +++ b/tests/components/garage_door/__init__.py @@ -0,0 +1 @@ +"""The tests for Garage door platforms.""" diff --git a/tests/components/garage_door/test_demo.py b/tests/components/garage_door/test_demo.py index b500bc01013..7c1ea056318 100644 --- a/tests/components/garage_door/test_demo.py +++ b/tests/components/garage_door/test_demo.py @@ -1,9 +1,4 @@ -""" -tests.components.garage_door.test_demo -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests demo garage door component. -""" +"""The tests for the Demo Garage door platform.""" import unittest import homeassistant.components.garage_door as gd @@ -16,9 +11,10 @@ RIGHT = 'garage_door.right_garage_door' class TestGarageDoorDemo(unittest.TestCase): - """ Test the demo garage door. """ + """Test the demo garage door.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.assertTrue(gd.setup(self.hass, { 'garage_door': { @@ -27,10 +23,11 @@ class TestGarageDoorDemo(unittest.TestCase): })) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_is_closed(self): + """Test if door is closed.""" self.assertTrue(gd.is_closed(self.hass, LEFT)) self.hass.states.is_state(LEFT, 'close') @@ -38,15 +35,15 @@ class TestGarageDoorDemo(unittest.TestCase): self.hass.states.is_state(RIGHT, 'open') def test_open_door(self): + """Test opeing of the door.""" gd.open_door(self.hass, LEFT) - self.hass.pool.block_till_done() self.assertFalse(gd.is_closed(self.hass, LEFT)) def test_close_door(self): + """Test closing ot the door.""" gd.close_door(self.hass, RIGHT) - self.hass.pool.block_till_done() self.assertTrue(gd.is_closed(self.hass, RIGHT)) diff --git a/tests/components/light/__init__.py b/tests/components/light/__init__.py index e69de29bb2d..53023c9d299 100644 --- a/tests/components/light/__init__.py +++ b/tests/components/light/__init__.py @@ -0,0 +1 @@ +"""The tests for Light platforms.""" diff --git a/tests/components/light/test_init.py b/tests/components/light/test_init.py index 5830e371f6e..7df35d9f3f8 100644 --- a/tests/components/light/test_init.py +++ b/tests/components/light/test_init.py @@ -1,9 +1,4 @@ -""" -tests.components.test_init -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests light component. -""" +"""The tests for the Light component.""" # pylint: disable=too-many-public-methods,protected-access import unittest import os @@ -18,13 +13,14 @@ from tests.common import mock_service, get_test_home_assistant class TestLight(unittest.TestCase): - """ Test the light module. """ + """Test the light module.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() user_light_file = self.hass.config.path(light.LIGHT_PROFILES_FILE) @@ -33,7 +29,7 @@ class TestLight(unittest.TestCase): os.remove(user_light_file) def test_methods(self): - """ Test if methods call the services as expected. """ + """Test if methods call the services as expected.""" # Test is_on self.hass.states.set('light.test', STATE_ON) self.assertTrue(light.is_on(self.hass, 'light.test')) @@ -111,7 +107,7 @@ class TestLight(unittest.TestCase): self.assertEqual('transition_val', call.data[light.ATTR_TRANSITION]) def test_services(self): - """ Test the provided services. """ + """Test the provided services.""" platform = loader.get_component('light.test') platform.init() @@ -245,7 +241,7 @@ class TestLight(unittest.TestCase): data) def test_broken_light_profiles(self): - """ Test light profiles. """ + """Test light profiles.""" platform = loader.get_component('light.test') platform.init() @@ -261,7 +257,7 @@ class TestLight(unittest.TestCase): )) def test_light_profiles(self): - """ Test light profiles. """ + """Test light profiles.""" platform = loader.get_component('light.test') platform.init() diff --git a/tests/components/light/test_mqtt.py b/tests/components/light/test_mqtt.py index 624f5ed94f7..bf4e7ab6a94 100644 --- a/tests/components/light/test_mqtt.py +++ b/tests/components/light/test_mqtt.py @@ -1,10 +1,6 @@ -""" -tests.components.light.test_mqtt -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +"""The tests for the MQTT light platform. -Tests mqtt light. - -config for RGB Version with brightness: +Configuration for RGB Version with brightness: light: platform: mqtt @@ -59,7 +55,6 @@ light: qos: 0 payload_on: "on" payload_off: "off" - """ import unittest @@ -70,17 +65,19 @@ from tests.common import ( class TestLightMQTT(unittest.TestCase): - """ Test the MQTT light. """ + """Test the MQTT light.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.mock_publish = mock_mqtt_component(self.hass) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_fail_setup_if_no_command_topic(self): + """Test if command fails with command topic.""" self.assertTrue(light.setup(self.hass, { 'light': { 'platform': 'mqtt', @@ -90,6 +87,7 @@ class TestLightMQTT(unittest.TestCase): self.assertIsNone(self.hass.states.get('light.test')) def test_no_color_or_brightness_if_no_topics(self): + """Test if there is no color and brightness if no topic.""" self.assertTrue(light.setup(self.hass, { 'light': { 'platform': 'mqtt', @@ -113,6 +111,7 @@ class TestLightMQTT(unittest.TestCase): self.assertIsNone(state.attributes.get('brightness')) def test_controlling_state_via_topic(self): + """Test the controlling of the state via topic.""" self.assertTrue(light.setup(self.hass, { 'light': { 'platform': 'mqtt', @@ -172,6 +171,7 @@ class TestLightMQTT(unittest.TestCase): light_state.attributes.get('rgb_color')) def test_controlling_scale(self): + """Test the controlling scale.""" self.assertTrue(light.setup(self.hass, { 'light': { 'platform': 'mqtt', @@ -217,6 +217,7 @@ class TestLightMQTT(unittest.TestCase): light_state.attributes['brightness']) def test_controlling_state_via_topic_with_templates(self): + """Test the setting og the state with a template.""" self.assertTrue(light.setup(self.hass, { 'light': { 'platform': 'mqtt', @@ -250,6 +251,7 @@ class TestLightMQTT(unittest.TestCase): self.assertEqual([1, 2, 3], state.attributes.get('rgb_color')) def test_sending_mqtt_commands_and_optimistic(self): + """Test the sending of command in optimistic mode.""" self.assertTrue(light.setup(self.hass, { 'light': { 'platform': 'mqtt', @@ -307,6 +309,7 @@ class TestLightMQTT(unittest.TestCase): self.assertEqual(50, state.attributes['brightness']) def test_show_brightness_if_only_command_topic(self): + """Test the brightness if only a command topic is present.""" self.assertTrue(light.setup(self.hass, { 'light': { 'platform': 'mqtt', diff --git a/tests/components/light/test_rfxtrx.py b/tests/components/light/test_rfxtrx.py index d4f8ab740ae..4cf9a048863 100644 --- a/tests/components/light/test_rfxtrx.py +++ b/tests/components/light/test_rfxtrx.py @@ -1,10 +1,4 @@ -""" -tests.components.light.test_rfxtrx -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests Rfxtrx light. -""" - +"""The tests for the Rfxtrx light platform.""" import unittest from homeassistant.components import rfxtrx as rfxtrx_core @@ -18,25 +12,25 @@ from tests.common import get_test_home_assistant @pytest.mark.skipif(True, reason='Does not clean up properly, takes 100% CPU') class TestLightRfxtrx(unittest.TestCase): - """ Test the Rfxtrx light. """ + """Test the Rfxtrx light platform.""" def setUp(self): - """ setup hass """ + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant(0) def tearDown(self): - """ Stop down stuff we started. """ + """Stop everything that was started.""" rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS = [] rfxtrx_core.RFX_DEVICES = {} self.hass.stop() def test_default_config(self): - """ Test with 0 lights """ + """Test with 0 lights.""" config = {'devices': {}} devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add a callback to add devices.""" for dev in devs: devices.append(dev) @@ -44,7 +38,7 @@ class TestLightRfxtrx(unittest.TestCase): self.assertEqual(0, len(devices)) def test_one_sensor(self): - """ Test with 1 light """ + """Test with 1 light.""" config = {'devices': {'123efab1': { 'name': 'Test', @@ -56,7 +50,7 @@ class TestLightRfxtrx(unittest.TestCase): devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add a callback to add devices.""" for dev in devs: devices.append(dev) @@ -104,7 +98,7 @@ class TestLightRfxtrx(unittest.TestCase): self.assertEqual(entity.brightness, 255) def test_several_lights(self): - """ Test with 3 lights """ + """Test with 3 lights.""" config = {'signal_repetitions': 3, 'devices': {'123efab1': { @@ -119,7 +113,7 @@ class TestLightRfxtrx(unittest.TestCase): devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add a callback to add devices.""" for dev in devs: devices.append(dev) @@ -145,12 +139,12 @@ class TestLightRfxtrx(unittest.TestCase): self.assertEqual(3, device_num) def test_discover_light(self): - """ Test with discover of light """ + """Test with discovery of lights.""" config = {'automatic_add': True, 'devices': {}} devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add a callback to add devices.""" for dev in devs: devices.append(dev) @@ -209,12 +203,12 @@ class TestLightRfxtrx(unittest.TestCase): self.assertEqual(2, len(devices)) def test_discover_light_noautoadd(self): - """ Test with discover of light when auto add is False """ + """Test with discover of light when auto add is False.""" config = {'automatic_add': False, 'devices': {}} devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add a callback to add devices.""" for dev in devs: devices.append(dev) @@ -250,14 +244,14 @@ class TestLightRfxtrx(unittest.TestCase): self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) self.assertEqual(0, len(devices)) - # trying to add a sensor + # Trying to add a sensor event = rfxtrx_core.get_rfx_object('0a52085e070100b31b0279') event.data = bytearray(b'\nR\x08^\x07\x01\x00\xb3\x1b\x02y') rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) self.assertEqual(0, len(devices)) - # trying to add a switch + # Trying to add a switch event = rfxtrx_core.get_rfx_object('0b1100100118cdea02010f70') event.data = bytearray([0x0b, 0x11, 0x00, 0x10, 0x01, 0x18, 0xcd, 0xea, 0x01, 0x01, 0x0f, 0x70]) diff --git a/tests/components/lock/__init__.py b/tests/components/lock/__init__.py index e69de29bb2d..0e7121a675c 100644 --- a/tests/components/lock/__init__.py +++ b/tests/components/lock/__init__.py @@ -0,0 +1 @@ +"""The tests for Lock platforms.""" diff --git a/tests/components/lock/test_demo.py b/tests/components/lock/test_demo.py index d116a9bcd7c..84be7629fce 100644 --- a/tests/components/lock/test_demo.py +++ b/tests/components/lock/test_demo.py @@ -1,9 +1,4 @@ -""" -tests.components.lock.test_demo -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests demo lock component. -""" +"""The tests for the Demo lock platform.""" import unittest from homeassistant.components import lock @@ -16,9 +11,10 @@ KITCHEN = 'lock.kitchen_door' class TestLockDemo(unittest.TestCase): - """ Test the demo lock. """ + """Test the demo lock.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.assertTrue(lock.setup(self.hass, { 'lock': { @@ -27,10 +23,11 @@ class TestLockDemo(unittest.TestCase): })) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_is_locked(self): + """Test if lock is locked.""" self.assertTrue(lock.is_locked(self.hass, FRONT)) self.hass.states.is_state(FRONT, 'locked') @@ -38,15 +35,15 @@ class TestLockDemo(unittest.TestCase): self.hass.states.is_state(KITCHEN, 'unlocked') def test_locking(self): + """Test the locking of a lock.""" lock.lock(self.hass, KITCHEN) - self.hass.pool.block_till_done() self.assertTrue(lock.is_locked(self.hass, KITCHEN)) def test_unlocking(self): + """Test the unlocking of a lock.""" lock.unlock(self.hass, FRONT) - self.hass.pool.block_till_done() self.assertFalse(lock.is_locked(self.hass, FRONT)) diff --git a/tests/components/lock/test_mqtt.py b/tests/components/lock/test_mqtt.py index f43ed79b7e2..810d5c5449f 100644 --- a/tests/components/lock/test_mqtt.py +++ b/tests/components/lock/test_mqtt.py @@ -1,6 +1,4 @@ -""" -Tests MQTT lock. -""" +"""The tests for the MQTT lock platform.""" import unittest from homeassistant.const import (STATE_LOCKED, STATE_UNLOCKED, @@ -12,15 +10,18 @@ from tests.common import ( class TestLockMQTT(unittest.TestCase): """Test the MQTT lock.""" + def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.mock_publish = mock_mqtt_component(self.hass) def tearDown(self): # pylint: disable=invalid-name - """Stop down stuff we started.""" + """Stop everything that was started.""" self.hass.stop() def test_controlling_state_via_topic(self): + """Test the controlling state via topic.""" self.assertTrue(lock.setup(self.hass, { 'lock': { 'platform': 'mqtt', @@ -49,6 +50,7 @@ class TestLockMQTT(unittest.TestCase): self.assertEqual(STATE_UNLOCKED, state.state) def test_sending_mqtt_commands_and_optimistic(self): + """Test the sending MQTT commands in optimistic mode.""" self.assertTrue(lock.setup(self.hass, { 'lock': { 'platform': 'mqtt', @@ -81,6 +83,7 @@ class TestLockMQTT(unittest.TestCase): self.assertEqual(STATE_UNLOCKED, state.state) def test_controlling_state_via_topic_and_json_message(self): + """Test the controlling state via topic and JSON message.""" self.assertTrue(lock.setup(self.hass, { 'lock': { 'platform': 'mqtt', diff --git a/tests/components/media_player/__init__.py b/tests/components/media_player/__init__.py index e69de29bb2d..5b4cdd92a07 100644 --- a/tests/components/media_player/__init__.py +++ b/tests/components/media_player/__init__.py @@ -0,0 +1 @@ +"""The tests for Media player platforms.""" diff --git a/tests/components/media_player/test_cast.py b/tests/components/media_player/test_cast.py index 296c5590593..9930ae678f3 100644 --- a/tests/components/media_player/test_cast.py +++ b/tests/components/media_player/test_cast.py @@ -1,9 +1,4 @@ -""" -tests.component.media_player.test_cast -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests cast media_player component. -""" +"""The tests for the Cast Media player platform.""" # pylint: disable=too-many-public-methods,protected-access import unittest from unittest.mock import patch @@ -12,10 +7,11 @@ from homeassistant.components.media_player import cast class TestCastMediaPlayer(unittest.TestCase): - """ Test the media_player module. """ + """Test the media_player module.""" @patch('homeassistant.components.media_player.cast.CastDevice') def test_filter_duplicates(self, mock_device): + """Test filtering of duplicates.""" cast.setup_platform(None, { 'host': 'some_host' }, lambda _: _) diff --git a/tests/components/media_player/test_demo.py b/tests/components/media_player/test_demo.py index 3af558cb735..499a5cd8c18 100644 --- a/tests/components/media_player/test_demo.py +++ b/tests/components/media_player/test_demo.py @@ -1,9 +1,4 @@ -""" -tests.component.media_player.test_demo -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests demo media_player component. -""" +"""The tests for the Demo Media player platform.""" import unittest from unittest.mock import patch import homeassistant.components.media_player as mp @@ -14,16 +9,18 @@ entity_id = 'media_player.walkman' class TestDemoMediaPlayer(unittest.TestCase): - """ Test the media_player module. """ + """Test the media_player module.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_volume_services(self): + """Test the volume service.""" assert mp.setup(self.hass, {'media_player': {'platform': 'demo'}}) state = self.hass.states.get(entity_id) assert 1.0 == state.attributes.get('volume_level') @@ -50,6 +47,7 @@ class TestDemoMediaPlayer(unittest.TestCase): assert True is state.attributes.get('is_volume_muted') def test_turning_off_and_on(self): + """Test turn_on and turn_off.""" assert mp.setup(self.hass, {'media_player': {'platform': 'demo'}}) assert self.hass.states.is_state(entity_id, 'playing') @@ -68,6 +66,7 @@ class TestDemoMediaPlayer(unittest.TestCase): assert not mp.is_on(self.hass, entity_id) def test_playing_pausing(self): + """Test media_pause.""" assert mp.setup(self.hass, {'media_player': {'platform': 'demo'}}) assert self.hass.states.is_state(entity_id, 'playing') @@ -88,6 +87,7 @@ class TestDemoMediaPlayer(unittest.TestCase): assert self.hass.states.is_state(entity_id, 'playing') def test_prev_next_track(self): + """Test media_next_track and media_prevoius_track .""" assert mp.setup(self.hass, {'media_player': {'platform': 'demo'}}) state = self.hass.states.get(entity_id) assert 1 == state.attributes.get('media_track') @@ -118,6 +118,7 @@ class TestDemoMediaPlayer(unittest.TestCase): @patch('homeassistant.components.media_player.demo.DemoYoutubePlayer.' 'media_seek') def test_play_media(self, mock_seek): + """Test play_media .""" assert mp.setup(self.hass, {'media_player': {'platform': 'demo'}}) ent_id = 'media_player.living_room' state = self.hass.states.get(ent_id) diff --git a/tests/components/media_player/test_universal.py b/tests/components/media_player/test_universal.py index 8412db29214..6777b2f5c9b 100644 --- a/tests/components/media_player/test_universal.py +++ b/tests/components/media_player/test_universal.py @@ -1,9 +1,4 @@ -""" -tests.component.media_player.test_universal -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests universal media_player component. -""" +"""The tests for the Universal Media player platform.""" from copy import copy import unittest @@ -17,9 +12,10 @@ from tests.common import mock_service, get_test_home_assistant class MockMediaPlayer(media_player.MediaPlayerDevice): - """ Mock media player for testing """ + """Mock media player for testing.""" def __init__(self, hass, name): + """Initialize the media player.""" self.hass = hass self._name = name self.entity_id = media_player.ENTITY_ID_FORMAT.format(name) @@ -34,58 +30,59 @@ class MockMediaPlayer(media_player.MediaPlayerDevice): @property def name(self): - """ name of player """ + """Return the name of player.""" return self._name @property def state(self): - """ state of the player """ + """Return the state of the player.""" return self._state @property def volume_level(self): - """ volume level of player """ + """The volume level of player.""" return self._volume_level @property def is_volume_muted(self): - """ if the media player is muted """ + """Return true if the media player is muted.""" return self._is_volume_muted @property def supported_media_commands(self): - """ supported media commands flag """ + """Supported media commands flag.""" return self._supported_media_commands def turn_on(self): - """ mock turn_on function """ + """Mock turn_on function.""" self._state = STATE_UNKNOWN def turn_off(self): - """ mock turn_off function """ + """Mock turn_off function.""" self._state = STATE_OFF def mute_volume(self): - """ mock mute function """ + """Mock mute function.""" self._is_volume_muted = ~self._is_volume_muted def set_volume_level(self, volume): - """ mock set volume level """ + """Mock set volume level.""" self._volume_level = volume def media_play(self): - """ mock play """ + """Mock play.""" self._state = STATE_PLAYING def media_pause(self): - """ mock pause """ + """Mock pause.""" self._state = STATE_PAUSED class TestMediaPlayer(unittest.TestCase): - """ Test the media_player module. """ + """Test the media_player module.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.mock_mp_1 = MockMediaPlayer(self.hass, 'mock1') @@ -113,11 +110,11 @@ class TestMediaPlayer(unittest.TestCase): 'state': self.mock_state_switch_id}} def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_check_config_children_only(self): - """ Check config with only children """ + """Check config with only children.""" config_start = copy(self.config_children_only) del config_start['platform'] config_start['commands'] = {} @@ -129,7 +126,7 @@ class TestMediaPlayer(unittest.TestCase): self.assertEqual(config_start, self.config_children_only) def test_check_config_children_and_attr(self): - """ Check config with children and attributes """ + """Check config with children and attributes.""" config_start = copy(self.config_children_and_attr) del config_start['platform'] config_start['commands'] = {} @@ -140,13 +137,13 @@ class TestMediaPlayer(unittest.TestCase): self.assertEqual(config_start, self.config_children_and_attr) def test_check_config_no_name(self): - """ Check config with no Name entry """ + """Check config with no Name entry.""" response = universal.validate_config({'platform': 'universal'}) self.assertFalse(response) def test_check_config_bad_children(self): - """ Check config with bad children entry """ + """Check config with bad children entry.""" config_no_children = {'name': 'test', 'platform': 'universal'} config_bad_children = {'name': 'test', 'children': {}, 'platform': 'universal'} @@ -160,7 +157,7 @@ class TestMediaPlayer(unittest.TestCase): self.assertEqual([], config_bad_children['children']) def test_check_config_bad_commands(self): - """ Check config with bad commands entry """ + """Check config with bad commands entry.""" config = {'name': 'test', 'commands': [], 'platform': 'universal'} response = universal.validate_config(config) @@ -168,7 +165,7 @@ class TestMediaPlayer(unittest.TestCase): self.assertEqual({}, config['commands']) def test_check_config_bad_attributes(self): - """ Check config with bad attributes """ + """Check config with bad attributes.""" config = {'name': 'test', 'attributes': [], 'platform': 'universal'} response = universal.validate_config(config) @@ -176,7 +173,7 @@ class TestMediaPlayer(unittest.TestCase): self.assertEqual({}, config['attributes']) def test_check_config_bad_key(self): - """ check config with bad key """ + """Check config with bad key.""" config = {'name': 'test', 'asdf': 5, 'platform': 'universal'} response = universal.validate_config(config) @@ -184,12 +181,12 @@ class TestMediaPlayer(unittest.TestCase): self.assertFalse('asdf' in config) def test_platform_setup(self): - """ test platform setup """ + """Test platform setup.""" config = {'name': 'test', 'platform': 'universal'} entities = [] def add_devices(new_entities): - """ add devices to list """ + """Add devices to list.""" for dev in new_entities: entities.append(dev) @@ -199,7 +196,7 @@ class TestMediaPlayer(unittest.TestCase): self.assertEqual('test', entities[0].name) def test_master_state(self): - """ test master state property """ + """Test master state property.""" config = self.config_children_only universal.validate_config(config) @@ -208,20 +205,18 @@ class TestMediaPlayer(unittest.TestCase): self.assertEqual(None, ump.master_state) def test_master_state_with_attrs(self): - """ test master state property """ + """Test master state property.""" config = self.config_children_and_attr universal.validate_config(config) ump = universal.UniversalMediaPlayer(self.hass, **config) self.assertEqual(STATE_OFF, ump.master_state) - self.hass.states.set(self.mock_state_switch_id, STATE_ON) - self.assertEqual(STATE_ON, ump.master_state) def test_master_state_with_bad_attrs(self): - """ test master state property """ + """Test master state property.""" config = self.config_children_and_attr config['attributes']['state'] = 'bad.entity_id' universal.validate_config(config) @@ -231,7 +226,7 @@ class TestMediaPlayer(unittest.TestCase): self.assertEqual(STATE_OFF, ump.master_state) def test_active_child_state(self): - """ test active child state property """ + """Test active child state property.""" config = self.config_children_only universal.validate_config(config) @@ -260,7 +255,7 @@ class TestMediaPlayer(unittest.TestCase): ump._child_state.entity_id) def test_name(self): - """ test name property """ + """Test name property.""" config = self.config_children_only universal.validate_config(config) @@ -269,7 +264,7 @@ class TestMediaPlayer(unittest.TestCase): self.assertEqual(config['name'], ump.name) def test_state_children_only(self): - """ test media player state with only children """ + """Test media player state with only children.""" config = self.config_children_only universal.validate_config(config) @@ -285,7 +280,7 @@ class TestMediaPlayer(unittest.TestCase): self.assertEqual(STATE_PLAYING, ump.state) def test_state_with_children_and_attrs(self): - """ test media player with children and master state """ + """Test media player with children and master state.""" config = self.config_children_and_attr universal.validate_config(config) @@ -309,7 +304,7 @@ class TestMediaPlayer(unittest.TestCase): self.assertEqual(STATE_OFF, ump.state) def test_volume_level(self): - """ test volume level property """ + """Test volume level property.""" config = self.config_children_only universal.validate_config(config) @@ -330,7 +325,7 @@ class TestMediaPlayer(unittest.TestCase): self.assertEqual(1, ump.volume_level) def test_is_volume_muted_children_only(self): - """ test is volume muted property w/ children only """ + """Test is volume muted property w/ children only.""" config = self.config_children_only universal.validate_config(config) @@ -351,7 +346,7 @@ class TestMediaPlayer(unittest.TestCase): self.assertTrue(ump.is_volume_muted) def test_is_volume_muted_children_and_attr(self): - """ test is volume muted property w/ children and attrs """ + """Test is volume muted property w/ children and attrs.""" config = self.config_children_and_attr universal.validate_config(config) @@ -363,7 +358,7 @@ class TestMediaPlayer(unittest.TestCase): self.assertTrue(ump.is_volume_muted) def test_supported_media_commands_children_only(self): - """ test supported media commands with only children """ + """Test supported media commands with only children.""" config = self.config_children_only universal.validate_config(config) @@ -380,7 +375,7 @@ class TestMediaPlayer(unittest.TestCase): self.assertEqual(512, ump.supported_media_commands) def test_supported_media_commands_children_and_cmds(self): - """ test supported media commands with children and attrs """ + """Test supported media commands with children and attrs.""" config = self.config_children_and_attr universal.validate_config(config) config['commands']['turn_on'] = 'test' @@ -405,7 +400,7 @@ class TestMediaPlayer(unittest.TestCase): self.assertEqual(check_flags, ump.supported_media_commands) def test_service_call_to_child(self): - """ test a service call that should be routed to a child """ + """Test a service call that should be routed to a child.""" config = self.config_children_only universal.validate_config(config) @@ -421,6 +416,7 @@ class TestMediaPlayer(unittest.TestCase): self.assertEqual(1, len(self.mock_mp_2.turn_off_service_calls)) def test_service_call_to_command(self): + """Test service call to command.""" config = self.config_children_only config['commands'] = \ {'turn_off': {'service': 'test.turn_off', 'data': {}}} diff --git a/tests/components/notify/__init__.py b/tests/components/notify/__init__.py index e69de29bb2d..951a21a9597 100644 --- a/tests/components/notify/__init__.py +++ b/tests/components/notify/__init__.py @@ -0,0 +1 @@ +"""The tests for notification platforms.""" diff --git a/tests/components/notify/test_command_line.py b/tests/components/notify/test_command_line.py index f920590a21c..8f1c41bbb92 100644 --- a/tests/components/notify/test_command_line.py +++ b/tests/components/notify/test_command_line.py @@ -1,9 +1,4 @@ -""" -tests.components.notify.test_command_line -~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests command line notification. -""" +"""The tests for the command line notification platform.""" import os import tempfile import unittest @@ -14,16 +9,18 @@ from unittest.mock import patch class TestCommandLine(unittest.TestCase): - """ Test the command line. """ + """Test the command line notifications.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = core.HomeAssistant() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop down everything that was started.""" self.hass.stop() def test_command_line_output(self): + """Test the command line output.""" with tempfile.TemporaryDirectory() as tempdirname: filename = os.path.join(tempdirname, 'message.txt') message = 'one, two, testing, testing' @@ -44,7 +41,7 @@ class TestCommandLine(unittest.TestCase): @patch('homeassistant.components.notify.command_line._LOGGER.error') def test_error_for_none_zero_exit_code(self, mock_error): - """ Test if an error if logged for non zero exit codes. """ + """Test if an error if logged for non zero exit codes.""" self.assertTrue(notify.setup(self.hass, { 'notify': { 'name': 'test', diff --git a/tests/components/notify/test_demo.py b/tests/components/notify/test_demo.py index 7cf14c0064f..92f4723323b 100644 --- a/tests/components/notify/test_demo.py +++ b/tests/components/notify/test_demo.py @@ -1,9 +1,4 @@ -""" -tests.components.notify.test_demo -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests notify demo component. -""" +"""The tests for the notify demo platform.""" import unittest import homeassistant.components.notify as notify @@ -13,9 +8,10 @@ from tests.common import get_test_home_assistant class TestNotifyDemo(unittest.TestCase): - """ Test the demo notify. """ + """Test the demo notify.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.assertTrue(notify.setup(self.hass, { 'notify': { @@ -25,15 +21,17 @@ class TestNotifyDemo(unittest.TestCase): self.events = [] def record_event(event): + """Record event to send notification.""" self.events.append(event) self.hass.bus.listen(demo.EVENT_NOTIFY, record_event) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """"Stop down everything that was started.""" self.hass.stop() def test_sending_templated_message(self): + """Send a templated message.""" self.hass.states.set('sensor.temperature', 10) notify.send_message(self.hass, '{{ states.sensor.temperature.state }}', '{{ states.sensor.temperature.name }}') diff --git a/tests/components/rollershutter/__init__.py b/tests/components/rollershutter/__init__.py index e69de29bb2d..4fc6ddee8a9 100644 --- a/tests/components/rollershutter/__init__.py +++ b/tests/components/rollershutter/__init__.py @@ -0,0 +1 @@ +"""The tests for Roller shutter platforms.""" diff --git a/tests/components/rollershutter/test_command_line.py b/tests/components/rollershutter/test_command_line.py index 6f71b6f6353..6538c5bc756 100644 --- a/tests/components/rollershutter/test_command_line.py +++ b/tests/components/rollershutter/test_command_line.py @@ -1,8 +1,4 @@ -""" -tests.components.rollershutter.command_line -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Tests the command_line component -""" +"""The tests the Roller shutter command line platform.""" import os import tempfile @@ -16,7 +12,10 @@ from homeassistant.components.rollershutter import ( class TestCommandRollerShutter(unittest.TestCase): + """Test the Roller shutter command line platform.""" + def setup_method(self, method): + """Setup things to be run when tests are started.""" self.hass = ha.HomeAssistant() self.hass.config.latitude = 32.87336 self.hass.config.longitude = 117.22743 @@ -26,15 +25,17 @@ class TestCommandRollerShutter(unittest.TestCase): None) # FIXME def teardown_method(self, method): - """ Stop down stuff we started. """ + """Stop down everything that was started.""" self.hass.stop() def test_should_poll(self): + """Test the setting of polling.""" self.assertTrue(self.rs.should_poll) self.rs._command_state = None self.assertFalse(self.rs.should_poll) def test_query_state_value(self): + """Test with state value.""" with mock.patch('subprocess.check_output') as mock_run: mock_run.return_value = b' foo bar ' result = self.rs._query_state_value('runme') @@ -42,6 +43,7 @@ class TestCommandRollerShutter(unittest.TestCase): mock_run.assert_called_once_with('runme', shell=True) def test_state_value(self): + """Test with state value.""" with tempfile.TemporaryDirectory() as tempdirname: path = os.path.join(tempdirname, 'rollershutter_status') test_rollershutter = { diff --git a/tests/components/rollershutter/test_mqtt.py b/tests/components/rollershutter/test_mqtt.py index 3a5fe936af9..b871a8d06e2 100644 --- a/tests/components/rollershutter/test_mqtt.py +++ b/tests/components/rollershutter/test_mqtt.py @@ -1,9 +1,4 @@ -""" -tests.components.rollershutter.test_mqtt -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests MQTT rollershutter. -""" +"""The tests for the MQTT roller shutter platform.""" import unittest from homeassistant.const import STATE_OPEN, STATE_CLOSED, STATE_UNKNOWN @@ -14,17 +9,19 @@ from tests.common import get_test_home_assistant class TestRollershutterMQTT(unittest.TestCase): - """ Test the MQTT rollershutter. """ + """Test the MQTT roller shutter.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.mock_publish = mock_mqtt_component(self.hass) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop down everything that was started.""" self.hass.stop() def test_controlling_state_via_topic(self): + """Test the controlling state via topic.""" self.assertTrue(rollershutter.setup(self.hass, { 'rollershutter': { 'platform': 'mqtt', @@ -60,6 +57,7 @@ class TestRollershutterMQTT(unittest.TestCase): self.assertEqual(STATE_OPEN, state.state) def test_send_move_up_command(self): + """Test the sending of move_up.""" self.assertTrue(rollershutter.setup(self.hass, { 'rollershutter': { 'platform': 'mqtt', @@ -82,6 +80,7 @@ class TestRollershutterMQTT(unittest.TestCase): self.assertEqual(STATE_UNKNOWN, state.state) def test_send_move_down_command(self): + """Test the sending of move_down.""" self.assertTrue(rollershutter.setup(self.hass, { 'rollershutter': { 'platform': 'mqtt', @@ -104,6 +103,7 @@ class TestRollershutterMQTT(unittest.TestCase): self.assertEqual(STATE_UNKNOWN, state.state) def test_send_stop_command(self): + """Test the sending of stop.""" self.assertTrue(rollershutter.setup(self.hass, { 'rollershutter': { 'platform': 'mqtt', @@ -126,6 +126,7 @@ class TestRollershutterMQTT(unittest.TestCase): self.assertEqual(STATE_UNKNOWN, state.state) def test_state_attributes_current_position(self): + """Test the current position.""" self.assertTrue(rollershutter.setup(self.hass, { 'rollershutter': { 'platform': 'mqtt', diff --git a/tests/components/sensor/__init__.py b/tests/components/sensor/__init__.py index e69de29bb2d..17c225c67d6 100644 --- a/tests/components/sensor/__init__.py +++ b/tests/components/sensor/__init__.py @@ -0,0 +1 @@ +"""The tests for Sensor platforms.""" diff --git a/tests/components/sensor/test_command_line.py b/tests/components/sensor/test_command_line.py index fa51a9a1c15..bd083f7b63e 100644 --- a/tests/components/sensor/test_command_line.py +++ b/tests/components/sensor/test_command_line.py @@ -1,9 +1,4 @@ -""" -tests.components.sensor.test_command_line -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests command sensor. -""" +"""The tests for the Command line sensor platform.""" import unittest from homeassistant.components.sensor import command_line @@ -12,24 +7,25 @@ from tests.common import get_test_home_assistant class TestCommandSensorSensor(unittest.TestCase): - """ Test the Command line sensor. """ + """Test the Command line sensor.""" def setUp(self): + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def tearDown(self): - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_setup(self): - """ Test sensor setup. """ + """Test sensor setup.""" config = {'name': 'Test', 'unit_of_measurement': 'in', 'command': 'echo 5'} devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add callback to add devices.""" for dev in devs: devices.append(dev) @@ -43,13 +39,13 @@ class TestCommandSensorSensor(unittest.TestCase): self.assertEqual('5', entity.state) def test_setup_bad_config(self): - """ Test setup with a bad configuration. """ + """Test setup with a bad configuration.""" config = {} devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add a callback to add devices.""" for dev in devs: devices.append(dev) @@ -59,7 +55,7 @@ class TestCommandSensorSensor(unittest.TestCase): self.assertEqual(0, len(devices)) def test_template(self): - """ Test command sensor with template. """ + """Test command sensor with template.""" data = command_line.CommandSensorData('echo 50') entity = command_line.CommandSensor( @@ -68,7 +64,7 @@ class TestCommandSensorSensor(unittest.TestCase): self.assertEqual(5, float(entity.state)) def test_bad_command(self): - """ Test bad command. """ + """Test bad command.""" data = command_line.CommandSensorData('asdfasdf') data.update() diff --git a/tests/components/sensor/test_mfi.py b/tests/components/sensor/test_mfi.py index 229e18b5f6a..033ee30cc09 100644 --- a/tests/components/sensor/test_mfi.py +++ b/tests/components/sensor/test_mfi.py @@ -1,9 +1,4 @@ -""" -tests.components.sensor.test_mfi -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests mFi sensor. -""" +"""The tests for the mFi sensor platform.""" import unittest import unittest.mock as mock @@ -17,6 +12,8 @@ from tests.common import get_test_home_assistant class TestMfiSensorSetup(unittest.TestCase): + """Test the mFi sensor platform.""" + PLATFORM = mfi COMPONENT = sensor THING = 'sensor' @@ -33,15 +30,17 @@ class TestMfiSensorSetup(unittest.TestCase): } def setup_method(self, method): + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.config.latitude = 32.87336 self.hass.config.longitude = 117.22743 def teardown_method(self, method): - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_setup_missing_config(self): + """Test setup with missing configuration.""" config = { 'sensor': { 'platform': 'mfi', @@ -51,6 +50,7 @@ class TestMfiSensorSetup(unittest.TestCase): @mock.patch('mficlient.client') def test_setup_failed_login(self, mock_client): + """Test setup with login failure.""" mock_client.FailedToLogin = Exception() mock_client.MFiClient.side_effect = mock_client.FailedToLogin self.assertFalse( @@ -60,6 +60,7 @@ class TestMfiSensorSetup(unittest.TestCase): @mock.patch('mficlient.client') def test_setup_failed_connect(self, mock_client): + """Test setup with conection failure.""" mock_client.FailedToLogin = Exception() mock_client.MFiClient.side_effect = requests.exceptions.ConnectionError self.assertFalse( @@ -69,6 +70,7 @@ class TestMfiSensorSetup(unittest.TestCase): @mock.patch('mficlient.client.MFiClient') def test_setup_minimum(self, mock_client): + """Test setup with minimum configuration.""" config = dict(self.GOOD_CONFIG) del config[self.THING]['port'] assert self.COMPONENT.setup(self.hass, config) @@ -78,6 +80,7 @@ class TestMfiSensorSetup(unittest.TestCase): @mock.patch('mficlient.client.MFiClient') def test_setup_with_port(self, mock_client): + """Test setup with port.""" config = dict(self.GOOD_CONFIG) config[self.THING]['port'] = 6123 assert self.COMPONENT.setup(self.hass, config) @@ -87,6 +90,7 @@ class TestMfiSensorSetup(unittest.TestCase): @mock.patch('mficlient.client.MFiClient') def test_setup_with_tls_disabled(self, mock_client): + """Test setup without TLS.""" config = dict(self.GOOD_CONFIG) del config[self.THING]['port'] config[self.THING]['use_tls'] = False @@ -99,6 +103,7 @@ class TestMfiSensorSetup(unittest.TestCase): @mock.patch('mficlient.client.MFiClient') @mock.patch('homeassistant.components.sensor.mfi.MfiSensor') def test_setup_adds_proper_devices(self, mock_sensor, mock_client): + """Test if setup adds devices.""" ports = {i: mock.MagicMock(model=model) for i, model in enumerate(mfi.SENSOR_MODELS)} ports['bad'] = mock.MagicMock(model='notasensor') @@ -113,7 +118,10 @@ class TestMfiSensorSetup(unittest.TestCase): class TestMfiSensor(unittest.TestCase): + """Test for mFi sensor platform.""" + def setup_method(self, method): + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.config.latitude = 32.87336 self.hass.config.longitude = 117.22743 @@ -121,29 +129,35 @@ class TestMfiSensor(unittest.TestCase): self.sensor = mfi.MfiSensor(self.port, self.hass) def teardown_method(self, method): - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_name(self): + """Test the name.""" self.assertEqual(self.port.label, self.sensor.name) def test_uom_temp(self): + """Test the UOM temperature.""" self.port.tag = 'temperature' self.assertEqual(TEMP_CELCIUS, self.sensor.unit_of_measurement) def test_uom_power(self): + """Test the UOEM power.""" self.port.tag = 'active_pwr' self.assertEqual('Watts', self.sensor.unit_of_measurement) def test_uom_digital(self): + """Test the UOM digital input.""" self.port.model = 'Input Digital' self.assertEqual('State', self.sensor.unit_of_measurement) def test_uom_unknown(self): + """Test the UOM.""" self.port.tag = 'balloons' self.assertEqual('balloons', self.sensor.unit_of_measurement) def test_state_digital(self): + """Test the digital input.""" self.port.model = 'Input Digital' self.port.value = 0 self.assertEqual(mfi.STATE_OFF, self.sensor.state) @@ -153,6 +167,7 @@ class TestMfiSensor(unittest.TestCase): self.assertEqual(mfi.STATE_ON, self.sensor.state) def test_state_digits(self): + """Test the state of digits.""" self.port.tag = 'didyoucheckthedict?' self.port.value = 1.25 with mock.patch.dict(mfi.DIGITS, {'didyoucheckthedict?': 1}): @@ -161,5 +176,6 @@ class TestMfiSensor(unittest.TestCase): self.assertEqual(1.0, self.sensor.state) def test_update(self): + """Test the update.""" self.sensor.update() self.port.refresh.assert_called_once_with() diff --git a/tests/components/sensor/test_mqtt.py b/tests/components/sensor/test_mqtt.py index 2d460b8ac3e..280542bb305 100644 --- a/tests/components/sensor/test_mqtt.py +++ b/tests/components/sensor/test_mqtt.py @@ -1,9 +1,4 @@ -""" -tests.components.sensor.test_mqtt -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests MQTT sensor. -""" +"""The tests for the MQTT sensor platform.""" import unittest import homeassistant.components.sensor as sensor @@ -13,17 +8,19 @@ from tests.common import get_test_home_assistant class TestSensorMQTT(unittest.TestCase): - """ Test the MQTT sensor. """ + """Test the MQTT sensor.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() mock_mqtt_component(self.hass) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop down everything that was started.""" self.hass.stop() def test_setting_sensor_value_via_mqtt_message(self): + """Test the setting of the value via MQTT.""" self.assertTrue(sensor.setup(self.hass, { 'sensor': { 'platform': 'mqtt', @@ -42,6 +39,7 @@ class TestSensorMQTT(unittest.TestCase): state.attributes.get('unit_of_measurement')) def test_setting_sensor_value_via_mqtt_json_message(self): + """Test the setting of the value via MQTT with JSON playload.""" self.assertTrue(sensor.setup(self.hass, { 'sensor': { 'platform': 'mqtt', diff --git a/tests/components/sensor/test_rfxtrx.py b/tests/components/sensor/test_rfxtrx.py index 578cd405f69..631d2273541 100644 --- a/tests/components/sensor/test_rfxtrx.py +++ b/tests/components/sensor/test_rfxtrx.py @@ -1,10 +1,4 @@ -""" -tests.components.sensor.test_rfxtrx -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests Rfxtrx sensor. -""" - +"""The tests for the Rfxtrx sensor platform.""" import unittest @@ -16,25 +10,25 @@ from tests.common import get_test_home_assistant class TestSensorRfxtrx(unittest.TestCase): - """ Test the Rfxtrx sensor. """ + """Test the Rfxtrx sensor platform.""" def setUp(self): - """ setup hass """ + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant(0) def tearDown(self): - """ Stop down stuff we started. """ + """Stop everything that was started.""" rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS = [] rfxtrx_core.RFX_DEVICES = {} self.hass.stop() def test_default_config(self): - """ Test with 0 sensors """ + """Test with 0 sensor.""" config = {'devices': {}} devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add a callback to add devices.""" for dev in devs: devices.append(dev) @@ -42,7 +36,7 @@ class TestSensorRfxtrx(unittest.TestCase): self.assertEqual(0, len(devices)) def test_one_sensor(self): - """ Test with 1 sensor """ + """Test with 1 sensor.""" config = {'devices': {'sensor_0502': { 'name': 'Test', @@ -51,7 +45,7 @@ class TestSensorRfxtrx(unittest.TestCase): devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add a callback to add devices.""" for dev in devs: devices.append(dev) @@ -69,7 +63,7 @@ class TestSensorRfxtrx(unittest.TestCase): entity.device_state_attributes) def test_several_sensors(self): - """ Test with 3 sensors """ + """Test with 3 sensors.""" config = {'devices': {'sensor_0502': { 'name': 'Test', @@ -85,7 +79,7 @@ class TestSensorRfxtrx(unittest.TestCase): devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add a callback to add devices.""" for dev in devs: devices.append(dev) @@ -129,12 +123,12 @@ class TestSensorRfxtrx(unittest.TestCase): self.assertEqual(3, device_num) def test_discover_sensor(self): - """ Test with discover of sensor """ + """Test with discovery of sensor.""" config = {'devices': {}} devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add a callback to add devices.""" for dev in devs: devices.append(dev) @@ -196,12 +190,12 @@ class TestSensorRfxtrx(unittest.TestCase): self.assertEqual(2, len(devices)) def test_discover_sensor_noautoadd(self): - """ Test with discover of sensor when auto add is False """ + """Test with discover of sensor when auto add is False.""" config = {'automatic_add': False, 'devices': {}} devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add a callback to add devices.""" for dev in devs: devices.append(dev) diff --git a/tests/components/sensor/test_tcp.py b/tests/components/sensor/test_tcp.py index 091b109f335..a20c01eee52 100644 --- a/tests/components/sensor/test_tcp.py +++ b/tests/components/sensor/test_tcp.py @@ -1,9 +1,4 @@ -""" -tests.components.sensor.tcp -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests TCP sensor. -""" +"""The tests for the TCP sensor platform.""" import socket from copy import copy from uuid import uuid4 @@ -37,7 +32,7 @@ KEYS_AND_DEFAULTS = { @patch('homeassistant.components.sensor.tcp.Sensor.update') def test_setup_platform_valid_config(mock_update): - """ Should check the supplied config and call add_entities with Sensor. """ + """Should check the supplied config and call add_entities with Sensor.""" add_entities = Mock() ret = tcp.setup_platform(None, TEST_CONFIG, add_entities) assert ret is None, "setup_platform() should return None if successful." @@ -46,30 +41,32 @@ def test_setup_platform_valid_config(mock_update): def test_setup_platform_invalid_config(): - """ Should check the supplied config and return False if it is invalid. """ + """Should check the supplied config and return False if it is invalid.""" config = copy(TEST_CONFIG) del config[tcp.CONF_HOST] assert tcp.setup_platform(None, config, None) is False class TestTCPSensor(): - """ Test the TCP Sensor. """ + """Test the TCP Sensor.""" def setup_class(cls): + """Setup things to be run when tests are started.""" cls.hass = get_test_home_assistant() def teardown_class(cls): + """Stop everything that was started.""" cls.hass.stop() @patch('homeassistant.components.sensor.tcp.Sensor.update') def test_name(self, mock_update): - """ Should return the name if set in the config. """ + """Should return the name if set in the config.""" sensor = tcp.Sensor(self.hass, TEST_CONFIG) assert sensor.name == TEST_CONFIG[tcp.CONF_NAME] @patch('homeassistant.components.sensor.tcp.Sensor.update') def test_name_not_set(self, mock_update): - """ Should return the superclass name property if not set in config """ + """Should return the superclass name property if not set in config.""" config = copy(TEST_CONFIG) del config[tcp.CONF_NAME] entity = Entity() @@ -78,7 +75,7 @@ class TestTCPSensor(): @patch('homeassistant.components.sensor.tcp.Sensor.update') def test_state(self, mock_update): - """ Should return the contents of _state. """ + """Should return the contents of _state.""" sensor = tcp.Sensor(self.hass, TEST_CONFIG) uuid = str(uuid4()) sensor._state = uuid @@ -86,30 +83,24 @@ class TestTCPSensor(): @patch('homeassistant.components.sensor.tcp.Sensor.update') def test_unit_of_measurement(self, mock_update): - """ Should return the configured unit of measurement. """ + """Should return the configured unit of measurement.""" sensor = tcp.Sensor(self.hass, TEST_CONFIG) assert sensor.unit_of_measurement == TEST_CONFIG[tcp.CONF_UNIT] @patch("homeassistant.components.sensor.tcp.Sensor.update") def test_config_valid_keys(self, *args): - """ - Should store valid keys in _config. - """ + """Should store valid keys in _config.""" sensor = tcp.Sensor(self.hass, TEST_CONFIG) for key in TEST_CONFIG: assert key in sensor._config def test_validate_config_valid_keys(self): - """ - Should return True when provided with the correct keys. - """ + """Should return True when provided with the correct keys.""" assert tcp.Sensor.validate_config(TEST_CONFIG) @patch("homeassistant.components.sensor.tcp.Sensor.update") def test_config_invalid_keys(self, mock_update): - """ - Shouldn't store invalid keys in _config. - """ + """Shouldn't store invalid keys in _config.""" config = copy(TEST_CONFIG) config.update({ "a": "test_a", @@ -121,9 +112,7 @@ class TestTCPSensor(): assert invalid_key not in sensor._config def test_validate_config_invalid_keys(self): - """ - Should return True when provided with the correct keys plus some extra. - """ + """Test with invalid keys plus some extra.""" config = copy(TEST_CONFIG) config.update({ "a": "test_a", @@ -134,9 +123,7 @@ class TestTCPSensor(): @patch("homeassistant.components.sensor.tcp.Sensor.update") def test_config_uses_defaults(self, mock_update): - """ - Should use defaults where appropriate. - """ + """Should use defaults where appropriate.""" config = copy(TEST_CONFIG) for key in KEYS_AND_DEFAULTS.keys(): del config[key] @@ -145,18 +132,14 @@ class TestTCPSensor(): assert sensor._config[key] == default def test_validate_config_missing_defaults(self): - """ - Should return True when defaulted keys are not provided. - """ + """Should return True when defaulted keys are not provided.""" config = copy(TEST_CONFIG) for key in KEYS_AND_DEFAULTS.keys(): del config[key] assert tcp.Sensor.validate_config(config) def test_validate_config_missing_required(self): - """ - Should return False when required config items are missing. - """ + """Should return False when required config items are missing.""" for key in TEST_CONFIG: if key in KEYS_AND_DEFAULTS: continue @@ -168,18 +151,14 @@ class TestTCPSensor(): @patch("homeassistant.components.sensor.tcp.Sensor.update") def test_init_calls_update(self, mock_update): - """ - Should call update() method during __init__(). - """ + """Should call update() method during __init__().""" tcp.Sensor(self.hass, TEST_CONFIG) assert mock_update.called @patch("socket.socket") @patch("select.select", return_value=(True, False, False)) def test_update_connects_to_host_and_port(self, mock_select, mock_socket): - """ - Should connect to the configured host and port. - """ + """Should connect to the configured host and port.""" tcp.Sensor(self.hass, TEST_CONFIG) mock_socket = mock_socket().__enter__() assert mock_socket.connect.mock_calls[0][1] == (( @@ -188,9 +167,7 @@ class TestTCPSensor(): @patch("socket.socket.connect", side_effect=socket.error()) def test_update_returns_if_connecting_fails(self, *args): - """ - Should return if connecting to host fails. - """ + """Should return if connecting to host fails.""" with patch("homeassistant.components.sensor.tcp.Sensor.update"): sensor = tcp.Sensor(self.hass, TEST_CONFIG) assert sensor.update() is None @@ -198,9 +175,7 @@ class TestTCPSensor(): @patch("socket.socket.connect") @patch("socket.socket.send", side_effect=socket.error()) def test_update_returns_if_sending_fails(self, *args): - """ - Should return if sending fails. - """ + """Should return if sending fails.""" with patch("homeassistant.components.sensor.tcp.Sensor.update"): sensor = tcp.Sensor(self.hass, TEST_CONFIG) assert sensor.update() is None @@ -209,7 +184,7 @@ class TestTCPSensor(): @patch("socket.socket.send") @patch("select.select", return_value=(False, False, False)) def test_update_returns_if_select_fails(self, *args): - """ Should return if select fails to return a socket. """ + """Should return if select fails to return a socket.""" with patch("homeassistant.components.sensor.tcp.Sensor.update"): sensor = tcp.Sensor(self.hass, TEST_CONFIG) assert sensor.update() is None @@ -217,9 +192,7 @@ class TestTCPSensor(): @patch("socket.socket") @patch("select.select", return_value=(True, False, False)) def test_update_sends_payload(self, mock_select, mock_socket): - """ - Should send the configured payload as bytes. - """ + """Should send the configured payload as bytes.""" tcp.Sensor(self.hass, TEST_CONFIG) mock_socket = mock_socket().__enter__() mock_socket.send.assert_called_with( @@ -229,9 +202,7 @@ class TestTCPSensor(): @patch("socket.socket") @patch("select.select", return_value=(True, False, False)) def test_update_calls_select_with_timeout(self, mock_select, mock_socket): - """ - Should provide the timeout argument to select. - """ + """Should provide the timeout argument to select.""" tcp.Sensor(self.hass, TEST_CONFIG) mock_socket = mock_socket().__enter__() mock_select.assert_called_with( @@ -241,9 +212,7 @@ class TestTCPSensor(): @patch("select.select", return_value=(True, False, False)) def test_update_receives_packet_and_sets_as_state( self, mock_select, mock_socket): - """ - Should receive the response from the socket and set it as the state. - """ + """Test the response from the socket and set it as the state.""" test_value = "test_value" mock_socket = mock_socket().__enter__() mock_socket.recv.return_value = test_value.encode() @@ -255,9 +224,7 @@ class TestTCPSensor(): @patch("socket.socket") @patch("select.select", return_value=(True, False, False)) def test_update_renders_value_in_template(self, mock_select, mock_socket): - """ - Should render the value in the provided template. - """ + """Should render the value in the provided template.""" test_value = "test_value" mock_socket = mock_socket().__enter__() mock_socket.recv.return_value = test_value.encode() @@ -270,7 +237,7 @@ class TestTCPSensor(): @patch("select.select", return_value=(True, False, False)) def test_update_returns_if_template_render_fails( self, mock_select, mock_socket): - """ Should return None if rendering the template fails. """ + """Should return None if rendering the template fails.""" test_value = "test_value" mock_socket = mock_socket().__enter__() mock_socket.recv.return_value = test_value.encode() diff --git a/tests/components/sensor/test_template.py b/tests/components/sensor/test_template.py index 14603850296..aa657f04bfa 100644 --- a/tests/components/sensor/test_template.py +++ b/tests/components/sensor/test_template.py @@ -1,25 +1,22 @@ -""" -tests.components.sensor.test_template -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests template sensor. -""" +"""The test for the Template sensor platform.""" import homeassistant.components.sensor as sensor from tests.common import get_test_home_assistant class TestTemplateSensor: - """ Test the Template sensor. """ + """Test the Template sensor.""" def setup_method(self, method): + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def teardown_method(self, method): - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_template(self): + """Test template.""" assert sensor.setup(self.hass, { 'sensor': { 'platform': 'template', @@ -41,6 +38,7 @@ class TestTemplateSensor: assert state.state == 'It Works.' def test_template_syntax_error(self): + """Test templating syntax error.""" assert sensor.setup(self.hass, { 'sensor': { 'platform': 'template', @@ -59,6 +57,7 @@ class TestTemplateSensor: assert state.state == 'error' def test_template_attribute_missing(self): + """Test missing attribute template.""" assert sensor.setup(self.hass, { 'sensor': { 'platform': 'template', @@ -75,6 +74,7 @@ class TestTemplateSensor: assert state.state == 'error' def test_invalid_name_does_not_create(self): + """Test invalid name.""" assert sensor.setup(self.hass, { 'sensor': { 'platform': 'template', @@ -89,6 +89,7 @@ class TestTemplateSensor: assert self.hass.states.all() == [] def test_invalid_sensor_does_not_create(self): + """Test invalid sensor.""" assert sensor.setup(self.hass, { 'sensor': { 'platform': 'template', @@ -100,6 +101,7 @@ class TestTemplateSensor: assert self.hass.states.all() == [] def test_no_sensors_does_not_create(self): + """Test no sensors.""" assert sensor.setup(self.hass, { 'sensor': { 'platform': 'template' @@ -108,6 +110,7 @@ class TestTemplateSensor: assert self.hass.states.all() == [] def test_missing_template_does_not_create(self): + """Test missing template.""" assert sensor.setup(self.hass, { 'sensor': { 'platform': 'template', diff --git a/tests/components/sensor/test_yr.py b/tests/components/sensor/test_yr.py index b01e51d78ba..aa15d7cf3ea 100644 --- a/tests/components/sensor/test_yr.py +++ b/tests/components/sensor/test_yr.py @@ -1,9 +1,4 @@ -""" -tests.components.sensor.test_yr -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests Yr sensor. -""" +"""The tests for the Yr sensor platform.""" from datetime import datetime from unittest.mock import patch @@ -17,18 +12,20 @@ from tests.common import get_test_home_assistant @pytest.mark.usefixtures('betamax_session') class TestSensorYr: - """ Test the Yr sensor. """ + """Test the Yr sensor.""" def setup_method(self, method): + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.config.latitude = 32.87336 self.hass.config.longitude = 117.22743 def teardown_method(self, method): - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_default_setup(self, betamax_session): + """Test the default setup.""" now = datetime(2016, 1, 5, 1, tzinfo=dt_util.UTC) with patch('homeassistant.components.sensor.yr.requests.Session', @@ -49,6 +46,7 @@ class TestSensorYr: assert state.attributes.get('unit_of_measurement') is None def test_custom_setup(self, betamax_session): + """Test a custom setup.""" now = datetime(2016, 1, 5, 1, tzinfo=dt_util.UTC) with patch('homeassistant.components.sensor.yr.requests.Session', diff --git a/tests/components/switch/__init__.py b/tests/components/switch/__init__.py index e69de29bb2d..46bea615959 100644 --- a/tests/components/switch/__init__.py +++ b/tests/components/switch/__init__.py @@ -0,0 +1 @@ +"""The tests for Switch platforms.""" diff --git a/tests/components/switch/test_command_line.py b/tests/components/switch/test_command_line.py index 3a717d5d44f..eef058aa50d 100644 --- a/tests/components/switch/test_command_line.py +++ b/tests/components/switch/test_command_line.py @@ -1,9 +1,4 @@ -""" -tests.components.switch.test_command_line -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests command switch. -""" +"""the tests for the Command line switch platform.""" import json import os import tempfile @@ -16,16 +11,18 @@ from tests.common import get_test_home_assistant class TestCommandSwitch(unittest.TestCase): - """ Test the command switch. """ + """Test the command switch.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_state_none(self): + """Test with none state.""" with tempfile.TemporaryDirectory() as tempdirname: path = os.path.join(tempdirname, 'switch_status') test_switch = { @@ -57,6 +54,7 @@ class TestCommandSwitch(unittest.TestCase): self.assertEqual(STATE_OFF, state.state) def test_state_value(self): + """Test with state value.""" with tempfile.TemporaryDirectory() as tempdirname: path = os.path.join(tempdirname, 'switch_status') test_switch = { @@ -90,6 +88,7 @@ class TestCommandSwitch(unittest.TestCase): self.assertEqual(STATE_OFF, state.state) def test_state_json_value(self): + """Test with state JSON value.""" with tempfile.TemporaryDirectory() as tempdirname: path = os.path.join(tempdirname, 'switch_status') oncmd = json.dumps({'status': 'ok'}) @@ -125,6 +124,7 @@ class TestCommandSwitch(unittest.TestCase): self.assertEqual(STATE_OFF, state.state) def test_state_code(self): + """Test with state code.""" with tempfile.TemporaryDirectory() as tempdirname: path = os.path.join(tempdirname, 'switch_status') test_switch = { diff --git a/tests/components/switch/test_init.py b/tests/components/switch/test_init.py index 6860ca85c3b..b49c7866984 100644 --- a/tests/components/switch/test_init.py +++ b/tests/components/switch/test_init.py @@ -1,9 +1,4 @@ -""" -tests.components.switch.test_init -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests switch component. -""" +"""The tests for the Switch component.""" # pylint: disable=too-many-public-methods,protected-access import unittest @@ -15,13 +10,12 @@ from tests.common import get_test_home_assistant class TestSwitch(unittest.TestCase): - """ Test the switch module. """ + """Test the switch module.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() - platform = loader.get_component('switch.test') - platform.init() self.assertTrue(switch.setup( self.hass, {switch.DOMAIN: {CONF_PLATFORM: 'test'}} @@ -32,11 +26,11 @@ class TestSwitch(unittest.TestCase): platform.DEVICES def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_methods(self): - """ Test is_on, turn_on, turn_off methods. """ + """Test is_on, turn_on, turn_off methods.""" self.assertTrue(switch.is_on(self.hass)) self.assertEqual( STATE_ON, @@ -81,7 +75,7 @@ class TestSwitch(unittest.TestCase): self.assertTrue(switch.is_on(self.hass, self.switch_3.entity_id)) def test_setup_two_platforms(self): - """ Test with bad config. """ + """Test with bad configuration.""" # Test if switch component returns 0 switches test_platform = loader.get_component('switch.test') test_platform.init(True) diff --git a/tests/components/switch/test_mfi.py b/tests/components/switch/test_mfi.py index 85b676eef58..5eccb88f2ca 100644 --- a/tests/components/switch/test_mfi.py +++ b/tests/components/switch/test_mfi.py @@ -1,9 +1,4 @@ -""" -tests.components.switch.test_mfi -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests mFi switch. -""" +"""The tests for the mFi switch platform.""" import unittest import unittest.mock as mock @@ -15,6 +10,8 @@ from tests.common import get_test_home_assistant class TestMfiSwitchSetup(test_mfi_sensor.TestMfiSensorSetup): + """Test the mFi switch.""" + PLATFORM = mfi COMPONENT = switch THING = 'switch' @@ -31,6 +28,7 @@ class TestMfiSwitchSetup(test_mfi_sensor.TestMfiSensorSetup): @mock.patch('mficlient.client.MFiClient') @mock.patch('homeassistant.components.switch.mfi.MfiSwitch') def test_setup_adds_proper_devices(self, mock_switch, mock_client): + """Test if setup adds devices.""" ports = {i: mock.MagicMock(model=model) for i, model in enumerate(mfi.SWITCH_MODELS)} ports['bad'] = mock.MagicMock(model='notaswitch') @@ -45,7 +43,10 @@ class TestMfiSwitchSetup(test_mfi_sensor.TestMfiSensorSetup): class TestMfiSwitch(unittest.TestCase): + """Test for mFi switch platform.""" + def setup_method(self, method): + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.config.latitude = 32.87336 self.hass.config.longitude = 117.22743 @@ -53,17 +54,20 @@ class TestMfiSwitch(unittest.TestCase): self.switch = mfi.MfiSwitch(self.port) def teardown_method(self, method): - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_name(self): + """Test the name.""" self.assertEqual(self.port.label, self.switch.name) def test_update(self): + """Test update.""" self.switch.update() self.port.refresh.assert_called_once_with() def test_update_with_target_state(self): + """Test update with target state.""" self.switch._target_state = True self.port.data = {} self.port.data['output'] = 'stale' @@ -75,24 +79,29 @@ class TestMfiSwitch(unittest.TestCase): self.assertEqual('untouched', self.port.data['output']) def test_turn_on(self): + """Test turn_on.""" self.switch.turn_on() self.port.control.assert_called_once_with(True) self.assertTrue(self.switch._target_state) def test_turn_off(self): + """Test turn_off.""" self.switch.turn_off() self.port.control.assert_called_once_with(False) self.assertFalse(self.switch._target_state) def test_current_power_mwh(self): + """Test current power.""" self.port.data = {'active_pwr': 1} self.assertEqual(1000, self.switch.current_power_mwh) def test_current_power_mwh_no_data(self): + """Test current power if there is no data.""" self.port.data = {'notpower': 123} self.assertEqual(0, self.switch.current_power_mwh) def test_device_state_attributes(self): + """Test the state attributes.""" self.port.data = {'v_rms': 1.25, 'i_rms': 2.75} self.assertEqual({'volts': 1.2, 'amps': 2.8}, diff --git a/tests/components/switch/test_mqtt.py b/tests/components/switch/test_mqtt.py index 17bc65c7e5a..c26ceb26dc2 100644 --- a/tests/components/switch/test_mqtt.py +++ b/tests/components/switch/test_mqtt.py @@ -1,9 +1,4 @@ -""" -tests.components.switch.test_mqtt -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests MQTT switch. -""" +"""The tests for the MQTT switch platform.""" import unittest from homeassistant.const import STATE_ON, STATE_OFF, ATTR_ASSUMED_STATE @@ -13,17 +8,19 @@ from tests.common import ( class TestSensorMQTT(unittest.TestCase): - """ Test the MQTT switch. """ + """Test the MQTT switch.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.mock_publish = mock_mqtt_component(self.hass) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """"Stop everything that was started.""" self.hass.stop() def test_controlling_state_via_topic(self): + """Test the controlling state via topic.""" self.assertTrue(switch.setup(self.hass, { 'switch': { 'platform': 'mqtt', @@ -52,6 +49,7 @@ class TestSensorMQTT(unittest.TestCase): self.assertEqual(STATE_OFF, state.state) def test_sending_mqtt_commands_and_optimistic(self): + """Test the sending MQTT commands in optimistic mode.""" self.assertTrue(switch.setup(self.hass, { 'switch': { 'platform': 'mqtt', @@ -84,6 +82,7 @@ class TestSensorMQTT(unittest.TestCase): self.assertEqual(STATE_OFF, state.state) def test_controlling_state_via_topic_and_json_message(self): + """Test the controlling state via topic and JSON message.""" self.assertTrue(switch.setup(self.hass, { 'switch': { 'platform': 'mqtt', diff --git a/tests/components/switch/test_rfxtrx.py b/tests/components/switch/test_rfxtrx.py index 902f2256458..f9fe805fa46 100644 --- a/tests/components/switch/test_rfxtrx.py +++ b/tests/components/switch/test_rfxtrx.py @@ -1,10 +1,4 @@ -""" -tests.components.switch.test_rfxtrx -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests Rfxtrx switch. -""" - +"""The tests for the Rfxtrx switch platform.""" import unittest from homeassistant.components import rfxtrx as rfxtrx_core @@ -18,25 +12,25 @@ from tests.common import get_test_home_assistant @pytest.mark.skipif(True, reason='Does not clean up properly, takes 100% CPU') class TestSwitchRfxtrx(unittest.TestCase): - """ Test the Rfxtrx switch. """ + """Test the Rfxtrx switch platform.""" def setUp(self): - """ setup hass """ + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant(0) def tearDown(self): - """ Stop down stuff we started. """ + """Stop everything that was started.""" rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS = [] rfxtrx_core.RFX_DEVICES = {} self.hass.stop() def test_default_config(self): - """ Test with 0 switchs """ + """Test with 0 switches.""" config = {'devices': {}} devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add a callback to add devices.""" for dev in devs: devices.append(dev) @@ -44,7 +38,7 @@ class TestSwitchRfxtrx(unittest.TestCase): self.assertEqual(0, len(devices)) def test_one_sensor(self): - """ Test with 1 switch """ + """Test with 1 switch.""" config = {'devices': {'123efab1': { 'name': 'Test', @@ -56,7 +50,7 @@ class TestSwitchRfxtrx(unittest.TestCase): devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add a callback to add devices.""" for dev in devs: devices.append(dev) @@ -84,7 +78,7 @@ class TestSwitchRfxtrx(unittest.TestCase): self.assertFalse(entity.is_on) def test_several_switchs(self): - """ Test with 3 switchs """ + """Test with 3 switches.""" config = {'signal_repetitions': 3, 'devices': {'123efab1': { @@ -99,7 +93,7 @@ class TestSwitchRfxtrx(unittest.TestCase): devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add a callback to add devices.""" for dev in devs: devices.append(dev) @@ -125,12 +119,12 @@ class TestSwitchRfxtrx(unittest.TestCase): self.assertEqual(3, device_num) def test_discover_switch(self): - """ Test with discover of switch """ + """Test with discovery of switches.""" config = {'automatic_add': True, 'devices': {}} devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add a callback to add devices.""" for dev in devs: devices.append(dev) @@ -169,14 +163,14 @@ class TestSwitchRfxtrx(unittest.TestCase): self.assertEqual('', entity.__str__()) - # trying to add a sensor + # Trying to add a sensor event = rfxtrx_core.get_rfx_object('0a52085e070100b31b0279') event.data = bytearray(b'\nR\x08^\x07\x01\x00\xb3\x1b\x02y') rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) self.assertEqual(2, len(devices)) - # trying to add a light + # Trying to add a light event = rfxtrx_core.get_rfx_object('0b1100100118cdea02010f70') event.data = bytearray([0x0b, 0x11, 0x11, 0x10, 0x01, 0x18, 0xcd, 0xea, 0x01, 0x02, 0x0f, 0x70]) @@ -188,12 +182,12 @@ class TestSwitchRfxtrx(unittest.TestCase): self.assertEqual(2, len(devices)) def test_discover_switch_noautoadd(self): - """ Test with discover of switch when auto add is False """ + """Test with discovery of switch when auto add is False.""" config = {'automatic_add': False, 'devices': {}} devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add a callback to add devices.""" for dev in devs: devices.append(dev) @@ -226,14 +220,14 @@ class TestSwitchRfxtrx(unittest.TestCase): self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) self.assertEqual(0, len(devices)) - # trying to add a sensor + # Trying to add a sensor event = rfxtrx_core.get_rfx_object('0a52085e070100b31b0279') event.data = bytearray(b'\nR\x08^\x07\x01\x00\xb3\x1b\x02y') rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS[0](event) self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) self.assertEqual(0, len(devices)) - # trying to add a light + # Trying to add a light event = rfxtrx_core.get_rfx_object('0b1100100118cdea02010f70') event.data = bytearray([0x0b, 0x11, 0x11, 0x10, 0x01, 0x18, 0xcd, 0xea, 0x01, 0x02, 0x0f, 0x70]) diff --git a/tests/components/switch/test_template.py b/tests/components/switch/test_template.py index 73e82e6fdd6..1b8d6cf5ab9 100644 --- a/tests/components/switch/test_template.py +++ b/tests/components/switch/test_template.py @@ -1,9 +1,4 @@ -""" -tests.components.switch.template -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests template switch. -""" +"""The tests for the Template switch platform.""" import homeassistant.components as core import homeassistant.components.switch as switch @@ -15,11 +10,11 @@ from tests.common import get_test_home_assistant class TestTemplateSwitch: - """ Test the Template switch. """ + """Test the Template switch.""" def setup_method(self, method): + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() - self.calls = [] def record_call(service): @@ -28,10 +23,11 @@ class TestTemplateSwitch: self.hass.services.register('test', 'automation', record_call) def teardown_method(self, method): - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_template_state_text(self): + """"Test the state text of a template.""" assert switch.setup(self.hass, { 'switch': { 'platform': 'template', @@ -65,6 +61,7 @@ class TestTemplateSwitch: assert state.state == STATE_OFF def test_template_state_boolean_on(self): + """Test the setting of the state with boolean on.""" assert switch.setup(self.hass, { 'switch': { 'platform': 'template', @@ -89,6 +86,7 @@ class TestTemplateSwitch: assert state.state == STATE_ON def test_template_state_boolean_off(self): + """Test the setting of the state with off.""" assert switch.setup(self.hass, { 'switch': { 'platform': 'template', @@ -113,6 +111,7 @@ class TestTemplateSwitch: assert state.state == STATE_OFF def test_template_syntax_error(self): + """Test templating syntax error.""" assert switch.setup(self.hass, { 'switch': { 'platform': 'template', @@ -139,6 +138,7 @@ class TestTemplateSwitch: assert state.state == 'unavailable' def test_invalid_name_does_not_create(self): + """Test invalid name.""" assert switch.setup(self.hass, { 'switch': { 'platform': 'template', @@ -161,6 +161,7 @@ class TestTemplateSwitch: assert self.hass.states.all() == [] def test_invalid_switch_does_not_create(self): + """Test invalid name.""" assert switch.setup(self.hass, { 'switch': { 'platform': 'template', @@ -172,6 +173,7 @@ class TestTemplateSwitch: assert self.hass.states.all() == [] def test_no_switches_does_not_create(self): + """Test if there are no switches no creation.""" assert switch.setup(self.hass, { 'switch': { 'platform': 'template' @@ -180,6 +182,7 @@ class TestTemplateSwitch: assert self.hass.states.all() == [] def test_missing_template_does_not_create(self): + """Test missing template.""" assert switch.setup(self.hass, { 'switch': { 'platform': 'template', @@ -202,6 +205,7 @@ class TestTemplateSwitch: assert self.hass.states.all() == [] def test_missing_on_does_not_create(self): + """Test missing on.""" assert switch.setup(self.hass, { 'switch': { 'platform': 'template', @@ -224,6 +228,7 @@ class TestTemplateSwitch: assert self.hass.states.all() == [] def test_missing_off_does_not_create(self): + """Test missing off.""" assert switch.setup(self.hass, { 'switch': { 'platform': 'template', @@ -246,6 +251,7 @@ class TestTemplateSwitch: assert self.hass.states.all() == [] def test_on_action(self): + """Test on action.""" assert switch.setup(self.hass, { 'switch': { 'platform': 'template', @@ -276,6 +282,7 @@ class TestTemplateSwitch: assert 1 == len(self.calls) def test_off_action(self): + """Test off action.""" assert switch.setup(self.hass, { 'switch': { 'platform': 'template', diff --git a/tests/components/test_alexa.py b/tests/components/test_alexa.py index fcdc4b09937..b004ab642ed 100644 --- a/tests/components/test_alexa.py +++ b/tests/components/test_alexa.py @@ -1,9 +1,4 @@ -""" -tests.components.test_alexa -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests Home Assistant Alexa component does what it should do. -""" +"""The tests for the Alexa component.""" # pylint: disable=protected-access,too-many-public-methods import unittest import json @@ -29,7 +24,7 @@ calls = [] def setUpModule(): # pylint: disable=invalid-name - """ Initalize a Home Assistant server for testing this module. """ + """Initialize a Home Assistant server for testing this module.""" global hass hass = get_test_home_assistant() @@ -90,7 +85,7 @@ def setUpModule(): # pylint: disable=invalid-name def tearDownModule(): # pylint: disable=invalid-name - """ Stops the Home Assistant server. """ + """Stop the Home Assistant server.""" hass.stop() @@ -100,12 +95,14 @@ def _req(data={}): class TestAlexa(unittest.TestCase): - """ Test Alexa. """ + """Test Alexa.""" def tearDown(self): + """Stop everything that was started.""" hass.pool.block_till_done() def test_launch_request(self): + """Test the launch of a request.""" data = { 'version': '1.0', 'session': { @@ -131,6 +128,7 @@ class TestAlexa(unittest.TestCase): self.assertIn('outputSpeech', resp['response']) def test_intent_request_with_slots(self): + """Test a request with slots.""" data = { 'version': '1.0', 'session': { @@ -172,6 +170,7 @@ class TestAlexa(unittest.TestCase): self.assertEqual('You told us your sign is virgo.', text) def test_intent_request_with_slots_but_no_value(self): + """Test a request with slots but no value.""" data = { 'version': '1.0', 'session': { @@ -212,6 +211,7 @@ class TestAlexa(unittest.TestCase): self.assertEqual('You told us your sign is .', text) def test_intent_request_without_slots(self): + """Test a request without slots.""" data = { 'version': '1.0', 'session': { @@ -258,6 +258,7 @@ class TestAlexa(unittest.TestCase): self.assertEqual('You are both home, you silly', text) def test_intent_request_calling_service(self): + """Test a request for calling a service.""" data = { 'version': '1.0', 'session': { @@ -291,6 +292,7 @@ class TestAlexa(unittest.TestCase): self.assertEqual(1, call.data.get('hello')) def test_session_ended_request(self): + """Test the request for ending the session.""" data = { 'version': '1.0', 'session': { diff --git a/tests/components/test_api.py b/tests/components/test_api.py index 87f67414e0f..fb571fe5811 100644 --- a/tests/components/test_api.py +++ b/tests/components/test_api.py @@ -1,9 +1,4 @@ -""" -tests.components.test_api -~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests Home Assistant HTTP component does what it should do. -""" +"""The tests for the Home Assistant HTTP component.""" # pylint: disable=protected-access,too-many-public-methods from contextlib import closing import json @@ -28,12 +23,12 @@ hass = None def _url(path=""): - """ Helper method to generate urls. """ + """Helper method to generate URLs.""" return HTTP_BASE_URL + path def setUpModule(): # pylint: disable=invalid-name - """ Initializes a Home Assistant server. """ + """Initialize a Home Assistant server.""" global hass hass = get_test_home_assistant() @@ -52,23 +47,26 @@ def setUpModule(): # pylint: disable=invalid-name def tearDownModule(): # pylint: disable=invalid-name - """ Stops the Home Assistant server. """ + """Stop the Home Assistant server.""" hass.stop() class TestAPI(unittest.TestCase): - """ Test the API. """ + """Test the API.""" def tearDown(self): + """Stop everything that was started.""" hass.pool.block_till_done() # TODO move back to http component and test with use_auth. def test_access_denied_without_password(self): + """Test access without password.""" req = requests.get(_url(const.URL_API)) self.assertEqual(401, req.status_code) def test_access_denied_with_wrong_password(self): + """Test ascces with wrong password.""" req = requests.get( _url(const.URL_API), headers={const.HTTP_HEADER_HA_AUTH: 'wrongpassword'}) @@ -76,12 +74,14 @@ class TestAPI(unittest.TestCase): self.assertEqual(401, req.status_code) def test_access_with_password_in_url(self): + """Test access with password in URL.""" req = requests.get( "{}?api_password={}".format(_url(const.URL_API), API_PASSWORD)) self.assertEqual(200, req.status_code) def test_access_via_session(self): + """Test access wia session.""" session = requests.Session() req = session.get(_url(const.URL_API), headers=HA_HEADERS) self.assertEqual(200, req.status_code) @@ -90,7 +90,7 @@ class TestAPI(unittest.TestCase): self.assertEqual(200, req.status_code) def test_api_list_state_entities(self): - """ Test if the debug interface allows us to list state entities. """ + """Test if the debug interface allows us to list state entities.""" req = requests.get(_url(const.URL_API_STATES), headers=HA_HEADERS) @@ -99,7 +99,7 @@ class TestAPI(unittest.TestCase): self.assertEqual(hass.states.all(), remote_data) def test_api_get_state(self): - """ Test if the debug interface allows us to get a state. """ + """Test if the debug interface allows us to get a state.""" req = requests.get( _url(const.URL_API_STATES_ENTITY.format("test.test")), headers=HA_HEADERS) @@ -113,7 +113,7 @@ class TestAPI(unittest.TestCase): self.assertEqual(state.attributes, data.attributes) def test_api_get_non_existing_state(self): - """ Test if the debug interface allows us to get a state. """ + """Test if the debug interface allows us to get a state.""" req = requests.get( _url(const.URL_API_STATES_ENTITY.format("does_not_exist")), headers=HA_HEADERS) @@ -121,8 +121,7 @@ class TestAPI(unittest.TestCase): self.assertEqual(404, req.status_code) def test_api_state_change(self): - """ Test if we can change the state of an entity that exists. """ - + """Test if we can change the state of an entity that exists.""" hass.states.set("test.test", "not_to_be_set") requests.post(_url(const.URL_API_STATES_ENTITY.format("test.test")), @@ -134,9 +133,7 @@ class TestAPI(unittest.TestCase): # pylint: disable=invalid-name def test_api_state_change_of_non_existing_entity(self): - """ Test if the API allows us to change a state of - a non existing entity. """ - + """Test if changing a state of a non existing entity is possible.""" new_state = "debug_state_change" req = requests.post( @@ -153,8 +150,7 @@ class TestAPI(unittest.TestCase): # pylint: disable=invalid-name def test_api_state_change_with_bad_data(self): - """ Test if API sends appropriate error if we omit state. """ - + """Test if API sends appropriate error if we omit state.""" req = requests.post( _url(const.URL_API_STATES_ENTITY.format( "test_entity.that_does_not_exist")), @@ -165,11 +161,11 @@ class TestAPI(unittest.TestCase): # pylint: disable=invalid-name def test_api_fire_event_with_no_data(self): - """ Test if the API allows us to fire an event. """ + """Test if the API allows us to fire an event.""" test_value = [] def listener(event): - """ Helper method that will verify our event got called. """ + """Helper method that will verify our event got called.""" test_value.append(1) hass.bus.listen_once("test.event_no_data", listener) @@ -184,12 +180,14 @@ class TestAPI(unittest.TestCase): # pylint: disable=invalid-name def test_api_fire_event_with_data(self): - """ Test if the API allows us to fire an event. """ + """Test if the API allows us to fire an event.""" test_value = [] def listener(event): - """ Helper method that will verify that our event got called and - that test if our data came through. """ + """Helper method that will verify that our event got called. + + Also test if our data came through. + """ if "test" in event.data: test_value.append(1) @@ -206,11 +204,11 @@ class TestAPI(unittest.TestCase): # pylint: disable=invalid-name def test_api_fire_event_with_invalid_json(self): - """ Test if the API allows us to fire an event. """ + """Test if the API allows us to fire an event.""" test_value = [] def listener(event): - """ Helper method that will verify our event got called. """ + """Helper method that will verify our event got called.""" test_value.append(1) hass.bus.listen_once("test_event_bad_data", listener) @@ -237,16 +235,19 @@ class TestAPI(unittest.TestCase): self.assertEqual(0, len(test_value)) def test_api_get_config(self): + """Test the return of the configuration.""" req = requests.get(_url(const.URL_API_CONFIG), headers=HA_HEADERS) self.assertEqual(hass.config.as_dict(), req.json()) def test_api_get_components(self): + """Test the return of the components.""" req = requests.get(_url(const.URL_API_COMPONENTS), headers=HA_HEADERS) self.assertEqual(hass.config.components, req.json()) def test_api_get_error_log(self): + """Test the return of the error log.""" test_content = 'Test String' with tempfile.NamedTemporaryFile() as log: log.write(test_content.encode('utf-8')) @@ -259,7 +260,7 @@ class TestAPI(unittest.TestCase): self.assertIsNone(req.headers.get('expires')) def test_api_get_event_listeners(self): - """ Test if we can get the list of events being listened for. """ + """Test if we can get the list of events being listened for.""" req = requests.get(_url(const.URL_API_EVENTS), headers=HA_HEADERS) @@ -272,7 +273,7 @@ class TestAPI(unittest.TestCase): self.assertEqual(0, len(local)) def test_api_get_services(self): - """ Test if we can get a dict describing current services. """ + """Test if we can get a dict describing current services.""" req = requests.get(_url(const.URL_API_SERVICES), headers=HA_HEADERS) @@ -284,11 +285,11 @@ class TestAPI(unittest.TestCase): self.assertEqual(local, serv_domain["services"]) def test_api_call_service_no_data(self): - """ Test if the API allows us to call a service. """ + """Test if the API allows us to call a service.""" test_value = [] def listener(service_call): - """ Helper method that will verify that our service got called. """ + """Helper method that will verify that our service got called.""" test_value.append(1) hass.services.register("test_domain", "test_service", listener) @@ -303,12 +304,14 @@ class TestAPI(unittest.TestCase): self.assertEqual(1, len(test_value)) def test_api_call_service_with_data(self): - """ Test if the API allows us to call a service. """ + """Test if the API allows us to call a service.""" test_value = [] def listener(service_call): - """ Helper method that will verify that our service got called and - that test if our data came through. """ + """Helper method that will verify that our service got called. + + Also test if our data came through. + """ if "test" in service_call.data: test_value.append(1) @@ -325,7 +328,7 @@ class TestAPI(unittest.TestCase): self.assertEqual(1, len(test_value)) def test_api_template(self): - """ Test template API. """ + """Test the template API.""" hass.states.set('sensor.temperature', 10) req = requests.post( @@ -337,7 +340,7 @@ class TestAPI(unittest.TestCase): self.assertEqual('10', req.text) def test_api_template_error(self): - """ Test template API. """ + """Test the template API.""" hass.states.set('sensor.temperature', 10) req = requests.post( @@ -349,8 +352,7 @@ class TestAPI(unittest.TestCase): self.assertEqual(422, req.status_code) def test_api_event_forward(self): - """ Test setting up event forwarding. """ - + """Test setting up event forwarding.""" req = requests.post( _url(const.URL_API_EVENT_FORWARD), headers=HA_HEADERS) @@ -425,6 +427,7 @@ class TestAPI(unittest.TestCase): self.assertEqual(200, req.status_code) def test_stream(self): + """Test the stream.""" listen_count = self._listen_count() with closing(requests.get(_url(const.URL_API_STREAM), stream=True, headers=HA_HEADERS)) as req: @@ -442,6 +445,7 @@ class TestAPI(unittest.TestCase): self.assertEqual('test_event', data['event_type']) def test_stream_with_restricted(self): + """Test the stream with restrictions.""" listen_count = self._listen_count() with closing(requests.get(_url(const.URL_API_STREAM), data=json.dumps({ @@ -466,6 +470,7 @@ class TestAPI(unittest.TestCase): self.assertEqual('test_event3', data['event_type']) def _stream_next_event(self, stream): + """Test the stream for next event.""" data = b'' last_new_line = False for dat in stream.iter_content(1): @@ -479,5 +484,5 @@ class TestAPI(unittest.TestCase): return conv if conv == 'ping' else json.loads(conv) def _listen_count(self): - """ Return number of event listeners. """ + """Return number of event listeners.""" return sum(hass.bus.listeners.values()) diff --git a/tests/components/test_configurator.py b/tests/components/test_configurator.py index 28b4ea126c9..d45f64cf2ad 100644 --- a/tests/components/test_configurator.py +++ b/tests/components/test_configurator.py @@ -1,9 +1,4 @@ -""" -tests.components.test_configurator -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests Configurator component. -""" +"""The tests for the Configurator component.""" # pylint: disable=too-many-public-methods,protected-access import unittest @@ -14,18 +9,18 @@ from tests.common import get_test_home_assistant class TestConfigurator(unittest.TestCase): - """ Test the chromecast module. """ + """Test the Configurator component.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_request_least_info(self): - """ Test request config with least amount of data. """ - + """Test request config with least amount of data.""" request_id = configurator.request_config( self.hass, "Test Request", lambda _: None) @@ -44,8 +39,7 @@ class TestConfigurator(unittest.TestCase): request_id, state.attributes.get(configurator.ATTR_CONFIGURE_ID)) def test_request_all_info(self): - """ Test request config with all possible info. """ - + """Test request config with all possible info.""" values = [ "config_description", "config image url", "config submit caption", []] @@ -61,18 +55,15 @@ class TestConfigurator(unittest.TestCase): *values) states = self.hass.states.all() - self.assertEqual(1, len(states)) - state = states[0] self.assertEqual(configurator.STATE_CONFIGURE, state.state) self.assertEqual(exp_attr, state.attributes) def test_callback_called_on_configure(self): - """ Test if our callback gets called when configure service called. """ + """Test if our callback gets called when configure service called.""" calls = [] - request_id = configurator.request_config( self.hass, "Test Request", lambda _: calls.append(1)) @@ -81,41 +72,33 @@ class TestConfigurator(unittest.TestCase): {configurator.ATTR_CONFIGURE_ID: request_id}) self.hass.pool.block_till_done() - self.assertEqual(1, len(calls), "Callback not called") def test_state_change_on_notify_errors(self): - """ Test state change on notify errors. """ + """Test state change on notify errors.""" request_id = configurator.request_config( self.hass, "Test Request", lambda _: None) - error = "Oh no bad bad bad" - configurator.notify_errors(request_id, error) state = self.hass.states.all()[0] - self.assertEqual(error, state.attributes.get(configurator.ATTR_ERRORS)) def test_notify_errors_fail_silently_on_bad_request_id(self): - """ Test if notify errors fails silently with a bad request id. """ + """Test if notify errors fails silently with a bad request id.""" configurator.notify_errors(2015, "Try this error") def test_request_done_works(self): - """ Test if calling request done works. """ + """Test if calling request done works.""" request_id = configurator.request_config( self.hass, "Test Request", lambda _: None) - configurator.request_done(request_id) - self.assertEqual(1, len(self.hass.states.all())) self.hass.bus.fire(EVENT_TIME_CHANGED) - self.hass.pool.block_till_done() - self.assertEqual(0, len(self.hass.states.all())) def test_request_done_fail_silently_on_bad_request_id(self): - """ Test that request_done fails silently with a bad request id. """ + """Test that request_done fails silently with a bad request id.""" configurator.request_done(2016) diff --git a/tests/components/test_conversation.py b/tests/components/test_conversation.py index 2b41349c126..311efbf8a07 100644 --- a/tests/components/test_conversation.py +++ b/tests/components/test_conversation.py @@ -1,9 +1,4 @@ -""" -tests.components.test_conversation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests Conversation component. -""" +"""The tests for the Conversation component.""" # pylint: disable=too-many-public-methods,protected-access import unittest from unittest.mock import patch @@ -16,10 +11,10 @@ from tests.common import get_test_home_assistant class TestConversation(unittest.TestCase): - """ Test the conversation component. """ + """Test the conversation component.""" def setUp(self): # pylint: disable=invalid-name - """ Start up ha for testing """ + """Setup things to be run when tests are started.""" self.ent_id = 'light.kitchen_lights' self.hass = get_test_home_assistant(3) self.hass.states.set(self.ent_id, 'on') @@ -28,11 +23,11 @@ class TestConversation(unittest.TestCase): conversation.setup(self.hass, {conversation.DOMAIN: {}})) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_turn_on(self): - """ Setup and perform good turn on requests """ + """Setup and perform good turn on requests.""" calls = [] def record_call(service): @@ -50,7 +45,7 @@ class TestConversation(unittest.TestCase): self.assertEqual([self.ent_id], call.data[ATTR_ENTITY_ID]) def test_turn_off(self): - """ Setup and perform good turn off requests """ + """Setup and perform good turn off requests.""" calls = [] def record_call(service): @@ -70,7 +65,7 @@ class TestConversation(unittest.TestCase): @patch('homeassistant.components.conversation.logging.Logger.error') @patch('homeassistant.core.ServiceRegistry.call') def test_bad_request_format(self, mock_logger, mock_call): - """ Setup and perform a badly formatted request """ + """Setup and perform a badly formatted request.""" event_data = { conversation.ATTR_TEXT: 'what is the answer to the ultimate question of life, ' + @@ -83,7 +78,7 @@ class TestConversation(unittest.TestCase): @patch('homeassistant.components.conversation.logging.Logger.error') @patch('homeassistant.core.ServiceRegistry.call') def test_bad_request_entity(self, mock_logger, mock_call): - """ Setup and perform requests with bad entity id """ + """Setup and perform requests with bad entity id.""" event_data = {conversation.ATTR_TEXT: 'turn something off'} self.assertTrue(self.hass.services.call( conversation.DOMAIN, 'process', event_data, True)) @@ -93,7 +88,7 @@ class TestConversation(unittest.TestCase): @patch('homeassistant.components.conversation.logging.Logger.error') @patch('homeassistant.core.ServiceRegistry.call') def test_bad_request_command(self, mock_logger, mock_call): - """ Setup and perform requests with bad command """ + """Setup and perform requests with bad command.""" event_data = {conversation.ATTR_TEXT: 'turn kitchen lights over'} self.assertTrue(self.hass.services.call( conversation.DOMAIN, 'process', event_data, True)) @@ -103,7 +98,7 @@ class TestConversation(unittest.TestCase): @patch('homeassistant.components.conversation.logging.Logger.error') @patch('homeassistant.core.ServiceRegistry.call') def test_bad_request_notext(self, mock_logger, mock_call): - """ Setup and perform requests with bad command with no text """ + """Setup and perform requests with bad command with no text.""" event_data = {} self.assertTrue(self.hass.services.call( conversation.DOMAIN, 'process', event_data, True)) diff --git a/tests/components/test_demo.py b/tests/components/test_demo.py index ec53e33e8fa..c6abe66a7ce 100644 --- a/tests/components/test_demo.py +++ b/tests/components/test_demo.py @@ -1,9 +1,4 @@ -""" -tests.test_component_demo -~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests demo component. -""" +"""The tests for the Demo component.""" import json import os import unittest @@ -17,14 +12,15 @@ from tests.common import mock_http_component, get_test_home_assistant @patch('homeassistant.components.sun.setup') class TestDemo(unittest.TestCase): - """ Test the demo module. """ + """Test the Demo component.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() mock_http_component(self.hass) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() try: @@ -33,19 +29,19 @@ class TestDemo(unittest.TestCase): pass def test_if_demo_state_shows_by_default(self, mock_sun_setup): - """ Test if demo state shows if we give no configuration. """ + """Test if demo state shows if we give no configuration.""" demo.setup(self.hass, {demo.DOMAIN: {}}) self.assertIsNotNone(self.hass.states.get('a.Demo_Mode')) def test_hiding_demo_state(self, mock_sun_setup): - """ Test if you can hide the demo card. """ + """Test if you can hide the demo card.""" demo.setup(self.hass, {demo.DOMAIN: {'hide_demo_state': 1}}) self.assertIsNone(self.hass.states.get('a.Demo_Mode')) def test_all_entities_can_be_loaded_over_json(self, mock_sun_setup): - """ Test if you can hide the demo card. """ + """Test if you can hide the demo card.""" demo.setup(self.hass, {demo.DOMAIN: {'hide_demo_state': 1}}) try: diff --git a/tests/components/test_device_sun_light_trigger.py b/tests/components/test_device_sun_light_trigger.py index 0309ac1fb75..ff134465174 100644 --- a/tests/components/test_device_sun_light_trigger.py +++ b/tests/components/test_device_sun_light_trigger.py @@ -1,4 +1,4 @@ -"""Tests device sun light trigger component.""" +"""The tests device sun light trigger component.""" # pylint: disable=too-many-public-methods,protected-access import os import unittest @@ -37,9 +37,10 @@ def tearDownModule(): # pylint: disable=invalid-name class TestDeviceSunLightTrigger(unittest.TestCase): - """ Test the device sun light trigger module. """ + """Test the device sun light trigger module.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() event_decorators.HASS = self.hass @@ -63,30 +64,27 @@ class TestDeviceSunLightTrigger(unittest.TestCase): self.hass, {sun.DOMAIN: {sun.CONF_ELEVATION: 0}})) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() event_decorators.HASS = None def test_lights_on_when_sun_sets(self): - """ Test lights go on when there is someone home and the sun sets. """ - + """Test lights go on when there is someone home and the sun sets.""" self.assertTrue(device_sun_light_trigger.setup( self.hass, {device_sun_light_trigger.DOMAIN: {}})) ensure_sun_risen(self.hass) - light.turn_off(self.hass) self.hass.pool.block_till_done() ensure_sun_set(self.hass) - self.hass.pool.block_till_done() self.assertTrue(light.is_on(self.hass)) def test_lights_turn_off_when_everyone_leaves(self): - """ Test lights turn off when everyone leaves the house. """ + """Test lights turn off when everyone leaves the house.""" light.turn_on(self.hass) self.hass.pool.block_till_done() @@ -102,9 +100,8 @@ class TestDeviceSunLightTrigger(unittest.TestCase): self.assertFalse(light.is_on(self.hass)) def test_lights_turn_on_when_coming_home_after_sun_set(self): - """ Test lights turn on when coming home after sun set. """ + """Test lights turn on when coming home after sun set.""" light.turn_off(self.hass) - ensure_sun_set(self.hass) self.hass.pool.block_till_done() @@ -116,5 +113,4 @@ class TestDeviceSunLightTrigger(unittest.TestCase): device_tracker.ENTITY_ID_FORMAT.format('device_2'), STATE_HOME) self.hass.pool.block_till_done() - self.assertTrue(light.is_on(self.hass)) diff --git a/tests/components/test_frontend.py b/tests/components/test_frontend.py index a9fb6550a9f..24ee426645e 100644 --- a/tests/components/test_frontend.py +++ b/tests/components/test_frontend.py @@ -1,9 +1,4 @@ -""" -tests.test_component_http -~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests Home Assistant HTTP component does what it should do. -""" +"""The tests for Home Assistant frontend.""" # pylint: disable=protected-access,too-many-public-methods import re import unittest @@ -25,12 +20,12 @@ hass = None def _url(path=""): - """ Helper method to generate urls. """ + """Helper method to generate URLs.""" return HTTP_BASE_URL + path def setUpModule(): # pylint: disable=invalid-name - """ Initalizes a Home Assistant server. """ + """Initialize a Home Assistant server.""" global hass hass = get_test_home_assistant() @@ -49,18 +44,19 @@ def setUpModule(): # pylint: disable=invalid-name def tearDownModule(): # pylint: disable=invalid-name - """ Stops the Home Assistant server. """ + """Stop everything that was started.""" hass.stop() class TestFrontend(unittest.TestCase): - """ Test the frontend. """ + """Test the frontend.""" def tearDown(self): + """Stop everything that was started.""" hass.pool.block_till_done() def test_frontend_and_static(self): - """ Tests if we can get the frontend. """ + """Test if we can get the frontend.""" req = requests.get(_url("")) self.assertEqual(200, req.status_code) @@ -77,6 +73,7 @@ class TestFrontend(unittest.TestCase): self.assertEqual(200, req.status_code) def test_auto_filling_in_api_password(self): + """Test for auto filling of API password.""" req = requests.get( _url("?{}={}".format(http.DATA_API_PASSWORD, API_PASSWORD))) @@ -87,7 +84,9 @@ class TestFrontend(unittest.TestCase): self.assertIsNotNone(auth_text) def test_404(self): + """Test for HTTP 404 error.""" self.assertEqual(404, requests.get(_url("/not-existing")).status_code) def test_we_cannot_POST_to_root(self): + """Test that POST is not allow to root.""" self.assertEqual(405, requests.post(_url("")).status_code) diff --git a/tests/components/test_graphite.py b/tests/components/test_graphite.py index 3faaa4c1659..9e9ea837dfe 100644 --- a/tests/components/test_graphite.py +++ b/tests/components/test_graphite.py @@ -1,9 +1,4 @@ -""" -tests.components.test_graphite -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests graphite feeder. -""" +"""The tests for the Graphite component.""" import socket import unittest from unittest import mock @@ -19,23 +14,28 @@ from tests.common import get_test_home_assistant class TestGraphite(unittest.TestCase): + """Test the Graphite component.""" + def setup_method(self, method): + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.config.latitude = 32.87336 self.hass.config.longitude = 117.22743 self.gf = graphite.GraphiteFeeder(self.hass, 'foo', 123, 'ha') def teardown_method(self, method): - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() @mock.patch('homeassistant.components.graphite.GraphiteFeeder') def test_minimal_config(self, mock_gf): + """Test setup with minimal configuration.""" self.assertTrue(graphite.setup(self.hass, {})) mock_gf.assert_called_once_with(self.hass, 'localhost', 2003, 'ha') @mock.patch('homeassistant.components.graphite.GraphiteFeeder') def test_full_config(self, mock_gf): + """Test setup with full configuration.""" config = { 'graphite': { 'host': 'foo', @@ -48,6 +48,7 @@ class TestGraphite(unittest.TestCase): @mock.patch('homeassistant.components.graphite.GraphiteFeeder') def test_config_bad_port(self, mock_gf): + """Test setup with invalid port.""" config = { 'graphite': { 'host': 'foo', @@ -58,6 +59,7 @@ class TestGraphite(unittest.TestCase): self.assertFalse(mock_gf.called) def test_subscribe(self): + """Test the subscription.""" fake_hass = mock.MagicMock() gf = graphite.GraphiteFeeder(fake_hass, 'foo', 123, 'ha') fake_hass.bus.listen_once.has_calls([ @@ -68,22 +70,26 @@ class TestGraphite(unittest.TestCase): EVENT_STATE_CHANGED, gf.event_listener) def test_start(self): + """Test the start.""" with mock.patch.object(self.gf, 'start') as mock_start: self.gf.start_listen('event') mock_start.assert_called_once_with() def test_shutdown(self): + """Test the shutdown.""" with mock.patch.object(self.gf, '_queue') as mock_queue: self.gf.shutdown('event') mock_queue.put.assert_called_once_with(self.gf._quit_object) def test_event_listener(self): + """Test the event listener.""" with mock.patch.object(self.gf, '_queue') as mock_queue: self.gf.event_listener('foo') mock_queue.put.assert_called_once_with('foo') @mock.patch('time.time') def test_report_attributes(self, mock_time): + """Test the reporting with attributes.""" mock_time.return_value = 12345 attrs = {'foo': 1, 'bar': 2.0, @@ -104,6 +110,7 @@ class TestGraphite(unittest.TestCase): @mock.patch('time.time') def test_report_with_string_state(self, mock_time): + """Test the reporting with strings.""" mock_time.return_value = 12345 expected = [ 'ha.entity.foo 1.000000 12345', @@ -117,6 +124,7 @@ class TestGraphite(unittest.TestCase): @mock.patch('time.time') def test_report_with_binary_state(self, mock_time): + """Test the reporting with binary state.""" mock_time.return_value = 12345 state = ha.State('domain.entity', STATE_ON, {'foo': 1.0}) with mock.patch.object(self.gf, '_send_to_graphite') as mock_send: @@ -136,6 +144,7 @@ class TestGraphite(unittest.TestCase): @mock.patch('time.time') def test_send_to_graphite_errors(self, mock_time): + """Test the sending with errors.""" mock_time.return_value = 12345 state = ha.State('domain.entity', STATE_ON, {'foo': 1.0}) with mock.patch.object(self.gf, '_send_to_graphite') as mock_send: @@ -146,6 +155,7 @@ class TestGraphite(unittest.TestCase): @mock.patch('socket.socket') def test_send_to_graphite(self, mock_socket): + """Test the sending of data.""" self.gf._send_to_graphite('foo') mock_socket.assert_called_once_with(socket.AF_INET, socket.SOCK_STREAM) @@ -156,6 +166,7 @@ class TestGraphite(unittest.TestCase): sock.close.assert_called_once_with() def test_run_stops(self): + """Test the stops.""" with mock.patch.object(self.gf, '_queue') as mock_queue: mock_queue.get.return_value = self.gf._quit_object self.assertEqual(None, self.gf.run()) @@ -163,6 +174,7 @@ class TestGraphite(unittest.TestCase): mock_queue.task_done.assert_called_once_with() def test_run(self): + """Test the running.""" runs = [] event = mock.MagicMock(event_type=EVENT_STATE_CHANGED, data={'entity_id': 'entity', diff --git a/tests/components/test_group.py b/tests/components/test_group.py index 8e5a5d8e0c8..3b4f3d43c29 100644 --- a/tests/components/test_group.py +++ b/tests/components/test_group.py @@ -1,9 +1,4 @@ -""" -tests.test_component_group -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests the group compoments. -""" +"""The tests for the Group components.""" # pylint: disable=protected-access,too-many-public-methods import unittest @@ -16,18 +11,18 @@ from tests.common import get_test_home_assistant class TestComponentsGroup(unittest.TestCase): - """ Tests homeassistant.components.group module. """ + """Test Group component.""" def setUp(self): # pylint: disable=invalid-name - """ Init needed objects. """ + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_setup_group_with_mixed_groupable_states(self): - """ Try to setup a group with mixed groupable states """ + """Try to setup a group with mixed groupable states.""" self.hass.states.set('light.Bowl', STATE_ON) self.hass.states.set('device_tracker.Paulus', STATE_HOME) group.Group( @@ -40,7 +35,7 @@ class TestComponentsGroup(unittest.TestCase): group.ENTITY_ID_FORMAT.format('person_and_light')).state) def test_setup_group_with_a_non_existing_state(self): - """ Try to setup a group with a non existing state """ + """Try to setup a group with a non existing state.""" self.hass.states.set('light.Bowl', STATE_ON) grp = group.Group( @@ -50,6 +45,7 @@ class TestComponentsGroup(unittest.TestCase): self.assertEqual(STATE_ON, grp.state) def test_setup_group_with_non_groupable_states(self): + """Test setup with groups which are not groupable.""" self.hass.states.set('cast.living_room', "Plex") self.hass.states.set('cast.bedroom', "Netflix") @@ -60,13 +56,13 @@ class TestComponentsGroup(unittest.TestCase): self.assertEqual(STATE_UNKNOWN, grp.state) def test_setup_empty_group(self): - """ Try to setup an empty group. """ + """Try to setup an empty group.""" grp = group.Group(self.hass, 'nothing', []) self.assertEqual(STATE_UNKNOWN, grp.state) def test_monitor_group(self): - """ Test if the group keeps track of states. """ + """Test if the group keeps track of states.""" self.hass.states.set('light.Bowl', STATE_ON) self.hass.states.set('light.Ceiling', STATE_OFF) test_group = group.Group( @@ -80,9 +76,7 @@ class TestComponentsGroup(unittest.TestCase): self.assertTrue(group_state.attributes.get(group.ATTR_AUTO)) def test_group_turns_off_if_all_off(self): - """ - Test if the group turns off if the last device that was on turns off. - """ + """Test if turn off if the last device that was on turns off.""" self.hass.states.set('light.Bowl', STATE_OFF) self.hass.states.set('light.Ceiling', STATE_OFF) test_group = group.Group( @@ -94,9 +88,7 @@ class TestComponentsGroup(unittest.TestCase): self.assertEqual(STATE_OFF, group_state.state) def test_group_turns_on_if_all_are_off_and_one_turns_on(self): - """ - Test if group turns on if all devices were turned off and one turns on. - """ + """Test if turn on if all devices were turned off and one turns on.""" self.hass.states.set('light.Bowl', STATE_OFF) self.hass.states.set('light.Ceiling', STATE_OFF) test_group = group.Group( @@ -110,7 +102,7 @@ class TestComponentsGroup(unittest.TestCase): self.assertEqual(STATE_ON, group_state.state) def test_is_on(self): - """ Test is_on method. """ + """Test is_on method.""" self.hass.states.set('light.Bowl', STATE_ON) self.hass.states.set('light.Ceiling', STATE_OFF) test_group = group.Group( @@ -125,7 +117,7 @@ class TestComponentsGroup(unittest.TestCase): self.assertFalse(group.is_on(self.hass, 'non.existing')) def test_expand_entity_ids(self): - """ Test expand_entity_ids method. """ + """Test expand_entity_ids method.""" self.hass.states.set('light.Bowl', STATE_ON) self.hass.states.set('light.Ceiling', STATE_OFF) test_group = group.Group( @@ -136,7 +128,7 @@ class TestComponentsGroup(unittest.TestCase): self.hass, [test_group.entity_id]))) def test_expand_entity_ids_does_not_return_duplicates(self): - """ Test that expand_entity_ids does not return duplicates. """ + """Test that expand_entity_ids does not return duplicates.""" self.hass.states.set('light.Bowl', STATE_ON) self.hass.states.set('light.Ceiling', STATE_OFF) test_group = group.Group( @@ -153,11 +145,11 @@ class TestComponentsGroup(unittest.TestCase): self.hass, ['light.bowl', test_group.entity_id]))) def test_expand_entity_ids_ignores_non_strings(self): - """ Test that non string elements in lists are ignored. """ + """Test that non string elements in lists are ignored.""" self.assertEqual([], group.expand_entity_ids(self.hass, [5, True])) def test_get_entity_ids(self): - """ Test get_entity_ids method. """ + """Test get_entity_ids method.""" self.hass.states.set('light.Bowl', STATE_ON) self.hass.states.set('light.Ceiling', STATE_OFF) test_group = group.Group( @@ -168,7 +160,7 @@ class TestComponentsGroup(unittest.TestCase): sorted(group.get_entity_ids(self.hass, test_group.entity_id))) def test_get_entity_ids_with_domain_filter(self): - """ Test if get_entity_ids works with a domain_filter. """ + """Test if get_entity_ids works with a domain_filter.""" self.hass.states.set('switch.AC', STATE_OFF) mixed_group = group.Group( @@ -180,16 +172,19 @@ class TestComponentsGroup(unittest.TestCase): self.hass, mixed_group.entity_id, domain_filter="switch")) def test_get_entity_ids_with_non_existing_group_name(self): - """ Tests get_entity_ids with a non existing group. """ + """Test get_entity_ids with a non existing group.""" self.assertEqual([], group.get_entity_ids(self.hass, 'non_existing')) def test_get_entity_ids_with_non_group_state(self): - """ Tests get_entity_ids with a non group state. """ + """Test get_entity_ids with a non group state.""" self.assertEqual([], group.get_entity_ids(self.hass, 'switch.AC')) def test_group_being_init_before_first_tracked_state_is_set_to_on(self): - """ Test if the group turns on if no states existed and now a state it is - tracking is being added as ON. """ + """Test if the groups turn on. + + If no states existed and now a state it is tracking is being added + as ON. + """ test_group = group.Group( self.hass, 'test group', ['light.not_there_1']) @@ -201,8 +196,11 @@ class TestComponentsGroup(unittest.TestCase): self.assertEqual(STATE_ON, group_state.state) def test_group_being_init_before_first_tracked_state_is_set_to_off(self): - """ Test if the group turns off if no states existed and now a state it is - tracking is being added as OFF. """ + """Test if the group turns off. + + If no states existed and now a state it is tracking is being added + as OFF. + """ test_group = group.Group( self.hass, 'test group', ['light.not_there_1']) @@ -214,7 +212,7 @@ class TestComponentsGroup(unittest.TestCase): self.assertEqual(STATE_OFF, group_state.state) def test_setup(self): - """ Test setup method. """ + """Test setup method.""" self.hass.states.set('light.Bowl', STATE_ON) self.hass.states.set('light.Ceiling', STATE_OFF) test_group = group.Group( @@ -256,13 +254,14 @@ class TestComponentsGroup(unittest.TestCase): self.assertIsNone(group_state.attributes.get(ATTR_HIDDEN)) def test_groups_get_unique_names(self): - """ Two groups with same name should both have a unique entity id. """ + """Two groups with same name should both have a unique entity id.""" grp1 = group.Group(self.hass, 'Je suis Charlie') grp2 = group.Group(self.hass, 'Je suis Charlie') self.assertNotEqual(grp1.entity_id, grp2.entity_id) def test_expand_entity_ids_expands_nested_groups(self): + """Test if entity ids epands to nested groups.""" group.Group(self.hass, 'light', ['light.test_1', 'light.test_2']) group.Group(self.hass, 'switch', ['switch.test_1', 'switch.test_2']) group.Group(self.hass, 'group_of_groups', ['group.light', @@ -274,6 +273,7 @@ class TestComponentsGroup(unittest.TestCase): ['group.group_of_groups']))) def test_set_assumed_state_based_on_tracked(self): + """Test assumed state.""" self.hass.states.set('light.Bowl', STATE_ON) self.hass.states.set('light.Ceiling', STATE_OFF) test_group = group.Group( diff --git a/tests/components/test_history.py b/tests/components/test_history.py index 3f781b9d30c..8fc76089f50 100644 --- a/tests/components/test_history.py +++ b/tests/components/test_history.py @@ -1,9 +1,4 @@ -""" -tests.components.test_history -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests the history component. -""" +"""The tests the History component.""" # pylint: disable=protected-access,too-many-public-methods from datetime import timedelta import os @@ -19,14 +14,14 @@ from tests.common import ( class TestComponentHistory(unittest.TestCase): - """ Tests homeassistant.components.history module. """ + """Test History component.""" def setUp(self): # pylint: disable=invalid-name - """ Init needed objects. """ + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant(1) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() db_path = self.hass.config.path(recorder.DB_FILE) @@ -34,22 +29,23 @@ class TestComponentHistory(unittest.TestCase): os.remove(db_path) def init_recorder(self): + """Initialize the recorder.""" recorder.setup(self.hass, {}) self.hass.start() self.wait_recording_done() def wait_recording_done(self): - """ Block till recording is done. """ + """Block till recording is done.""" self.hass.pool.block_till_done() recorder._INSTANCE.block_till_done() def test_setup(self): - """ Test setup method of history. """ + """Test setup method of history.""" mock_http_component(self.hass) self.assertTrue(history.setup(self.hass, {})) def test_last_5_states(self): - """ Test retrieving the last 5 states. """ + """Test retrieving the last 5 states.""" self.init_recorder() states = [] @@ -67,7 +63,7 @@ class TestComponentHistory(unittest.TestCase): list(reversed(states)), history.last_5_states(entity_id)) def test_get_states(self): - """ Test getting states at a specific point in time. """ + """Test getting states at a specific point in time.""" self.init_recorder() states = [] @@ -109,6 +105,7 @@ class TestComponentHistory(unittest.TestCase): states[0], history.get_state(future, states[0].entity_id)) def test_state_changes_during_period(self): + """Test state change during period.""" self.init_recorder() entity_id = 'media_player.test' @@ -145,14 +142,12 @@ class TestComponentHistory(unittest.TestCase): self.assertEqual(states, hist[entity_id]) def test_get_significant_states(self): - """test that only significant states are returned with - get_significant_states. + """Test that only significant states are returned. We inject a bunch of state updates from media player, zone and thermostat. We should get back every thermostat change that includes an attribute change, but only the state updates for media player (attribute changes are not significant and not returned). - """ self.init_recorder() mp = 'media_player.test' @@ -186,10 +181,10 @@ class TestComponentHistory(unittest.TestCase): with patch('homeassistant.components.recorder.dt_util.utcnow', return_value=two): - # this state will be skipped only different in time + # This state will be skipped only different in time set_state(mp, 'YouTube', attributes={'media_title': str(sentinel.mt3)}) - # this state will be skipped because domain blacklisted + # This state will be skipped because domain blacklisted set_state(zone, 'zoning') set_state(script_nc, 'off') states[script_c].append( @@ -202,7 +197,7 @@ class TestComponentHistory(unittest.TestCase): states[mp].append( set_state(mp, 'Netflix', attributes={'media_title': str(sentinel.mt4)})) - # attributes changed even though state is the same + # Attributes changed even though state is the same states[therm].append( set_state(therm, 21, attributes={'current_temperature': 20})) diff --git a/tests/components/test_influx.py b/tests/components/test_influx.py index aa160b69ac4..97ae87e6e91 100644 --- a/tests/components/test_influx.py +++ b/tests/components/test_influx.py @@ -1,9 +1,4 @@ -""" -tests.components.test_influxdb -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests influxdb component. -""" +"""The tests for the InfluxDB component.""" import copy import unittest from unittest import mock @@ -15,8 +10,11 @@ from homeassistant.const import STATE_ON, STATE_OFF, EVENT_STATE_CHANGED class TestInfluxDB(unittest.TestCase): + """Test the InfluxDB component.""" + @mock.patch('influxdb.InfluxDBClient') def test_setup_config_full(self, mock_client): + """Test the setup with full configuration.""" config = { 'influxdb': { 'host': 'host', @@ -37,6 +35,7 @@ class TestInfluxDB(unittest.TestCase): @mock.patch('influxdb.InfluxDBClient') def test_setup_config_defaults(self, mock_client): + """Test the setup with default configuration.""" config = { 'influxdb': { 'host': 'host', @@ -52,6 +51,7 @@ class TestInfluxDB(unittest.TestCase): @mock.patch('influxdb.InfluxDBClient') def test_setup_missing_keys(self, mock_client): + """Test the setup with missing keys.""" config = { 'influxdb': { 'host': 'host', @@ -67,6 +67,7 @@ class TestInfluxDB(unittest.TestCase): @mock.patch('influxdb.InfluxDBClient') def test_setup_query_fail(self, mock_client): + """Test the setup for query failures.""" config = { 'influxdb': { 'host': 'host', @@ -80,6 +81,7 @@ class TestInfluxDB(unittest.TestCase): self.assertFalse(influxdb.setup(hass, config)) def _setup(self, mock_influx): + """Setup the client.""" self.mock_client = mock_influx.return_value config = { 'influxdb': { @@ -95,6 +97,7 @@ class TestInfluxDB(unittest.TestCase): @mock.patch('influxdb.InfluxDBClient') def test_event_listener(self, mock_influx): + """Test the event listener.""" self._setup(mock_influx) valid = {'1': 1, @@ -127,6 +130,7 @@ class TestInfluxDB(unittest.TestCase): @mock.patch('influxdb.InfluxDBClient') def test_event_listener_no_units(self, mock_influx): + """Test the event listener for missing units.""" self._setup(mock_influx) for unit in (None, ''): @@ -158,6 +162,7 @@ class TestInfluxDB(unittest.TestCase): @mock.patch('influxdb.InfluxDBClient') def test_event_listener_fail_write(self, mock_influx): + """Test the event listener for write failures.""" self._setup(mock_influx) state = mock.MagicMock(state=1, @@ -173,6 +178,7 @@ class TestInfluxDB(unittest.TestCase): @mock.patch('influxdb.InfluxDBClient') def test_event_listener_blacklist(self, mock_influx): + """Test the event listener against a blacklist.""" self._setup(mock_influx) for entity_id in ('ok', 'blacklisted'): diff --git a/tests/components/test_init.py b/tests/components/test_init.py index 51d84aab731..ff663a95a53 100644 --- a/tests/components/test_init.py +++ b/tests/components/test_init.py @@ -1,9 +1,4 @@ -""" -tests.components.test_init -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests core compoments. -""" +"""The testd for Core components.""" # pylint: disable=protected-access,too-many-public-methods import unittest from unittest.mock import patch @@ -17,10 +12,10 @@ from tests.common import get_test_home_assistant class TestComponentsCore(unittest.TestCase): - """ Tests homeassistant.components module. """ + """Test homeassistant.components module.""" def setUp(self): # pylint: disable=invalid-name - """ Init needed objects. """ + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.assertTrue(comps.setup(self.hass, {})) @@ -28,17 +23,17 @@ class TestComponentsCore(unittest.TestCase): self.hass.states.set('light.Ceiling', STATE_OFF) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_is_on(self): - """ Test is_on method. """ + """Test is_on method.""" self.assertTrue(comps.is_on(self.hass, 'light.Bowl')) self.assertFalse(comps.is_on(self.hass, 'light.Ceiling')) self.assertTrue(comps.is_on(self.hass)) def test_turn_on(self): - """ Test turn_on method. """ + """Test turn_on method.""" runs = [] self.hass.services.register( 'light', SERVICE_TURN_ON, lambda x: runs.append(1)) @@ -50,7 +45,7 @@ class TestComponentsCore(unittest.TestCase): self.assertEqual(1, len(runs)) def test_turn_off(self): - """ Test turn_off method. """ + """Test turn_off method.""" runs = [] self.hass.services.register( 'light', SERVICE_TURN_OFF, lambda x: runs.append(1)) @@ -62,7 +57,7 @@ class TestComponentsCore(unittest.TestCase): self.assertEqual(1, len(runs)) def test_toggle(self): - """ Test toggle method. """ + """Test toggle method.""" runs = [] self.hass.services.register( 'light', SERVICE_TOGGLE, lambda x: runs.append(1)) @@ -75,6 +70,7 @@ class TestComponentsCore(unittest.TestCase): @patch('homeassistant.core.ServiceRegistry.call') def test_turn_on_to_not_block_for_domains_without_service(self, mock_call): + """Test if turn_on is blocking domain with no service.""" self.hass.services.register('light', SERVICE_TURN_ON, lambda x: x) # We can't test if our service call results in services being called diff --git a/tests/components/test_input_boolean.py b/tests/components/test_input_boolean.py index ace91018ccd..3e0bb0e6c48 100644 --- a/tests/components/test_input_boolean.py +++ b/tests/components/test_input_boolean.py @@ -1,9 +1,4 @@ -""" -tests.components.test_input_boolean -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests input_boolean component. -""" +"""The tests for the input_boolean component.""" # pylint: disable=too-many-public-methods,protected-access import unittest @@ -15,13 +10,14 @@ from tests.common import get_test_home_assistant class TestInputBoolean(unittest.TestCase): - """ Test the input boolean module. """ + """Test the input boolean module.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_config(self): @@ -42,7 +38,7 @@ class TestInputBoolean(unittest.TestCase): })) def test_methods(self): - """ Test is_on, turn_on, turn_off methods. """ + """Test is_on, turn_on, turn_off methods.""" self.assertTrue(input_boolean.setup(self.hass, { 'input_boolean': { 'test_1': None, @@ -68,6 +64,7 @@ class TestInputBoolean(unittest.TestCase): input_boolean.is_on(self.hass, entity_id)) def test_config_options(self): + """Test configuration options.""" count_start = len(self.hass.states.entity_ids()) self.assertTrue(input_boolean.setup(self.hass, { diff --git a/tests/components/test_input_select.py b/tests/components/test_input_select.py index f7aa87d2a0d..20d710a5b92 100644 --- a/tests/components/test_input_select.py +++ b/tests/components/test_input_select.py @@ -1,9 +1,4 @@ -""" -tests.components.test_input_select -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests input_select component. -""" +"""The tests for the Input select component.""" # pylint: disable=too-many-public-methods,protected-access import unittest @@ -15,13 +10,14 @@ from tests.common import get_test_home_assistant class TestInputSelect(unittest.TestCase): - """ Test the input select module. """ + """Test the input select component.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_config(self): @@ -56,7 +52,7 @@ class TestInputSelect(unittest.TestCase): })) def test_select_option(self): - """ Test select_option methods. """ + """Test select_option methods.""" self.assertTrue(input_select.setup(self.hass, { 'input_select': { 'test_1': { @@ -85,6 +81,7 @@ class TestInputSelect(unittest.TestCase): self.assertEqual('another option', state.state) def test_config_options(self): + """Test configuration options.""" count_start = len(self.hass.states.entity_ids()) test_2_options = [ diff --git a/tests/components/test_introduction.py b/tests/components/test_introduction.py index f4a53c65566..c1bb1b894bc 100644 --- a/tests/components/test_introduction.py +++ b/tests/components/test_introduction.py @@ -1,9 +1,4 @@ -""" -tests.components.test_introduction -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Test introduction. -""" +"""The tests for the Introduction component.""" import unittest from homeassistant.components import introduction @@ -12,15 +7,16 @@ from tests.common import get_test_home_assistant class TestIntroduction(unittest.TestCase): - """ Test Introduction. """ + """Test Introduction.""" def setUp(self): + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def tearDown(self): - """ Stop down stuff we started. """ + """Stop down everything that was started.""" self.hass.stop() def test_setup(self): - """ Test Introduction setup """ + """Test introduction setup.""" self.assertTrue(introduction.setup(self.hass, {})) diff --git a/tests/components/test_logbook.py b/tests/components/test_logbook.py index f83ecd548f0..d27865f4402 100644 --- a/tests/components/test_logbook.py +++ b/tests/components/test_logbook.py @@ -1,9 +1,4 @@ -""" -tests.components.test_logbook -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests the logbook component. -""" +"""The tests for the logbook component.""" # pylint: disable=protected-access,too-many-public-methods import unittest from datetime import timedelta @@ -18,18 +13,20 @@ from tests.common import mock_http_component, get_test_home_assistant class TestComponentHistory(unittest.TestCase): - """ Tests homeassistant.components.history module. """ + """Test the History component.""" def setUp(self): - """ Test setup method. """ + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() mock_http_component(self.hass) self.assertTrue(logbook.setup(self.hass, {})) def tearDown(self): + """Stop everything that was started.""" self.hass.stop() def test_service_call_create_logbook_entry(self): + """Test if service call create log book entry.""" calls = [] def event_listener(event): @@ -55,6 +52,7 @@ class TestComponentHistory(unittest.TestCase): logbook.ATTR_ENTITY_ID)) def test_service_call_create_log_book_entry_no_message(self): + """Test if service call create log book entry without message.""" calls = [] def event_listener(event): @@ -67,7 +65,7 @@ class TestComponentHistory(unittest.TestCase): self.assertEqual(0, len(calls)) def test_humanify_filter_sensor(self): - """ Test humanify filter too frequent sensor values. """ + """Test humanify filter too frequent sensor values.""" entity_id = 'sensor.bla' pointA = dt_util.strip_microseconds(dt_util.utcnow().replace(minute=2)) @@ -88,6 +86,7 @@ class TestComponentHistory(unittest.TestCase): entries[1], pointC, 'bla', domain='sensor', entity_id=entity_id) def test_entry_to_dict(self): + """Test conversion of entry to dict.""" entry = logbook.Entry( dt_util.utcnow(), 'Alarm', 'is triggered', 'switch', 'test_switch' ) @@ -98,8 +97,10 @@ class TestComponentHistory(unittest.TestCase): self.assertEqual('test_switch', data.get(logbook.ATTR_ENTITY_ID)) def test_home_assistant_start_stop_grouped(self): - """ Tests if home assistant start and stop events are grouped if - occuring in the same minute. """ + """Test if HA start and stop events are grouped. + + Events that are occuring in the same minute. + """ entries = list(logbook.humanify(( ha.Event(EVENT_HOMEASSISTANT_STOP), ha.Event(EVENT_HOMEASSISTANT_START), @@ -111,7 +112,7 @@ class TestComponentHistory(unittest.TestCase): domain=ha.DOMAIN) def test_process_custom_logbook_entries(self): - """ Tests if custom log book entries get added as an entry. """ + """Test if custom log book entries get added as an entry.""" name = 'Nice name' message = 'has a custom entry' entity_id = 'sun.sun' @@ -131,7 +132,7 @@ class TestComponentHistory(unittest.TestCase): def assert_entry(self, entry, when=None, name=None, message=None, domain=None, entity_id=None): - """ Asserts an entry is what is expected """ + """Assert an entry is what is expected.""" if when: self.assertEqual(when, entry.when) @@ -148,8 +149,7 @@ class TestComponentHistory(unittest.TestCase): self.assertEqual(entity_id, entry.entity_id) def create_state_changed_event(self, event_time_fired, entity_id, state): - """ Create state changed event. """ - + """Create state changed event.""" # Logbook only cares about state change events that # contain an old state but will not actually act on it. state = ha.State(entity_id, state).as_dict() diff --git a/tests/components/test_logger.py b/tests/components/test_logger.py index 2be5ca5c740..9973106fd14 100644 --- a/tests/components/test_logger.py +++ b/tests/components/test_logger.py @@ -1,9 +1,4 @@ -""" -tests.components.test_logger -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests logger component. -""" +"""The tests for the Logger component.""" from collections import namedtuple import logging import unittest @@ -14,19 +9,19 @@ RECORD = namedtuple('record', ('name', 'levelno')) class TestUpdater(unittest.TestCase): - """ Test logger component. """ + """Test logger component.""" def setUp(self): - """ Create default config """ + """Setup things to be run when tests are started.""" self.log_config = {'logger': {'default': 'warning', 'logs': {'test': 'info'}}} def tearDown(self): - """ Reset logs """ + """Stop everything that was started.""" del logging.root.handlers[-1] def test_logger_setup(self): - """ Uses logger to create a logging filter """ + """Use logger to create a logging filter.""" logger.setup(None, self.log_config) self.assertTrue(len(logging.root.handlers) > 0) @@ -39,23 +34,23 @@ class TestUpdater(unittest.TestCase): self.assertEqual(log_filter['logs']['test'], logging.INFO) def test_logger_test_filters(self): - """ Tests resulting filter operation """ + """Test resulting filter operation.""" logger.setup(None, self.log_config) log_filter = logging.root.handlers[-1].filters[0] - # blocked default record + # Blocked default record record = RECORD('asdf', logging.DEBUG) self.assertFalse(log_filter.filter(record)) - # allowed default record + # Allowed default record record = RECORD('asdf', logging.WARNING) self.assertTrue(log_filter.filter(record)) - # blocked named record + # Blocked named record record = RECORD('test', logging.DEBUG) self.assertFalse(log_filter.filter(record)) - # allowed named record + # Allowed named record record = RECORD('test', logging.INFO) self.assertTrue(log_filter.filter(record)) diff --git a/tests/components/test_mqtt.py b/tests/components/test_mqtt.py index 9ca51c687bc..4e5c59f73ef 100644 --- a/tests/components/test_mqtt.py +++ b/tests/components/test_mqtt.py @@ -1,9 +1,4 @@ -""" -tests.components.test_mqtt -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests MQTT component. -""" +"""The tests for the MQTT component.""" from collections import namedtuple import unittest from unittest import mock @@ -19,26 +14,30 @@ from tests.common import ( class TestMQTT(unittest.TestCase): - """ Test the MQTT module. """ + """Test the MQTT component.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant(1) mock_mqtt_component(self.hass) self.calls = [] def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def record_calls(self, *args): + """Helper for recording calls.""" self.calls.append(args) def test_client_starts_on_home_assistant_start(self): + """"Test if client start on HA launch.""" self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.pool.block_till_done() self.assertTrue(mqtt.MQTT_CLIENT.start.called) def test_client_stops_on_home_assistant_start(self): + """Test if client stops on HA launch.""" self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.pool.block_till_done() self.hass.bus.fire(EVENT_HOMEASSISTANT_STOP) @@ -46,9 +45,11 @@ class TestMQTT(unittest.TestCase): self.assertTrue(mqtt.MQTT_CLIENT.stop.called) def test_setup_fails_if_no_broker_config(self): + """Test for setup failure if broker configuration is missing.""" self.assertFalse(mqtt.setup(self.hass, {mqtt.DOMAIN: {}})) def test_setup_fails_if_no_connect_broker(self): + """Test for setup failure if connection to broker is missing.""" with mock.patch('homeassistant.components.mqtt.MQTT', side_effect=socket.error()): self.assertFalse(mqtt.setup(self.hass, {mqtt.DOMAIN: { @@ -56,6 +57,7 @@ class TestMQTT(unittest.TestCase): }})) def test_publish_calls_service(self): + """Test the publishing of call to services.""" self.hass.bus.listen_once(EVENT_CALL_SERVICE, self.record_calls) mqtt.publish(self.hass, 'test-topic', 'test-payload') @@ -71,6 +73,7 @@ class TestMQTT(unittest.TestCase): self.calls[0][0].data['service_data'][mqtt.ATTR_PAYLOAD]) def test_service_call_without_topic_does_not_publish(self): + """Test the service call if topic is missing.""" self.hass.bus.fire(EVENT_CALL_SERVICE, { ATTR_DOMAIN: mqtt.DOMAIN, ATTR_SERVICE: mqtt.SERVICE_PUBLISH @@ -79,7 +82,8 @@ class TestMQTT(unittest.TestCase): self.assertTrue(not mqtt.MQTT_CLIENT.publish.called) def test_service_call_with_template_payload_renders_template(self): - """ + """Test the service call with rendered template. + If 'payload_template' is provided and 'payload' is not, then render it. """ mqtt.publish_template(self.hass, "test/topic", "{{ 1+1 }}") @@ -88,7 +92,8 @@ class TestMQTT(unittest.TestCase): self.assertEqual(mqtt.MQTT_CLIENT.publish.call_args[0][1], "2") def test_service_call_with_payload_doesnt_render_template(self): - """ + """Test the service call with unrendered template. + If a 'payload' is provided then use that instead of 'payload_template'. """ payload = "not a template" @@ -104,7 +109,8 @@ class TestMQTT(unittest.TestCase): self.assertEqual(mqtt.MQTT_CLIENT.publish.call_args[0][1], payload) def test_service_call_without_payload_or_payload_template(self): - """ + """Test the service call without payload or payload template. + If neither 'payload' or 'payload_template' is provided then fail. """ # Call the service directly because the helper functions require you to @@ -115,6 +121,7 @@ class TestMQTT(unittest.TestCase): self.assertFalse(mqtt.MQTT_CLIENT.publish.called) def test_subscribe_topic(self): + """Test the subscription of a topic.""" mqtt.subscribe(self.hass, 'test-topic', self.record_calls) fire_mqtt_message(self.hass, 'test-topic', 'test-payload') @@ -125,6 +132,7 @@ class TestMQTT(unittest.TestCase): self.assertEqual('test-payload', self.calls[0][1]) def test_subscribe_topic_not_match(self): + """Test if subscribed topic is not a match.""" mqtt.subscribe(self.hass, 'test-topic', self.record_calls) fire_mqtt_message(self.hass, 'another-test-topic', 'test-payload') @@ -133,6 +141,7 @@ class TestMQTT(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_subscribe_topic_level_wildcard(self): + """Test the subscription of wildcard topics.""" mqtt.subscribe(self.hass, 'test-topic/+/on', self.record_calls) fire_mqtt_message(self.hass, 'test-topic/bier/on', 'test-payload') @@ -143,6 +152,7 @@ class TestMQTT(unittest.TestCase): self.assertEqual('test-payload', self.calls[0][1]) def test_subscribe_topic_level_wildcard_no_subtree_match(self): + """Test the subscription of wildcard topics.""" mqtt.subscribe(self.hass, 'test-topic/+/on', self.record_calls) fire_mqtt_message(self.hass, 'test-topic/bier', 'test-payload') @@ -151,6 +161,7 @@ class TestMQTT(unittest.TestCase): self.assertEqual(0, len(self.calls)) def test_subscribe_topic_subtree_wildcard_subtree_topic(self): + """Test the subscription of wildcard topics.""" mqtt.subscribe(self.hass, 'test-topic/#', self.record_calls) fire_mqtt_message(self.hass, 'test-topic/bier/on', 'test-payload') @@ -161,6 +172,7 @@ class TestMQTT(unittest.TestCase): self.assertEqual('test-payload', self.calls[0][1]) def test_subscribe_topic_subtree_wildcard_root_topic(self): + """Test the subscription of wildcard topics.""" mqtt.subscribe(self.hass, 'test-topic/#', self.record_calls) fire_mqtt_message(self.hass, 'test-topic', 'test-payload') @@ -171,6 +183,7 @@ class TestMQTT(unittest.TestCase): self.assertEqual('test-payload', self.calls[0][1]) def test_subscribe_topic_subtree_wildcard_no_match(self): + """Test the subscription of wildcard topics.""" mqtt.subscribe(self.hass, 'test-topic/#', self.record_calls) fire_mqtt_message(self.hass, 'another-test-topic', 'test-payload') @@ -180,9 +193,10 @@ class TestMQTT(unittest.TestCase): class TestMQTTCallbacks(unittest.TestCase): - """ Test the MQTT callbacks. """ + """Test the MQTT callbacks.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant(1) # mock_mqtt_component(self.hass) @@ -195,13 +209,15 @@ class TestMQTTCallbacks(unittest.TestCase): self.hass.config.components.append(mqtt.DOMAIN) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_receiving_mqtt_message_fires_hass_event(self): + """Test if receiving triggers an event.""" calls = [] def record(event): + """Helper to record calls.""" calls.append(event) self.hass.bus.listen_once(mqtt.EVENT_MQTT_MESSAGE_RECEIVED, record) @@ -219,6 +235,7 @@ class TestMQTTCallbacks(unittest.TestCase): self.assertEqual(message.qos, last_event.data['qos']) def test_mqtt_failed_connection_results_in_disconnect(self): + """Test if connection failure leads to disconnect.""" for result_code in range(1, 6): mqtt.MQTT_CLIENT._mqttc = mock.MagicMock() mqtt.MQTT_CLIENT._mqtt_on_connect(None, {'topics': {}}, 0, @@ -226,6 +243,7 @@ class TestMQTTCallbacks(unittest.TestCase): self.assertTrue(mqtt.MQTT_CLIENT._mqttc.disconnect.called) def test_mqtt_subscribes_topics_on_connect(self): + """Test subscription to topic on connect.""" from collections import OrderedDict prev_topics = OrderedDict() prev_topics['topic/test'] = 1, @@ -251,11 +269,13 @@ class TestMQTTCallbacks(unittest.TestCase): }, mqtt.MQTT_CLIENT.progress) def test_mqtt_disconnect_tries_no_reconnect_on_stop(self): + """Test the disconnect tries.""" mqtt.MQTT_CLIENT._mqtt_on_disconnect(None, None, 0) self.assertFalse(mqtt.MQTT_CLIENT._mqttc.reconnect.called) @mock.patch('homeassistant.components.mqtt.time.sleep') def test_mqtt_disconnect_tries_reconnect(self, mock_sleep): + """Test the re-connect tries.""" mqtt.MQTT_CLIENT.topics = { 'test/topic': 1, 'test/progress': None diff --git a/tests/components/test_mqtt_eventstream.py b/tests/components/test_mqtt_eventstream.py index 269b672055e..b4c36132444 100644 --- a/tests/components/test_mqtt_eventstream.py +++ b/tests/components/test_mqtt_eventstream.py @@ -1,9 +1,4 @@ -""" -tests.components.test_mqtt_eventstream -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests MQTT eventstream component. -""" +"""The tests for the MQTT eventstream component.""" import json import unittest from unittest.mock import ANY, patch @@ -24,19 +19,20 @@ from tests.common import ( class TestMqttEventStream(unittest.TestCase): - """ Test the MQTT eventstream module. """ + """Test the MQTT eventstream module.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" super(TestMqttEventStream, self).setUp() self.hass = get_test_home_assistant() self.mock_mqtt = mock_mqtt_component(self.hass) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def add_eventstream(self, sub_topic=None, pub_topic=None): - """ Add a mqtt_eventstream component to the hass. """ + """Add a mqtt_eventstream component.""" config = {} if sub_topic: config['subscribe_topic'] = sub_topic @@ -45,9 +41,11 @@ class TestMqttEventStream(unittest.TestCase): return eventstream.setup(self.hass, {eventstream.DOMAIN: config}) def test_setup_succeeds(self): + """"Test the success of the setup.""" self.assertTrue(self.add_eventstream()) def test_setup_with_pub(self): + """"Test the setup with subscription.""" # Should start off with no listeners for all events self.assertEqual(self.hass.bus.listeners.get('*'), None) @@ -59,6 +57,7 @@ class TestMqttEventStream(unittest.TestCase): @patch('homeassistant.components.mqtt.subscribe') def test_subscribe(self, mock_sub): + """"Test the subscription.""" sub_topic = 'foo' self.assertTrue(self.add_eventstream(sub_topic=sub_topic)) self.hass.pool.block_till_done() @@ -69,6 +68,7 @@ class TestMqttEventStream(unittest.TestCase): @patch('homeassistant.components.mqtt.publish') @patch('homeassistant.core.dt_util.datetime_to_str') def test_state_changed_event_sends_message(self, mock_datetime, mock_pub): + """"Test the sending of a new message if event changed.""" now = '00:19:19 11-01-2016' e_id = 'fake.entity' pub_topic = 'bar' @@ -110,6 +110,7 @@ class TestMqttEventStream(unittest.TestCase): @patch('homeassistant.components.mqtt.publish') def test_time_event_does_not_send_message(self, mock_pub): + """"Test the sending of a new message if time event.""" self.assertTrue(self.add_eventstream(pub_topic='bar')) self.hass.pool.block_till_done() @@ -121,6 +122,7 @@ class TestMqttEventStream(unittest.TestCase): self.assertFalse(mock_pub.called) def test_receiving_remote_event_fires_hass_event(self): + """"Test the receiving of the remotely fired event.""" sub_topic = 'foo' self.assertTrue(self.add_eventstream(sub_topic=sub_topic)) self.hass.pool.block_till_done() diff --git a/tests/components/test_proximity.py b/tests/components/test_proximity.py index 7c7ae0b954f..0bfa403ad44 100644 --- a/tests/components/test_proximity.py +++ b/tests/components/test_proximity.py @@ -1,18 +1,14 @@ -""" -tests.components.test_proximity -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests proximity component. -""" +"""The tests for the Proximity component.""" from homeassistant.components import proximity from tests.common import get_test_home_assistant class TestProximity: - """ Test the Proximity component. """ + """Test the Proximity component.""" def setup_method(self, method): + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.states.set( 'zone.home', 'zoning', @@ -24,10 +20,11 @@ class TestProximity: }) def teardown_method(self, method): - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_proximity(self): + """Test the proximity.""" assert proximity.setup(self.hass, { 'proximity': { 'zone': 'home', @@ -53,6 +50,7 @@ class TestProximity: assert state.state == '0' def test_no_devices_in_config(self): + """Test for missing devices in configuration.""" assert not proximity.setup(self.hass, { 'proximity': { 'zone': 'home', @@ -64,6 +62,7 @@ class TestProximity: }) def test_no_tolerance_in_config(self): + """Test for missing tolerance in configuration .""" assert proximity.setup(self.hass, { 'proximity': { 'zone': 'home', @@ -78,6 +77,7 @@ class TestProximity: }) def test_no_ignored_zones_in_config(self): + """Test for ignored zones in configuration.""" assert proximity.setup(self.hass, { 'proximity': { 'zone': 'home', @@ -90,6 +90,7 @@ class TestProximity: }) def test_no_zone_in_config(self): + """Test for missing zone in configuration.""" assert proximity.setup(self.hass, { 'proximity': { 'ignored_zones': { @@ -104,6 +105,7 @@ class TestProximity: }) def test_device_tracker_test1_in_zone(self): + """Test for tracker in zone.""" assert proximity.setup(self.hass, { 'proximity': { 'zone': 'home', @@ -131,6 +133,7 @@ class TestProximity: assert state.attributes.get('dir_of_travel') == 'arrived' def test_device_trackers_in_zone(self): + """Test for trackers in zone.""" assert proximity.setup(self.hass, { 'proximity': { 'zone': 'home', @@ -168,6 +171,7 @@ class TestProximity: assert state.attributes.get('dir_of_travel') == 'arrived' def test_device_tracker_test1_away(self): + """Test for tracker state away.""" assert proximity.setup(self.hass, { 'proximity': { 'zone': 'home', @@ -194,6 +198,7 @@ class TestProximity: assert state.attributes.get('dir_of_travel') == 'unknown' def test_device_tracker_test1_awayfurther(self): + """Test for tracker state away further.""" assert proximity.setup(self.hass, { 'proximity': { 'zone': 'home', @@ -230,6 +235,7 @@ class TestProximity: assert state.attributes.get('dir_of_travel') == 'away_from' def test_device_tracker_test1_awaycloser(self): + """Test for tracker state away closer.""" assert proximity.setup(self.hass, { 'proximity': { 'zone': 'home', @@ -266,6 +272,7 @@ class TestProximity: assert state.attributes.get('dir_of_travel') == 'towards' def test_all_device_trackers_in_ignored_zone(self): + """Test for tracker in ignored zone.""" assert proximity.setup(self.hass, { 'proximity': { 'zone': 'home', @@ -290,6 +297,7 @@ class TestProximity: assert state.attributes.get('dir_of_travel') == 'not set' def test_device_tracker_test1_no_coordinates(self): + """Test for tracker with no coordinates.""" assert proximity.setup(self.hass, { 'proximity': { 'zone': 'home', @@ -314,6 +322,7 @@ class TestProximity: assert state.attributes.get('dir_of_travel') == 'not set' def test_device_tracker_test1_awayfurther_than_test2_first_test1(self): + """Test for tracker ordering.""" self.hass.states.set( 'device_tracker.test1', 'not_home', { @@ -363,6 +372,7 @@ class TestProximity: assert state.attributes.get('dir_of_travel') == 'unknown' def test_device_tracker_test1_awayfurther_than_test2_first_test2(self): + """Test for tracker ordering.""" self.hass.states.set( 'device_tracker.test1', 'not_home', { @@ -412,6 +422,7 @@ class TestProximity: assert state.attributes.get('dir_of_travel') == 'unknown' def test_device_tracker_test1_awayfurther_test2_in_ignored_zone(self): + """Test for tracker states.""" self.hass.states.set( 'device_tracker.test1', 'not_home', { @@ -450,6 +461,7 @@ class TestProximity: assert state.attributes.get('dir_of_travel') == 'unknown' def test_device_tracker_test1_awayfurther_test2_first(self): + """Test for tracker state.""" self.hass.states.set( 'device_tracker.test1', 'not_home', { @@ -519,6 +531,7 @@ class TestProximity: assert state.attributes.get('dir_of_travel') == 'unknown' def test_device_tracker_test1_awayfurther_a_bit(self): + """Test for tracker states.""" assert proximity.setup(self.hass, { 'proximity': { 'zone': 'home', @@ -556,6 +569,7 @@ class TestProximity: assert state.attributes.get('dir_of_travel') == 'stationary' def test_device_tracker_test1_nearest_after_test2_in_ignored_zone(self): + """Test for tracker states.""" self.hass.states.set( 'device_tracker.test1', 'not_home', { diff --git a/tests/components/test_recorder.py b/tests/components/test_recorder.py index 0d42da865a0..aef21159cef 100644 --- a/tests/components/test_recorder.py +++ b/tests/components/test_recorder.py @@ -1,9 +1,4 @@ -""" -tests.components.test_recorder -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests Recorder component. -""" +"""The tests for the Recorder component.""" # pylint: disable=too-many-public-methods,protected-access import unittest import os @@ -15,22 +10,23 @@ from tests.common import get_test_home_assistant class TestRecorder(unittest.TestCase): - """ Test the chromecast module. """ + """Test the chromecast module.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() recorder.setup(self.hass, {}) self.hass.start() recorder._INSTANCE.block_till_done() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() recorder._INSTANCE.block_till_done() os.remove(self.hass.config.path(recorder.DB_FILE)) def test_saving_state(self): - """ Tests saving and restoring a state. """ + """Test saving and restoring a state.""" entity_id = 'test.recorder' state = 'restoring_from_db' attributes = {'test_attr': 5, 'test_attr_10': 'nice'} @@ -46,14 +42,14 @@ class TestRecorder(unittest.TestCase): self.assertEqual(self.hass.states.get(entity_id), states[0]) def test_saving_event(self): - """ Tests saving and restoring an event. """ + """Test saving and restoring an event.""" event_type = 'EVENT_TEST' event_data = {'test_attr': 5, 'test_attr_10': 'nice'} events = [] def event_listener(event): - """ Records events from eventbus. """ + """Record events from eventbus.""" if event.event_type == event_type: events.append(event) diff --git a/tests/components/test_rfxtrx.py b/tests/components/test_rfxtrx.py index c0b0746a44d..7c2ef788a44 100644 --- a/tests/components/test_rfxtrx.py +++ b/tests/components/test_rfxtrx.py @@ -1,9 +1,4 @@ -""" -tests.components.test_rfxtrx -~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests Rfxtrx component. -""" +"""Th tests for the Rfxtrx component.""" # pylint: disable=too-many-public-methods,protected-access import unittest import time @@ -18,21 +13,21 @@ from tests.common import get_test_home_assistant @pytest.mark.skipif(True, reason='Does not clean up properly, takes 100% CPU') class TestRFXTRX(unittest.TestCase): - """ Test the sun module. """ + """Test the Rfxtrx component.""" def setUp(self): - """ setup hass """ + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant(0) def tearDown(self): - """ Stop down stuff we started. """ + """Stop everything that was started.""" rfxtrx.RECEIVED_EVT_SUBSCRIBERS = [] rfxtrx.RFX_DEVICES = {} rfxtrx.RFXOBJECT = None self.hass.stop() def test_default_config(self): - """ Test config """ + """Test configuration.""" self.assertTrue(rfxtrx.setup(self.hass, { 'rfxtrx': { 'device': '/dev/serial/by-id/usb' + @@ -44,7 +39,7 @@ class TestRFXTRX(unittest.TestCase): devices = [] def add_dev_callback(devs): - """ callback to add device """ + """Add a callback to add devices.""" for dev in devs: devices.append(dev) @@ -57,7 +52,7 @@ class TestRFXTRX(unittest.TestCase): self.assertEquals(len(devices), 2) def test_config_failing(self): - """ Test config """ + """Test configuration.""" self.assertFalse(rfxtrx.setup(self.hass, { 'rfxtrx': {} })) diff --git a/tests/components/test_scene.py b/tests/components/test_scene.py index 6e2e61031fa..4a83a29453d 100644 --- a/tests/components/test_scene.py +++ b/tests/components/test_scene.py @@ -1,9 +1,4 @@ -""" -tests.components.test_scene -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests scene component. -""" +"""The tests for the Scene component.""" import unittest from homeassistant import loader @@ -13,19 +8,20 @@ from tests.common import get_test_home_assistant class TestScene(unittest.TestCase): - """ Test scene component. """ + """Test the scene component.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_config_yaml_alias_anchor(self): - """ - Tests the usage of YAML aliases and anchors. The following test scene - configuration is equivalent to: + """Test the usage of YAML aliases and anchors. + + The following test scene configuration is equivalent to: scene: - name: test @@ -77,6 +73,7 @@ class TestScene(unittest.TestCase): light_2.last_call('turn_on')[1].get('brightness')) def test_activate_scene(self): + """Test active scene.""" test_light = loader.get_component('light.test') test_light.init() diff --git a/tests/components/test_script.py b/tests/components/test_script.py index 3d957785d8b..450c75740b5 100644 --- a/tests/components/test_script.py +++ b/tests/components/test_script.py @@ -1,9 +1,4 @@ -""" -tests.components.test_script -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests script component. -""" +"""The tests for the Script component.""" # pylint: disable=too-many-public-methods,protected-access from datetime import timedelta import unittest @@ -18,16 +13,18 @@ ENTITY_ID = 'script.test' class TestScript(unittest.TestCase): - """ Test the switch module. """ + """Test the Script component.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop down everything that was started.""" self.hass.stop() def test_setup_with_missing_sequence(self): + """Test setup with missing sequence.""" self.assertTrue(script.setup(self.hass, { 'script': { 'test': {} @@ -37,6 +34,7 @@ class TestScript(unittest.TestCase): self.assertEqual(0, len(self.hass.states.entity_ids('script'))) def test_setup_with_invalid_object_id(self): + """Test setup with invalid objects.""" self.assertTrue(script.setup(self.hass, { 'script': { 'test hello world': { @@ -48,6 +46,7 @@ class TestScript(unittest.TestCase): self.assertEqual(0, len(self.hass.states.entity_ids('script'))) def test_setup_with_dict_as_sequence(self): + """Test setup with dict as sequence.""" self.assertTrue(script.setup(self.hass, { 'script': { 'test': { @@ -61,10 +60,12 @@ class TestScript(unittest.TestCase): self.assertEqual(0, len(self.hass.states.entity_ids('script'))) def test_firing_event(self): + """Test the firing of events.""" event = 'test_event' calls = [] def record_event(event): + """Add recorded event to set.""" calls.append(event) self.hass.bus.listen(event, record_event) @@ -92,9 +93,11 @@ class TestScript(unittest.TestCase): self.hass.states.get(ENTITY_ID).attributes.get('can_cancel')) def test_calling_service_old(self): + """Test the calling of an old service.""" calls = [] def record_call(service): + """Add recorded event to set.""" calls.append(service) self.hass.services.register('test', 'script', record_call) @@ -119,9 +122,11 @@ class TestScript(unittest.TestCase): self.assertEqual('world', calls[0].data.get('hello')) def test_calling_service(self): + """Test the calling of a service.""" calls = [] def record_call(service): + """Add recorded event to set.""" calls.append(service) self.hass.services.register('test', 'script', record_call) @@ -146,10 +151,12 @@ class TestScript(unittest.TestCase): self.assertEqual('world', calls[0].data.get('hello')) def test_delay(self): + """Test the delay.""" event = 'test_event' calls = [] def record_event(event): + """Add recorded event to set.""" calls.append(event) self.hass.bus.listen(event, record_event) @@ -191,10 +198,12 @@ class TestScript(unittest.TestCase): self.assertEqual(2, len(calls)) def test_cancel_while_delay(self): + """Test the cancelling while the delay is present.""" event = 'test_event' calls = [] def record_event(event): + """Add recorded event to set.""" calls.append(event) self.hass.bus.listen(event, record_event) @@ -233,14 +242,12 @@ class TestScript(unittest.TestCase): self.assertEqual(0, len(calls)) def test_turn_on_service(self): - """ - Verifies that the turn_on service for a script only turns on scripts - that are not currently running. - """ + """Verify that the turn_on service.""" event = 'test_event' calls = [] def record_event(event): + """Add recorded event to set.""" calls.append(event) self.hass.bus.listen(event, record_event) @@ -264,16 +271,18 @@ class TestScript(unittest.TestCase): self.assertTrue(script.is_on(self.hass, ENTITY_ID)) self.assertEqual(0, len(calls)) - # calling turn_on a second time should not advance the script + # Calling turn_on a second time should not advance the script script.turn_on(self.hass, ENTITY_ID) self.hass.pool.block_till_done() self.assertEqual(0, len(calls)) def test_toggle_service(self): + """Test the toggling of a service.""" event = 'test_event' calls = [] def record_event(event): + """Add recorded event to set.""" calls.append(event) self.hass.bus.listen(event, record_event) diff --git a/tests/components/test_shell_command.py b/tests/components/test_shell_command.py index cf0c09bb052..f899411356d 100644 --- a/tests/components/test_shell_command.py +++ b/tests/components/test_shell_command.py @@ -1,9 +1,4 @@ -""" -tests.components.test_shell_command -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests Shell command component. -""" +"""The tests for the Shell command component.""" import os import tempfile import unittest @@ -16,17 +11,18 @@ from tests.common import get_test_home_assistant class TestShellCommand(unittest.TestCase): - """ Test the demo module. """ + """Test the Shell command component.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_executing_service(self): - """ Test if able to call a configured service. """ + """Test if able to call a configured service.""" with tempfile.TemporaryDirectory() as tempdirname: path = os.path.join(tempdirname, 'called.txt') self.assertTrue(shell_command.setup(self.hass, { @@ -41,13 +37,13 @@ class TestShellCommand(unittest.TestCase): self.assertTrue(os.path.isfile(path)) def test_config_not_dict(self): - """ Test if config is not a dict. """ + """Test if config is not a dict.""" self.assertFalse(shell_command.setup(self.hass, { 'shell_command': ['some', 'weird', 'list'] })) def test_config_not_valid_service_names(self): - """ Test if config contains invalid service names. """ + """Test if config contains invalid service names.""" self.assertFalse(shell_command.setup(self.hass, { 'shell_command': { 'this is invalid because space': 'touch bla.txt' @@ -57,6 +53,7 @@ class TestShellCommand(unittest.TestCase): side_effect=SubprocessError) @patch('homeassistant.components.shell_command._LOGGER.error') def test_subprocess_raising_error(self, mock_call, mock_error): + """Test subprocess.""" with tempfile.TemporaryDirectory() as tempdirname: path = os.path.join(tempdirname, 'called.txt') self.assertTrue(shell_command.setup(self.hass, { diff --git a/tests/components/test_splunk.py b/tests/components/test_splunk.py index 811878d537b..e4e9cf96ee0 100644 --- a/tests/components/test_splunk.py +++ b/tests/components/test_splunk.py @@ -1,9 +1,4 @@ -""" -tests.components.test_splunk -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests splunk component. -""" +"""The tests for the Splunk component.""" import unittest from unittest import mock @@ -12,7 +7,10 @@ from homeassistant.const import STATE_ON, STATE_OFF, EVENT_STATE_CHANGED class TestSplunk(unittest.TestCase): + """Test the Splunk component.""" + def test_setup_config_full(self): + """Test setup with all data.""" config = { 'splunk': { 'host': 'host', @@ -28,6 +26,7 @@ class TestSplunk(unittest.TestCase): hass.bus.listen.call_args_list[0][0][0]) def test_setup_config_defaults(self): + """Test setup with defaults.""" config = { 'splunk': { 'host': 'host', @@ -41,6 +40,7 @@ class TestSplunk(unittest.TestCase): hass.bus.listen.call_args_list[0][0][0]) def _setup(self, mock_requests): + """Test the setup.""" self.mock_post = mock_requests.post self.mock_request_exception = Exception mock_requests.exceptions.RequestException = self.mock_request_exception @@ -57,6 +57,7 @@ class TestSplunk(unittest.TestCase): @mock.patch.object(splunk, 'requests') @mock.patch('json.dumps') def test_event_listener(self, mock_dump, mock_requests): + """Test event listener.""" mock_dump.side_effect = lambda x: x self._setup(mock_requests) diff --git a/tests/components/test_statsd.py b/tests/components/test_statsd.py index 5057ac7bc19..7b0ca2e2f19 100644 --- a/tests/components/test_statsd.py +++ b/tests/components/test_statsd.py @@ -1,9 +1,4 @@ -""" -tests.components.test_statsd -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests StatsD feeder. -""" +"""The tests for the StatsD feeder.""" import unittest from unittest import mock @@ -13,9 +8,12 @@ from homeassistant.const import STATE_ON, STATE_OFF, EVENT_STATE_CHANGED class TestStatsd(unittest.TestCase): + """Test the StatsD component.""" + @mock.patch('statsd.Connection') @mock.patch('statsd.Gauge') def test_statsd_setup_full(self, mock_gauge, mock_connection): + """Test setup with all data.""" config = { 'statsd': { 'host': 'host', @@ -38,6 +36,7 @@ class TestStatsd(unittest.TestCase): @mock.patch('statsd.Connection') @mock.patch('statsd.Gauge') def test_statsd_setup_defaults(self, mock_gauge, mock_connection): + """Test setup with defaults.""" config = { 'statsd': { 'host': 'host', @@ -57,6 +56,7 @@ class TestStatsd(unittest.TestCase): @mock.patch('statsd.Connection') @mock.patch('statsd.Gauge') def test_event_listener(self, mock_gauge, mock_connection): + """Test event listener.""" config = { 'statsd': { 'host': 'host', diff --git a/tests/components/test_sun.py b/tests/components/test_sun.py index 3a1b6340ba0..fd3664ceb96 100644 --- a/tests/components/test_sun.py +++ b/tests/components/test_sun.py @@ -1,9 +1,4 @@ -""" -tests.components.test_sun -~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests Sun component. -""" +"""The tests for the Sun component.""" # pylint: disable=too-many-public-methods,protected-access import unittest from datetime import timedelta @@ -18,24 +13,25 @@ from tests.common import get_test_home_assistant class TestSun(unittest.TestCase): - """ Test the sun module. """ + """Test the sun module.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_is_on(self): - """ Test is_on method. """ + """Test is_on method.""" self.hass.states.set(sun.ENTITY_ID, sun.STATE_ABOVE_HORIZON) self.assertTrue(sun.is_on(self.hass)) self.hass.states.set(sun.ENTITY_ID, sun.STATE_BELOW_HORIZON) self.assertFalse(sun.is_on(self.hass)) def test_setting_rising(self): - """ Test retrieving sun setting and rising. """ + """Test retrieving sun setting and rising.""" latitude = 32.87336 longitude = 117.22743 @@ -76,7 +72,7 @@ class TestSun(unittest.TestCase): self.assertIsNone(sun.next_setting(self.hass, 'non.existing')) def test_state_change(self): - """ Test if the state changes at next setting/rising. """ + """Test if the state changes at next setting/rising.""" self.hass.config.latitude = '32.87336' self.hass.config.longitude = '117.22743' sun.setup(self.hass, {sun.DOMAIN: {sun.CONF_ELEVATION: 0}}) diff --git a/tests/components/test_updater.py b/tests/components/test_updater.py index 440974d4457..a6adef563c4 100644 --- a/tests/components/test_updater.py +++ b/tests/components/test_updater.py @@ -1,9 +1,4 @@ -""" -tests.components.test_updater -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests updater component. -""" +"""The tests for the Updater component.""" import unittest from unittest.mock import patch @@ -18,17 +13,19 @@ NEW_VERSION = '10000.0' class TestUpdater(unittest.TestCase): - """ Test the demo lock. """ + """Test the Updater component.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() @patch('homeassistant.components.updater.get_newest_version') def test_new_version_shows_entity_on_start(self, mock_get_newest_version): + """Test if new entity is created if new version is available.""" mock_get_newest_version.return_value = NEW_VERSION self.assertTrue(updater.setup(self.hass, { @@ -40,6 +37,7 @@ class TestUpdater(unittest.TestCase): @patch('homeassistant.components.updater.get_newest_version') def test_no_entity_on_same_version(self, mock_get_newest_version): + """Test if no entity is created if same version.""" mock_get_newest_version.return_value = CURRENT_VERSION self.assertTrue(updater.setup(self.hass, { @@ -60,14 +58,12 @@ class TestUpdater(unittest.TestCase): @patch('homeassistant.components.updater.requests.get') def test_errors_while_fetching_new_version(self, mock_get): + """Test for errors while fetching the new version.""" mock_get.side_effect = requests.RequestException - self.assertIsNone(updater.get_newest_version()) mock_get.side_effect = ValueError - self.assertIsNone(updater.get_newest_version()) mock_get.side_effect = KeyError - self.assertIsNone(updater.get_newest_version()) diff --git a/tests/components/test_weblink.py b/tests/components/test_weblink.py index 29809722e68..70a32e850ed 100644 --- a/tests/components/test_weblink.py +++ b/tests/components/test_weblink.py @@ -1,9 +1,4 @@ -""" -tests.components.test_weblink -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests weblink component. -""" +"""The tests for the weblink component.""" import unittest from homeassistant.components import weblink @@ -12,16 +7,18 @@ from tests.common import get_test_home_assistant class TestComponentWeblink(unittest.TestCase): - """ Tests homeassistant.components.history module. """ + """Test the Weblink component.""" def setUp(self): - """ Test setup method. """ + """Setup 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_entities_get_created(self): + """Test if new entity is created.""" self.assertTrue(weblink.setup(self.hass, { weblink.DOMAIN: { 'entities': [ diff --git a/tests/components/test_zone.py b/tests/components/test_zone.py index 12f9a04792f..1c7c982a6eb 100644 --- a/tests/components/test_zone.py +++ b/tests/components/test_zone.py @@ -1,9 +1,4 @@ -""" -tests.components.test_zone -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests zone component. -""" +"""Test zone component.""" import unittest from homeassistant.components import zone @@ -12,16 +7,18 @@ from tests.common import get_test_home_assistant class TestComponentZone(unittest.TestCase): - """ Test the zone component. """ + """Test the zone component.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop down everything that was started.""" self.hass.stop() def test_setup(self): + """Test setup.""" info = { 'name': 'Test Zone', 'latitude': 32.880837, @@ -41,6 +38,7 @@ class TestComponentZone(unittest.TestCase): assert info['passive'] == state.attributes['passive'] def test_active_zone_skips_passive_zones(self): + """Test active and passive zones.""" assert zone.setup(self.hass, { 'zone': [ { @@ -71,6 +69,7 @@ class TestComponentZone(unittest.TestCase): assert 'zone.active_zone' == active.entity_id def test_active_zone_prefers_smaller_zone_if_same_distance(self): + """Test zone size preferences.""" latitude = 32.880600 longitude = -117.237561 assert zone.setup(self.hass, { @@ -108,6 +107,7 @@ class TestComponentZone(unittest.TestCase): assert 'zone.smallest_zone' == active.entity_id def test_in_zone_works_for_passive_zones(self): + """Test working in passive zones.""" latitude = 32.880600 longitude = -117.237561 assert zone.setup(self.hass, { diff --git a/tests/components/thermostat/__init__.py b/tests/components/thermostat/__init__.py index e69de29bb2d..9a15198ecb4 100644 --- a/tests/components/thermostat/__init__.py +++ b/tests/components/thermostat/__init__.py @@ -0,0 +1 @@ +"""The tests for Thermostat platforms.""" diff --git a/tests/components/thermostat/test_heat_control.py b/tests/components/thermostat/test_heat_control.py index 9d91d3c70cb..cbd0c021bdb 100644 --- a/tests/components/thermostat/test_heat_control.py +++ b/tests/components/thermostat/test_heat_control.py @@ -1,9 +1,4 @@ -""" -tests.components.thermostat.test_heat_control -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests heat control thermostat. -""" +"""The tests for the heat control thermostat.""" import unittest from homeassistant.const import ( @@ -28,9 +23,10 @@ target_temp = 42.0 class TestThermostatHeatControl(unittest.TestCase): - """ Test the Heat Control thermostat. """ + """Test the Heat Control thermostat.""" def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.config.temperature_unit = TEMP_CELCIUS thermostat.setup(self.hass, {'thermostat': { @@ -41,19 +37,22 @@ class TestThermostatHeatControl(unittest.TestCase): }}) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop down everything that was started.""" self.hass.stop() def test_setup_defaults_to_unknown(self): + """Test the setting of defaults to unknown.""" self.assertEqual('unknown', self.hass.states.get(entity).state) def test_default_setup_params(self): + """Test the setup with default parameters.""" state = self.hass.states.get(entity) self.assertEqual(7, state.attributes.get('min_temp')) self.assertEqual(35, state.attributes.get('max_temp')) self.assertEqual(None, state.attributes.get('temperature')) def test_custom_setup_params(self): + """Test the setup with custom parameters.""" thermostat.setup(self.hass, {'thermostat': { 'platform': 'heat_control', 'name': 'test', @@ -70,11 +69,13 @@ class TestThermostatHeatControl(unittest.TestCase): self.assertEqual(str(target_temp), self.hass.states.get(entity).state) def test_set_target_temp(self): + """Test the setting of the target temperature.""" thermostat.set_temperature(self.hass, 30) self.hass.pool.block_till_done() self.assertEqual('30.0', self.hass.states.get(entity).state) def test_set_target_temp_turns_on_heater(self): + """Test if target temperature turn heater on.""" self._setup_switch(False) self._setup_sensor(25) self.hass.pool.block_till_done() @@ -87,6 +88,7 @@ class TestThermostatHeatControl(unittest.TestCase): self.assertEqual(ent_switch, call.data['entity_id']) def test_set_target_temp_turns_off_heater(self): + """Test if target temperature turn heater off.""" self._setup_switch(True) self._setup_sensor(30) self.hass.pool.block_till_done() @@ -99,6 +101,7 @@ class TestThermostatHeatControl(unittest.TestCase): self.assertEqual(ent_switch, call.data['entity_id']) def test_set_temp_change_turns_on_heater(self): + """Test if temperature change turn heater on.""" self._setup_switch(False) thermostat.set_temperature(self.hass, 30) self.hass.pool.block_till_done() @@ -111,6 +114,7 @@ class TestThermostatHeatControl(unittest.TestCase): self.assertEqual(ent_switch, call.data['entity_id']) def test_temp_change_turns_off_heater(self): + """Test if temperature change turn heater off.""" self._setup_switch(True) thermostat.set_temperature(self.hass, 25) self.hass.pool.block_till_done() @@ -123,18 +127,18 @@ class TestThermostatHeatControl(unittest.TestCase): self.assertEqual(ent_switch, call.data['entity_id']) def _setup_sensor(self, temp, unit=TEMP_CELCIUS): - """ Setup the test sensor. """ + """Setup the test sensor.""" self.hass.states.set(ent_sensor, temp, { ATTR_UNIT_OF_MEASUREMENT: unit }) def _setup_switch(self, is_on): - """ Setup the test switch. """ + """Setup the test switch.""" self.hass.states.set(ent_switch, STATE_ON if is_on else STATE_OFF) self.calls = [] def log_call(call): - """ Log service calls. """ + """Log service calls.""" self.calls.append(call) self.hass.services.register('switch', SERVICE_TURN_ON, log_call) diff --git a/tests/components/thermostat/test_honeywell.py b/tests/components/thermostat/test_honeywell.py index 8e4605c739f..ba3a7f5d8dc 100644 --- a/tests/components/thermostat/test_honeywell.py +++ b/tests/components/thermostat/test_honeywell.py @@ -1,9 +1,4 @@ -""" -tests.components.thermostat.honeywell -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests the Honeywell thermostat module. -""" +"""The test the Honeywell thermostat module.""" import socket import unittest from unittest import mock @@ -16,10 +11,13 @@ import homeassistant.components.thermostat.honeywell as honeywell class TestHoneywell(unittest.TestCase): + """A test class for Honeywell themostats.""" + @mock.patch('somecomfort.SomeComfort') @mock.patch('homeassistant.components.thermostat.' 'honeywell.HoneywellUSThermostat') def test_setup_us(self, mock_ht, mock_sc): + """Test for the US setup.""" config = { CONF_USERNAME: 'user', CONF_PASSWORD: 'pass', @@ -50,6 +48,7 @@ class TestHoneywell(unittest.TestCase): @mock.patch('somecomfort.SomeComfort') def test_setup_us_failures(self, mock_sc): + """Test the US setup.""" hass = mock.MagicMock() add_devices = mock.MagicMock() config = { @@ -72,6 +71,7 @@ class TestHoneywell(unittest.TestCase): @mock.patch('homeassistant.components.thermostat.' 'honeywell.HoneywellUSThermostat') def _test_us_filtered_devices(self, mock_ht, mock_sc, loc=None, dev=None): + """Test for US filtered thermostats.""" config = { CONF_USERNAME: 'user', CONF_PASSWORD: 'pass', @@ -107,18 +107,21 @@ class TestHoneywell(unittest.TestCase): return mock_ht.call_args_list, mock_sc def test_us_filtered_thermostat_1(self): + """Test for US filtered thermostats.""" result, client = self._test_us_filtered_devices( dev=mock.sentinel.loc1dev1) devices = [x[0][1].deviceid for x in result] self.assertEqual([mock.sentinel.loc1dev1], devices) def test_us_filtered_thermostat_2(self): + """Test for US filtered location.""" result, client = self._test_us_filtered_devices( dev=mock.sentinel.loc2dev1) devices = [x[0][1].deviceid for x in result] self.assertEqual([mock.sentinel.loc2dev1], devices) def test_us_filtered_location_1(self): + """Test for US filtered locations.""" result, client = self._test_us_filtered_devices( loc=mock.sentinel.loc1) devices = [x[0][1].deviceid for x in result] @@ -126,6 +129,7 @@ class TestHoneywell(unittest.TestCase): mock.sentinel.loc1dev2], devices) def test_us_filtered_location_2(self): + """Test for US filtered locations.""" result, client = self._test_us_filtered_devices( loc=mock.sentinel.loc2) devices = [x[0][1].deviceid for x in result] @@ -135,6 +139,7 @@ class TestHoneywell(unittest.TestCase): @mock.patch('homeassistant.components.thermostat.honeywell.' 'RoundThermostat') def test_eu_setup_full_config(self, mock_round, mock_evo): + """Test the EU setup wwith complete configuration.""" config = { CONF_USERNAME: 'user', CONF_PASSWORD: 'pass', @@ -159,6 +164,7 @@ class TestHoneywell(unittest.TestCase): @mock.patch('homeassistant.components.thermostat.honeywell.' 'RoundThermostat') def test_eu_setup_partial_config(self, mock_round, mock_evo): + """Test the EU setup with partial configuration.""" config = { CONF_USERNAME: 'user', CONF_PASSWORD: 'pass', @@ -179,6 +185,7 @@ class TestHoneywell(unittest.TestCase): @mock.patch('homeassistant.components.thermostat.honeywell.' 'RoundThermostat') def test_eu_setup_bad_temp(self, mock_round, mock_evo): + """Test the EU setup with invalid temperature.""" config = { CONF_USERNAME: 'user', CONF_PASSWORD: 'pass', @@ -191,6 +198,7 @@ class TestHoneywell(unittest.TestCase): @mock.patch('homeassistant.components.thermostat.honeywell.' 'RoundThermostat') def test_eu_setup_error(self, mock_round, mock_evo): + """Test the EU setup with errors.""" config = { CONF_USERNAME: 'user', CONF_PASSWORD: 'pass', @@ -204,8 +212,12 @@ class TestHoneywell(unittest.TestCase): class TestHoneywellRound(unittest.TestCase): + """A test class for Honeywell Round thermostats.""" + def setup_method(self, method): + """Test the setup method.""" def fake_temperatures(force_refresh=None): + """Create fake temperatures.""" temps = [ {'id': '1', 'temp': 20, 'setpoint': 21, 'thermostat': 'main', 'name': 'House'}, @@ -222,6 +234,7 @@ class TestHoneywellRound(unittest.TestCase): False, 17) def test_attributes(self): + """Test the attributes.""" self.assertEqual('House', self.round1.name) self.assertEqual(TEMP_CELCIUS, self.round1.unit_of_measurement) self.assertEqual(20, self.round1.current_temperature) @@ -235,6 +248,7 @@ class TestHoneywellRound(unittest.TestCase): self.assertFalse(self.round2.is_away_mode_on) def test_away_mode(self): + """Test setting the away mode.""" self.assertFalse(self.round1.is_away_mode_on) self.round1.turn_away_mode_on() self.assertTrue(self.round1.is_away_mode_on) @@ -246,12 +260,16 @@ class TestHoneywellRound(unittest.TestCase): self.device.cancel_temp_override.assert_called_once_with('House') def test_set_temperature(self): + """Test setting the temperature.""" self.round1.set_temperature(25) self.device.set_temperature.assert_called_once_with('House', 25) class TestHoneywellUS(unittest.TestCase): + """A test class for Honeywell US thermostats.""" + def setup_method(self, method): + """Test the setup method.""" self.client = mock.MagicMock() self.device = mock.MagicMock() self.honeywell = honeywell.HoneywellUSThermostat( @@ -267,21 +285,25 @@ class TestHoneywellUS(unittest.TestCase): self.device.fan_mode = 'auto' def test_properties(self): + """Test the properties.""" self.assertTrue(self.honeywell.is_fan_on) self.assertEqual('test', self.honeywell.name) self.assertEqual(72, self.honeywell.current_temperature) def test_unit_of_measurement(self): + """Test the unit of measurement.""" self.assertEqual(TEMP_FAHRENHEIT, self.honeywell.unit_of_measurement) self.device.temperature_unit = 'C' self.assertEqual(TEMP_CELCIUS, self.honeywell.unit_of_measurement) def test_target_temp(self): + """Test the target temperature.""" self.assertEqual(65, self.honeywell.target_temperature) self.device.system_mode = 'cool' self.assertEqual(78, self.honeywell.target_temperature) def test_set_temp(self): + """Test setting the temperature.""" self.honeywell.set_temperature(70) self.assertEqual(70, self.device.setpoint_heat) self.assertEqual(70, self.honeywell.target_temperature) @@ -293,11 +315,13 @@ class TestHoneywellUS(unittest.TestCase): self.assertEqual(74, self.honeywell.target_temperature) def test_set_temp_fail(self): + """Test if setting the temperature fails.""" self.device.setpoint_heat = mock.MagicMock( side_effect=somecomfort.SomeComfortError) self.honeywell.set_temperature(123) def test_attributes(self): + """Test the attributes.""" expected = { 'fan': 'running', 'fanmode': 'auto', @@ -309,6 +333,7 @@ class TestHoneywellUS(unittest.TestCase): self.assertEqual(expected, self.honeywell.device_state_attributes) def test_with_no_fan(self): + """Test if there is on fan.""" self.device.fan_running = False self.device.fan_mode = None expected = { diff --git a/tests/config/custom_components/device_tracker/test.py b/tests/config/custom_components/device_tracker/test.py index 11c0a090420..e6c2dfdfb91 100644 --- a/tests/config/custom_components/device_tracker/test.py +++ b/tests/config/custom_components/device_tracker/test.py @@ -1,44 +1,38 @@ -""" -config.custom_components.device_tracker.test -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Provides a mock device scanner. -""" +"""Provide a mock device scanner.""" def get_scanner(hass, config): - """ Returns a mock scanner. """ + """Returns a mock scanner.""" return SCANNER class MockScanner(object): - """ Mock device scanner. """ + """Mock device scanner.""" def __init__(self): - """ Initialize the MockScanner. """ + """Initialize the MockScanner.""" self.devices_home = [] def come_home(self, device): - """ Make a device come home. """ + """Make a device come home.""" self.devices_home.append(device) def leave_home(self, device): - """ Make a device leave the house. """ + """Make a device leave the house.""" self.devices_home.remove(device) def reset(self): - """ Resets which devices are home. """ + """Reset which devices are home.""" self.devices_home = [] def scan_devices(self): - """ Returns a list of fake devices. """ - + """Return a list of fake devices.""" return list(self.devices_home) def get_device_name(self, device): - """ - Returns a name for a mock device. - Returns None for dev1 for testing. + """Return a name for a mock device. + + Return None for dev1 for testing. """ return None if device == 'DEV1' else device.lower() diff --git a/tests/config/custom_components/light/test.py b/tests/config/custom_components/light/test.py index 6999f2436ca..07a856d42bc 100644 --- a/tests/config/custom_components/light/test.py +++ b/tests/config/custom_components/light/test.py @@ -1,8 +1,5 @@ """ -config.custom_components.light.test -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Provides a mock switch platform. +Provide a mock switch platform. Call init before using it in your tests to ensure clean test data. """ @@ -14,7 +11,7 @@ DEVICES = [] def init(empty=False): - """ (re-)initalizes the platform with devices. """ + """Initalize the platform with devices.""" global DEVICES DEVICES = [] if empty else [ @@ -25,5 +22,5 @@ def init(empty=False): def setup_platform(hass, config, add_devices_callback, discovery_info=None): - """ Returns mock devices. """ + """Return mock devices.""" add_devices_callback(DEVICES) diff --git a/tests/config/custom_components/switch/test.py b/tests/config/custom_components/switch/test.py index 5d3c2585e5d..ca027e9e906 100644 --- a/tests/config/custom_components/switch/test.py +++ b/tests/config/custom_components/switch/test.py @@ -1,8 +1,5 @@ """ -config.custom_components.switch.test -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Provides a mock switch platform. +Provide a mock switch platform. Call init before using it in your tests to ensure clean test data. """ @@ -14,7 +11,7 @@ DEVICES = [] def init(empty=False): - """ (re-)initalizes the platform with devices. """ + """Initalize the platform with devices.""" global DEVICES DEVICES = [] if empty else [ @@ -25,5 +22,5 @@ def init(empty=False): def setup_platform(hass, config, add_devices_callback, discovery_info=None): - """ Find and return test switches. """ + """Find and return test switches.""" add_devices_callback(DEVICES) diff --git a/tests/helpers/test_entity.py b/tests/helpers/test_entity.py index 7e305454228..94fbd383f61 100644 --- a/tests/helpers/test_entity.py +++ b/tests/helpers/test_entity.py @@ -1,9 +1,4 @@ -""" -tests.helpers.test_entity -~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests the entity helper. -""" +"""Test the entity helper.""" # pylint: disable=protected-access,too-many-public-methods import unittest @@ -14,29 +9,29 @@ from tests.common import get_test_home_assistant class TestHelpersEntity(unittest.TestCase): - """ Tests homeassistant.helpers.entity module. """ + """Test homeassistant.helpers.entity module.""" def setUp(self): # pylint: disable=invalid-name - """ Init needed objects. """ + """Init needed objects.""" self.entity = entity.Entity() self.entity.entity_id = 'test.overwrite_hidden_true' self.hass = self.entity.hass = get_test_home_assistant() self.entity.update_ha_state() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() entity.Entity.overwrite_attribute(self.entity.entity_id, [ATTR_HIDDEN], [None]) def test_default_hidden_not_in_attributes(self): - """ Test that the default hidden property is set to False. """ + """Test that the default hidden property is set to False.""" self.assertNotIn( ATTR_HIDDEN, self.hass.states.get(self.entity.entity_id).attributes) def test_overwriting_hidden_property_to_true(self): - """ Test we can overwrite hidden property to True. """ + """Test we can overwrite hidden property to True.""" entity.Entity.overwrite_attribute(self.entity.entity_id, [ATTR_HIDDEN], [True]) self.entity.update_ha_state() @@ -45,6 +40,6 @@ class TestHelpersEntity(unittest.TestCase): self.assertTrue(state.attributes.get(ATTR_HIDDEN)) def test_split_entity_id(self): - """ Test split_entity_id. """ + """Test split_entity_id.""" self.assertEqual(['domain', 'object_id'], entity.split_entity_id('domain.object_id')) diff --git a/tests/helpers/test_entity_component.py b/tests/helpers/test_entity_component.py index 6bd1a4e22f0..43c876cf98c 100644 --- a/tests/helpers/test_entity_component.py +++ b/tests/helpers/test_entity_component.py @@ -1,9 +1,4 @@ -""" -tests.helpers.test_entity_component -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests the entity component helper. -""" +"""Test the entity component helper.""" # pylint: disable=protected-access,too-many-public-methods from collections import OrderedDict import logging diff --git a/tests/helpers/test_event.py b/tests/helpers/test_event.py index 91cf252443c..6d3a9cbb6a0 100644 --- a/tests/helpers/test_event.py +++ b/tests/helpers/test_event.py @@ -1,9 +1,4 @@ -""" -tests.helpers.event_test -~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests event helpers. -""" +"""Test event helpers.""" # pylint: disable=protected-access,too-many-public-methods # pylint: disable=too-few-public-methods import unittest @@ -28,20 +23,18 @@ from tests.common import get_test_home_assistant class TestEventHelpers(unittest.TestCase): - """ - Tests the Home Assistant event helpers. - """ + """Test the Home Assistant event helpers.""" def setUp(self): # pylint: disable=invalid-name - """ things to be run when tests are started. """ + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_track_point_in_time(self): - """ Test track point in time. """ + """Test track point in time.""" before_birthday = datetime(1985, 7, 9, 12, 0, 0, tzinfo=dt_util.UTC) birthday_paulus = datetime(1986, 7, 9, 12, 0, 0, tzinfo=dt_util.UTC) after_birthday = datetime(1987, 7, 9, 12, 0, 0, tzinfo=dt_util.UTC) @@ -72,7 +65,7 @@ class TestEventHelpers(unittest.TestCase): self.assertEqual(2, len(runs)) def test_track_time_change(self): - """ Test tracking time change. """ + """Test tracking time change.""" wildcard_runs = [] specific_runs = [] @@ -150,16 +143,16 @@ class TestEventHelpers(unittest.TestCase): self.assertIsNone(wildcard_runs[-1][1]) def test_track_sunrise(self): - """ Test track sunrise """ + """Test track the sunrise.""" latitude = 32.87336 longitude = 117.22743 - # setup sun component + # Setup sun component self.hass.config.latitude = latitude self.hass.config.longitude = longitude sun.setup(self.hass, {sun.DOMAIN: {sun.CONF_ELEVATION: 0}}) - # get next sunrise/sunset + # Get next sunrise/sunset astral = Astral() utc_now = dt_util.utcnow() @@ -171,7 +164,7 @@ class TestEventHelpers(unittest.TestCase): break mod += 1 - # track sunrise + # Track sunrise runs = [] track_sunrise(self.hass, lambda: runs.append(1)) @@ -196,16 +189,16 @@ class TestEventHelpers(unittest.TestCase): self.assertEqual(1, len(offset_runs)) def test_track_sunset(self): - """ Test track sunset """ + """Test track the sunset.""" latitude = 32.87336 longitude = 117.22743 - # setup sun component + # Setup sun component self.hass.config.latitude = latitude self.hass.config.longitude = longitude sun.setup(self.hass, {sun.DOMAIN: {sun.CONF_ELEVATION: 0}}) - # get next sunrise/sunset + # Get next sunrise/sunset astral = Astral() utc_now = dt_util.utcnow() @@ -217,7 +210,7 @@ class TestEventHelpers(unittest.TestCase): break mod += 1 - # track sunset + # Track sunset runs = [] track_sunset(self.hass, lambda: runs.append(1)) @@ -225,7 +218,7 @@ class TestEventHelpers(unittest.TestCase): offset = timedelta(minutes=30) track_sunset(self.hass, lambda: offset_runs.append(1), offset) - # run tests + # Run tests self._send_time_changed(next_setting - offset) self.hass.pool.block_till_done() self.assertEqual(0, len(runs)) @@ -242,10 +235,11 @@ class TestEventHelpers(unittest.TestCase): self.assertEqual(1, len(offset_runs)) def _send_time_changed(self, now): - """ Send a time changed event. """ + """Send a time changed event.""" self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: now}) def test_periodic_task_minute(self): + """Test periodic tasks per minute.""" specific_runs = [] track_utc_time_change( @@ -264,6 +258,7 @@ class TestEventHelpers(unittest.TestCase): self.assertEqual(2, len(specific_runs)) def test_periodic_task_hour(self): + """Test periodic tasks per hour.""" specific_runs = [] track_utc_time_change( @@ -290,6 +285,7 @@ class TestEventHelpers(unittest.TestCase): self.assertEqual(3, len(specific_runs)) def test_periodic_task_day(self): + """Test periodic tasks per day.""" specific_runs = [] track_utc_time_change( @@ -308,6 +304,7 @@ class TestEventHelpers(unittest.TestCase): self.assertEqual(2, len(specific_runs)) def test_periodic_task_year(self): + """Test periodic tasks per year.""" specific_runs = [] track_utc_time_change( @@ -326,6 +323,7 @@ class TestEventHelpers(unittest.TestCase): self.assertEqual(2, len(specific_runs)) def test_periodic_task_wrong_input(self): + """Test periodic tasks with wrong input.""" specific_runs = [] track_utc_time_change( diff --git a/tests/helpers/test_event_decorators.py b/tests/helpers/test_event_decorators.py index 99fcf8c5d0f..cf2126175ea 100644 --- a/tests/helpers/test_event_decorators.py +++ b/tests/helpers/test_event_decorators.py @@ -1,9 +1,4 @@ -""" -tests.helpers.test_event_decorators -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests event decorator helpers. -""" +"""Test event decorator helpers.""" # pylint: disable=protected-access,too-many-public-methods # pylint: disable=too-few-public-methods import unittest @@ -23,12 +18,10 @@ from tests.common import get_test_home_assistant class TestEventDecoratorHelpers(unittest.TestCase): - """ - Tests the Home Assistant event helpers. - """ + """Test the Home Assistant event helpers.""" def setUp(self): # pylint: disable=invalid-name - """ things to be run when tests are started. """ + """Setup things to be run when tests are started. """ self.hass = get_test_home_assistant() self.hass.states.set("light.Bowl", "on") self.hass.states.set("switch.AC", "off") @@ -41,16 +34,16 @@ class TestEventDecoratorHelpers(unittest.TestCase): event_decorators.HASS = None def test_track_sunrise(self): - """ Test track sunrise decorator """ + """Test track sunrise decorator.""" latitude = 32.87336 longitude = 117.22743 - # setup sun component + # Setup sun component self.hass.config.latitude = latitude self.hass.config.longitude = longitude sun.setup(self.hass, {sun.DOMAIN: {sun.CONF_ELEVATION: 0}}) - # get next sunrise/sunset + # Get next sunrise/sunset astral = Astral() utc_now = dt_util.utcnow() @@ -62,7 +55,7 @@ class TestEventDecoratorHelpers(unittest.TestCase): break mod += 1 - # use decorator + # Use decorator runs = [] decor = track_sunrise() decor(lambda x: runs.append(1)) @@ -72,7 +65,7 @@ class TestEventDecoratorHelpers(unittest.TestCase): decor = track_sunrise(offset) decor(lambda x: offset_runs.append(1)) - # run tests + # Run tests self._send_time_changed(next_rising - offset) self.hass.pool.block_till_done() self.assertEqual(0, len(runs)) @@ -89,16 +82,16 @@ class TestEventDecoratorHelpers(unittest.TestCase): self.assertEqual(1, len(offset_runs)) def test_track_sunset(self): - """ Test track sunset decorator """ + """Test track sunset decorator.""" latitude = 32.87336 longitude = 117.22743 - # setup sun component + # Setup sun component self.hass.config.latitude = latitude self.hass.config.longitude = longitude sun.setup(self.hass, {sun.DOMAIN: {sun.CONF_ELEVATION: 0}}) - # get next sunrise/sunset + # Get next sunrise/sunset astral = Astral() utc_now = dt_util.utcnow() @@ -110,7 +103,7 @@ class TestEventDecoratorHelpers(unittest.TestCase): break mod += 1 - # use decorator + # Use decorator runs = [] decor = track_sunset() decor(lambda x: runs.append(1)) @@ -137,7 +130,7 @@ class TestEventDecoratorHelpers(unittest.TestCase): self.assertEqual(1, len(offset_runs)) def test_track_time_change(self): - """ Test tracking time change. """ + """Test tracking time change.""" wildcard_runs = [] specific_runs = [] @@ -163,7 +156,7 @@ class TestEventDecoratorHelpers(unittest.TestCase): self.assertEqual(3, len(wildcard_runs)) def test_track_state_change(self): - """ Test track_state_change. """ + """Test track_state_change.""" # 2 lists to track how often our callbacks get called specific_runs = [] wildcard_runs = [] @@ -199,5 +192,5 @@ class TestEventDecoratorHelpers(unittest.TestCase): self.assertEqual(3, len(wildcard_runs)) def _send_time_changed(self, now): - """ Send a time changed event. """ + """Send a time changed event.""" self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: now}) diff --git a/tests/helpers/test_init.py b/tests/helpers/test_init.py index fc6ec914046..098211085f7 100644 --- a/tests/helpers/test_init.py +++ b/tests/helpers/test_init.py @@ -1,9 +1,4 @@ -""" -tests.helpers.test_init -~~~~~~~~~~~~~~~~~~~~~~~ - -Tests component helpers. -""" +"""Test component helpers.""" # pylint: disable=protected-access,too-many-public-methods import unittest @@ -13,17 +8,18 @@ from tests.common import get_test_home_assistant class TestHelpers(unittest.TestCase): - """ Tests homeassistant.helpers module. """ + """Tests homeassistant.helpers module.""" def setUp(self): # pylint: disable=invalid-name - """ Init needed objects. """ + """Init needed objects.""" self.hass = get_test_home_assistant() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_extract_domain_configs(self): + """Test the extraction of domain configuration.""" config = { 'zone': None, 'zoner': None, diff --git a/tests/helpers/test_location.py b/tests/helpers/test_location.py index dfd57f642bd..ddecf368dc7 100644 --- a/tests/helpers/test_location.py +++ b/tests/helpers/test_location.py @@ -8,11 +8,15 @@ from homeassistant.helpers import location class TestHelpersLocation(unittest.TestCase): + """Setup the tests.""" + def test_has_location_with_invalid_states(self): + """Setup the tests.""" for state in (None, 1, "hello", object): self.assertFalse(location.has_location(state)) def test_has_location_with_states_with_invalid_locations(self): + """Setup the tests.""" state = State('hello.world', 'invalid', { ATTR_LATITUDE: 'no number', ATTR_LONGITUDE: 123.12 @@ -20,6 +24,7 @@ class TestHelpersLocation(unittest.TestCase): self.assertFalse(location.has_location(state)) def test_has_location_with_states_with_valid_location(self): + """Setup the tests.""" state = State('hello.world', 'invalid', { ATTR_LATITUDE: 123.12, ATTR_LONGITUDE: 123.12 @@ -27,6 +32,7 @@ class TestHelpersLocation(unittest.TestCase): self.assertTrue(location.has_location(state)) def test_closest_with_no_states_with_location(self): + """Setup the tests.""" state = State('light.test', 'on') state2 = State('light.test', 'on', { ATTR_LATITUDE: 'invalid', @@ -40,6 +46,7 @@ class TestHelpersLocation(unittest.TestCase): location.closest(123.45, 123.45, [state, state2, state3])) def test_closest_returns_closest(self): + """Test .""" state = State('light.test', 'on', { ATTR_LATITUDE: 124.45, ATTR_LONGITUDE: 124.45, diff --git a/tests/helpers/test_service.py b/tests/helpers/test_service.py index 73081a7da7e..830c382bb59 100644 --- a/tests/helpers/test_service.py +++ b/tests/helpers/test_service.py @@ -1,9 +1,4 @@ -""" -tests.helpers.test_service -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Test service helpers. -""" +"""Test service helpers.""" import unittest from unittest.mock import patch @@ -15,21 +10,21 @@ from tests.common import get_test_home_assistant, mock_service class TestServiceHelpers(unittest.TestCase): - """ Tests the Home Assistant service helpers. """ + """Test the Home Assistant service helpers.""" def setUp(self): # pylint: disable=invalid-name - """ things to be run when tests are started. """ + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.calls = mock_service(self.hass, 'test_domain', 'test_service') service.HASS = self.hass def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop down everything that was started.""" self.hass.stop() def test_service(self): - """ Test service registration decorator. """ + """Test service registration decorator.""" runs = [] decor = service.service('test', 'test') @@ -40,6 +35,7 @@ class TestServiceHelpers(unittest.TestCase): self.assertEqual(1, len(runs)) def test_split_entity_string(self): + """Test splitting of entity string.""" service.call_from_config(self.hass, { 'service': 'test_domain.test_service', 'entity_id': 'hello.world, sensor.beer' @@ -49,6 +45,7 @@ class TestServiceHelpers(unittest.TestCase): self.calls[-1].data.get('entity_id')) def test_not_mutate_input(self): + """Test for immutable input.""" orig = { 'service': 'test_domain.test_service', 'entity_id': 'hello.world, sensor.beer', @@ -68,6 +65,7 @@ class TestServiceHelpers(unittest.TestCase): @patch('homeassistant.helpers.service._LOGGER.error') def test_fail_silently_if_no_service(self, mock_log): + """Test failling if service is missing.""" service.call_from_config(self.hass, None) self.assertEqual(1, mock_log.call_count) @@ -80,7 +78,7 @@ class TestServiceHelpers(unittest.TestCase): self.assertEqual(3, mock_log.call_count) def test_extract_entity_ids(self): - """ Test extract_entity_ids method. """ + """Test extract_entity_ids method.""" self.hass.states.set('light.Bowl', STATE_ON) self.hass.states.set('light.Ceiling', STATE_OFF) self.hass.states.set('light.Kitchen', STATE_OFF) diff --git a/tests/helpers/test_state.py b/tests/helpers/test_state.py index a19968d21ae..d84f82c1be6 100644 --- a/tests/helpers/test_state.py +++ b/tests/helpers/test_state.py @@ -1,9 +1,4 @@ -""" -tests.helpers.test_state -~~~~~~~~~~~~~~~~~~~~~~~~ - -Test state helpers. -""" +"""Test state helpers.""" from datetime import timedelta import unittest from unittest.mock import patch @@ -24,18 +19,19 @@ from tests.common import get_test_home_assistant, mock_service class TestStateHelpers(unittest.TestCase): - """ Tests the Home Assistant event helpers. """ + """Test the Home Assistant event helpers.""" def setUp(self): # pylint: disable=invalid-name - """ Things to be run when tests are started. """ + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() core_components.setup(self.hass, {}) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop down everything that was started.""" self.hass.stop() def test_get_changed_since(self): + """Test for changes since.""" point1 = dt_util.utcnow() point2 = point1 + timedelta(seconds=5) point3 = point2 + timedelta(seconds=5) @@ -57,6 +53,7 @@ class TestStateHelpers(unittest.TestCase): state.get_changed_since([state1, state2, state3], point2)) def test_track_states(self): + """Test tracking of states.""" point1 = dt_util.utcnow() point2 = point1 + timedelta(seconds=5) point3 = point2 + timedelta(seconds=5) @@ -81,6 +78,7 @@ class TestStateHelpers(unittest.TestCase): sorted(states, key=lambda state: state.entity_id)) def test_reproduce_state_with_turn_on(self): + """Test reproduction of state with turn_on.""" calls = mock_service(self.hass, 'light', SERVICE_TURN_ON) self.hass.states.set('light.test', 'off') @@ -96,6 +94,7 @@ class TestStateHelpers(unittest.TestCase): self.assertEqual(['light.test'], last_call.data.get('entity_id')) def test_reproduce_state_with_complex_service_data(self): + """Test reproduction of state with complex service data.""" calls = mock_service(self.hass, 'light', SERVICE_TURN_ON) self.hass.states.set('light.test', 'off') @@ -115,6 +114,7 @@ class TestStateHelpers(unittest.TestCase): self.assertEqual(complex_data, last_call.data.get('complex')) def test_reproduce_state_with_group(self): + """Test reproduction of state with group.""" light_calls = mock_service(self.hass, 'light', SERVICE_TURN_ON) self.hass.states.set('group.test', 'off', { @@ -132,6 +132,7 @@ class TestStateHelpers(unittest.TestCase): last_call.data.get('entity_id')) def test_reproduce_state_group_states_with_same_domain_and_data(self): + """Test reproduction of state with the dame domain.""" light_calls = mock_service(self.hass, 'light', SERVICE_TURN_ON) self.hass.states.set('light.test1', 'off') @@ -152,6 +153,7 @@ class TestStateHelpers(unittest.TestCase): self.assertEqual(95, last_call.data.get('brightness')) def test_as_number_states(self): + """Test number as states.""" zero_states = (STATE_OFF, STATE_CLOSED, STATE_UNLOCKED, STATE_BELOW_HORIZON) one_states = (STATE_ON, STATE_OPEN, STATE_LOCKED, STATE_ABOVE_HORIZON) @@ -163,6 +165,7 @@ class TestStateHelpers(unittest.TestCase): ha.State('domain.test', _state, {}))) def test_as_number_coercion(self): + """Test numbers.""" for _state in ('0', '0.0', 0, 0.0): self.assertEqual( 0.0, state.state_as_number( @@ -173,6 +176,7 @@ class TestStateHelpers(unittest.TestCase): ha.State('domain.test', _state, {}))) def test_as_number_invalid_cases(self): + """.""" for _state in ('', 'foo', 'foo.bar', None, False, True, object, object()): self.assertRaises(ValueError, diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 4aefdcf4fc5..9aa91c3cd1a 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -1,6 +1,4 @@ -""" -Tests Home Assistant template helper methods. -""" +"""Test Home Assistant template helper methods.""" # pylint: disable=too-many-public-methods import unittest from unittest.mock import patch @@ -14,8 +12,10 @@ from tests.common import get_test_home_assistant class TestUtilTemplate(unittest.TestCase): + """Test the Template.""" def setUp(self): # pylint: disable=invalid-name + """Setup the tests.""" self.hass = get_test_home_assistant() def tearDown(self): # pylint: disable=invalid-name @@ -23,12 +23,14 @@ class TestUtilTemplate(unittest.TestCase): self.hass.stop() def test_referring_states_by_entity_id(self): + """.""" self.hass.states.set('test.object', 'happy') self.assertEqual( 'happy', template.render(self.hass, '{{ states.test.object.state }}')) def test_iterating_all_states(self): + """.""" self.hass.states.set('test.object', 'happy') self.hass.states.set('sensor.temperature', 10) @@ -39,6 +41,7 @@ class TestUtilTemplate(unittest.TestCase): '{% for state in states %}{{ state.state }}{% endfor %}')) def test_iterating_domain_states(self): + """.""" self.hass.states.set('test.object', 'happy') self.hass.states.set('sensor.back_door', 'open') self.hass.states.set('sensor.temperature', 10) @@ -52,6 +55,7 @@ class TestUtilTemplate(unittest.TestCase): """)) def test_float(self): + """.""" self.hass.states.set('sensor.temperature', '12') self.assertEqual( @@ -67,6 +71,7 @@ class TestUtilTemplate(unittest.TestCase): '{{ float(states.sensor.temperature.state) > 11 }}')) def test_rounding_value(self): + """.""" self.hass.states.set('sensor.temperature', 12.78) self.assertEqual( @@ -83,6 +88,7 @@ class TestUtilTemplate(unittest.TestCase): )) def test_rounding_value_get_original_value_on_error(self): + """.""" self.assertEqual( 'None', template.render( @@ -98,6 +104,7 @@ class TestUtilTemplate(unittest.TestCase): )) def test_multiply(self): + """.""" tests = { None: 'None', 10: '100', @@ -111,42 +118,50 @@ class TestUtilTemplate(unittest.TestCase): '{{ %s | multiply(10) | round }}' % inp)) def test_passing_vars_as_keywords(self): + """.""" self.assertEqual( '127', template.render(self.hass, '{{ hello }}', hello=127)) def test_passing_vars_as_vars(self): + """.""" self.assertEqual( '127', template.render(self.hass, '{{ hello }}', {'hello': 127})) def test_render_with_possible_json_value_with_valid_json(self): + """.""" self.assertEqual( 'world', template.render_with_possible_json_value( self.hass, '{{ value_json.hello }}', '{"hello": "world"}')) def test_render_with_possible_json_value_with_invalid_json(self): + """.""" self.assertEqual( '', template.render_with_possible_json_value( self.hass, '{{ value_json }}', '{ I AM NOT JSON }')) def test_render_with_possible_json_value_with_template_error(self): + """.""" self.assertEqual( 'hello', template.render_with_possible_json_value( self.hass, '{{ value_json', 'hello')) def test_render_with_possible_json_value_with_template_error_value(self): + """.""" self.assertEqual( '-', template.render_with_possible_json_value( self.hass, '{{ value_json', 'hello', '-')) def test_raise_exception_on_error(self): + """.""" with self.assertRaises(TemplateError): template.render(self.hass, '{{ invalid_syntax') def test_if_state_exists(self): + """.""" self.hass.states.set('test.object', 'available') self.assertEqual( 'exists', @@ -157,6 +172,7 @@ class TestUtilTemplate(unittest.TestCase): """)) def test_is_state(self): + """.""" self.hass.states.set('test.object', 'available') self.assertEqual( 'yes', @@ -167,6 +183,7 @@ class TestUtilTemplate(unittest.TestCase): """)) def test_is_state_attr(self): + """.""" self.hass.states.set('test.object', 'available', {'mode': 'on'}) self.assertEqual( 'yes', @@ -177,6 +194,7 @@ class TestUtilTemplate(unittest.TestCase): """)) def test_states_function(self): + """.""" self.hass.states.set('test.object', 'available') self.assertEqual( 'available', @@ -189,6 +207,7 @@ class TestUtilTemplate(unittest.TestCase): @patch('homeassistant.helpers.template.TemplateEnvironment.' 'is_safe_callable', return_value=True) def test_now(self, mock_is_safe, mock_utcnow): + """.""" self.assertEqual( dt_util.utcnow().isoformat(), template.render(self.hass, '{{ now.isoformat() }}')) @@ -197,16 +216,19 @@ class TestUtilTemplate(unittest.TestCase): @patch('homeassistant.helpers.template.TemplateEnvironment.' 'is_safe_callable', return_value=True) def test_utcnow(self, mock_is_safe, mock_utcnow): + """.""" self.assertEqual( dt_util.utcnow().isoformat(), template.render(self.hass, '{{ utcnow.isoformat() }}')) def test_utcnow_is_exactly_now(self): + """.""" self.assertEqual( 'True', template.render(self.hass, '{{ utcnow == now }}')) def test_distance_function_with_1_state(self): + """.""" self.hass.states.set('test.object', 'happy', { 'latitude': 32.87336, 'longitude': -117.22943, @@ -218,6 +240,7 @@ class TestUtilTemplate(unittest.TestCase): self.hass, '{{ distance(states.test.object) | round }}')) def test_distance_function_with_2_states(self): + """.""" self.hass.states.set('test.object', 'happy', { 'latitude': 32.87336, 'longitude': -117.22943, @@ -236,12 +259,14 @@ class TestUtilTemplate(unittest.TestCase): '| round }}')) def test_distance_function_with_1_coord(self): + """.""" self.assertEqual( '187', template.render( self.hass, '{{ distance("32.87336", "-117.22943") | round }}')) def test_distance_function_with_2_coords(self): + """.""" self.assertEqual( '187', template.render( @@ -250,6 +275,7 @@ class TestUtilTemplate(unittest.TestCase): % (self.hass.config.latitude, self.hass.config.longitude))) def test_distance_function_with_1_state_1_coord(self): + """.""" self.hass.states.set('test.object_2', 'happy', { 'latitude': self.hass.config.latitude, 'longitude': self.hass.config.longitude, @@ -270,6 +296,7 @@ class TestUtilTemplate(unittest.TestCase): '| round }}')) def test_distance_function_return_None_if_invalid_state(self): + """.""" self.hass.states.set('test.object_2', 'happy', { 'latitude': 10, }) @@ -281,6 +308,7 @@ class TestUtilTemplate(unittest.TestCase): '{{ distance(states.test.object_2) | round }}')) def test_distance_function_return_None_if_invalid_coord(self): + """.""" self.assertEqual( 'None', template.render( @@ -305,6 +333,7 @@ class TestUtilTemplate(unittest.TestCase): '{{ distance("123", states.test_object_2) }}')) def test_closest_function_home_vs_domain(self): + """.""" self.hass.states.set('test_domain.object', 'happy', { 'latitude': self.hass.config.latitude + 0.1, 'longitude': self.hass.config.longitude + 0.1, @@ -321,6 +350,7 @@ class TestUtilTemplate(unittest.TestCase): '{{ closest(states.test_domain).entity_id }}')) def test_closest_function_home_vs_all_states(self): + """.""" self.hass.states.set('test_domain.object', 'happy', { 'latitude': self.hass.config.latitude + 0.1, 'longitude': self.hass.config.longitude + 0.1, @@ -337,6 +367,7 @@ class TestUtilTemplate(unittest.TestCase): '{{ closest(states).entity_id }}')) def test_closest_function_home_vs_group_entity_id(self): + """.""" self.hass.states.set('test_domain.object', 'happy', { 'latitude': self.hass.config.latitude + 0.1, 'longitude': self.hass.config.longitude + 0.1, @@ -355,6 +386,7 @@ class TestUtilTemplate(unittest.TestCase): '{{ closest("group.location_group").entity_id }}')) def test_closest_function_home_vs_group_state(self): + """.""" self.hass.states.set('test_domain.object', 'happy', { 'latitude': self.hass.config.latitude + 0.1, 'longitude': self.hass.config.longitude + 0.1, @@ -374,6 +406,7 @@ class TestUtilTemplate(unittest.TestCase): '{{ closest(states.group.location_group).entity_id }}')) def test_closest_function_to_coord(self): + """.""" self.hass.states.set('test_domain.closest_home', 'happy', { 'latitude': self.hass.config.latitude + 0.1, 'longitude': self.hass.config.longitude + 0.1, @@ -399,6 +432,7 @@ class TestUtilTemplate(unittest.TestCase): ) def test_closest_function_to_entity_id(self): + """.""" self.hass.states.set('test_domain.closest_home', 'happy', { 'latitude': self.hass.config.latitude + 0.1, 'longitude': self.hass.config.longitude + 0.1, @@ -422,6 +456,7 @@ class TestUtilTemplate(unittest.TestCase): ) def test_closest_function_to_state(self): + """.""" self.hass.states.set('test_domain.closest_home', 'happy', { 'latitude': self.hass.config.latitude + 0.1, 'longitude': self.hass.config.longitude + 0.1, @@ -446,6 +481,7 @@ class TestUtilTemplate(unittest.TestCase): ) def test_closest_function_invalid_state(self): + """.""" self.hass.states.set('test_domain.closest_home', 'happy', { 'latitude': self.hass.config.latitude + 0.1, 'longitude': self.hass.config.longitude + 0.1, @@ -458,6 +494,7 @@ class TestUtilTemplate(unittest.TestCase): self.hass, '{{ closest(%s, states) }}' % state)) def test_closest_function_state_with_invalid_location(self): + """.""" self.hass.states.set('test_domain.closest_home', 'happy', { 'latitude': 'invalid latitude', 'longitude': self.hass.config.longitude + 0.1, @@ -471,6 +508,7 @@ class TestUtilTemplate(unittest.TestCase): 'states) }}')) def test_closest_function_invalid_coordinates(self): + """.""" self.hass.states.set('test_domain.closest_home', 'happy', { 'latitude': self.hass.config.latitude + 0.1, 'longitude': self.hass.config.longitude + 0.1, @@ -482,5 +520,6 @@ class TestUtilTemplate(unittest.TestCase): '{{ closest("invalid", "coord", states) }}')) def test_closest_function_no_location_states(self): + """.""" self.assertEqual('None', template.render(self.hass, '{{ closest(states) }}')) diff --git a/tests/test_bootstrap.py b/tests/test_bootstrap.py index 5113301dee6..fd2265db76e 100644 --- a/tests/test_bootstrap.py +++ b/tests/test_bootstrap.py @@ -1,9 +1,4 @@ -""" -tests.test_bootstrap -~~~~~~~~~~~~~~~~~~~~ - -Tests bootstrap. -""" +"""Test the bootstrapping.""" # pylint: disable=too-many-public-methods,protected-access import os import tempfile @@ -19,15 +14,18 @@ from tests.common import get_test_home_assistant, MockModule class TestBootstrap(unittest.TestCase): - """ Test the bootstrap utils. """ + """Test the bootstrap utils.""" def setUp(self): + """Setup the test.""" self.orig_timezone = dt_util.DEFAULT_TIME_ZONE def tearDown(self): + """Clean up.""" dt_util.DEFAULT_TIME_ZONE = self.orig_timezone def test_from_config_file(self): + """Test with configuration file.""" components = ['browser', 'conversation', 'script'] with tempfile.NamedTemporaryFile() as fp: for comp in components: @@ -42,6 +40,7 @@ class TestBootstrap(unittest.TestCase): sorted(hass.config.components)) def test_remove_lib_on_upgrade(self): + """Test removal of library on upgrade.""" with tempfile.TemporaryDirectory() as config_dir: version_path = os.path.join(config_dir, '.HA_VERSION') lib_dir = os.path.join(config_dir, 'lib') @@ -64,6 +63,7 @@ class TestBootstrap(unittest.TestCase): hass.stop() def test_not_remove_lib_if_not_upgrade(self): + """Test removal of library with no upgrade.""" with tempfile.TemporaryDirectory() as config_dir: version_path = os.path.join(config_dir, '.HA_VERSION') lib_dir = os.path.join(config_dir, 'lib') @@ -86,7 +86,7 @@ class TestBootstrap(unittest.TestCase): hass.stop() def test_entity_customization(self): - """ Test entity customization through config """ + """Test entity customization through configuration.""" config = {CONF_LATITUDE: 50, CONF_LONGITUDE: 50, CONF_NAME: 'Test', @@ -107,11 +107,12 @@ class TestBootstrap(unittest.TestCase): hass.stop() def test_handle_setup_circular_dependency(self): + """Test the setup of circular dependencies.""" hass = get_test_home_assistant() - loader.set_component('comp_b', MockModule('comp_b', ['comp_a'])) def setup_a(hass, config): + """Setup the another component.""" bootstrap.setup_component(hass, 'comp_b') return True diff --git a/tests/test_config.py b/tests/test_config.py index 87f0c4e5b03..91c909422f3 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,9 +1,4 @@ -""" -tests.test_config -~~~~~~~~~~~~~~~~~ - -Tests config utils. -""" +"""Test config utils.""" # pylint: disable=too-many-public-methods,protected-access import unittest import unittest.mock as mock @@ -22,46 +17,44 @@ YAML_PATH = os.path.join(CONFIG_DIR, config_util.YAML_CONFIG_FILE) def create_file(path): - """ Creates an empty file. """ + """Create an empty file.""" with open(path, 'w'): pass class TestConfig(unittest.TestCase): - """ Test the config utils. """ + """Test the configutils. """ def tearDown(self): # pylint: disable=invalid-name - """ Clean up. """ + """Clean up.""" if os.path.isfile(YAML_PATH): os.remove(YAML_PATH) def test_create_default_config(self): - """ Test creationg of default config. """ - + """Test creation of default config.""" config_util.create_default_config(CONFIG_DIR, False) self.assertTrue(os.path.isfile(YAML_PATH)) def test_find_config_file_yaml(self): - """ Test if it finds a YAML config file. """ - + """Test if it finds a YAML config file.""" create_file(YAML_PATH) self.assertEqual(YAML_PATH, config_util.find_config_file(CONFIG_DIR)) @mock.patch('builtins.print') def test_ensure_config_exists_creates_config(self, mock_print): - """ Test that calling ensure_config_exists creates a new config file if - none exists. """ + """Test that calling ensure_config_exists. + If not creates a new config file. + """ config_util.ensure_config_exists(CONFIG_DIR, False) self.assertTrue(os.path.isfile(YAML_PATH)) self.assertTrue(mock_print.called) def test_ensure_config_exists_uses_existing_config(self): - """ Test that calling ensure_config_exists uses existing config. """ - + """Test that calling ensure_config_exists uses existing config.""" create_file(YAML_PATH) config_util.ensure_config_exists(CONFIG_DIR, False) @@ -79,7 +72,7 @@ class TestConfig(unittest.TestCase): config_util.load_yaml_config_file(YAML_PATH), dict) def test_load_yaml_config_raises_error_if_not_dict(self): - """ Test error raised when YAML file is not a dict. """ + """Test error raised when YAML file is not a dict.""" with open(YAML_PATH, 'w') as f: f.write('5') @@ -87,7 +80,7 @@ class TestConfig(unittest.TestCase): config_util.load_yaml_config_file(YAML_PATH) def test_load_yaml_config_raises_error_if_malformed_yaml(self): - """ Test error raised if invalid YAML. """ + """Test error raised if invalid YAML.""" with open(YAML_PATH, 'w') as f: f.write(':') @@ -95,7 +88,7 @@ class TestConfig(unittest.TestCase): config_util.load_yaml_config_file(YAML_PATH) def test_load_yaml_config_raises_error_if_unsafe_yaml(self): - """ Test error raised if unsafe YAML. """ + """Test error raised if unsafe YAML.""" with open(YAML_PATH, 'w') as f: f.write('hello: !!python/object/apply:os.system') @@ -103,6 +96,7 @@ class TestConfig(unittest.TestCase): config_util.load_yaml_config_file(YAML_PATH) def test_load_yaml_config_preserves_key_order(self): + """Test removal of library.""" with open(YAML_PATH, 'w') as f: f.write('hello: 0\n') f.write('world: 1\n') @@ -113,7 +107,7 @@ class TestConfig(unittest.TestCase): @mock.patch('builtins.print') def test_create_default_config_detect_location(self, mock_print): - """ Test that detect location sets the correct config keys. """ + """Test that detect location sets the correct config keys.""" config_util.ensure_config_exists(CONFIG_DIR) config = config_util.load_yaml_config_file(YAML_PATH) @@ -136,8 +130,9 @@ class TestConfig(unittest.TestCase): @mock.patch('builtins.print') def test_create_default_config_returns_none_if_write_error(self, mock_print): - """ - Test that writing default config to non existing folder returns None. + """Test the writing of a default configuration. + + Non existing folder returns None. """ self.assertIsNone( config_util.create_default_config( diff --git a/tests/test_core.py b/tests/test_core.py index 61bfddf7548..ca3517666b3 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -1,9 +1,4 @@ -""" -tests.test_core -~~~~~~~~~~~~~~~ - -Provides tests to verify that Home Assistant core works. -""" +"""Test to verify that Home Assistant core works.""" # pylint: disable=protected-access,too-many-public-methods # pylint: disable=too-few-public-methods import os @@ -31,18 +26,16 @@ PST = pytz.timezone('America/Los_Angeles') class TestHomeAssistant(unittest.TestCase): - """ - Tests the Home Assistant core classes. - """ + """Test the Home Assistant core classes.""" def setUp(self): # pylint: disable=invalid-name - """ things to be run when tests are started. """ + """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.states.set("light.Bowl", "on") self.hass.states.set("switch.AC", "off") def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop down stuff we started.""" try: self.hass.stop() except HomeAssistantError: @@ -50,6 +43,7 @@ class TestHomeAssistant(unittest.TestCase): pass def test_start(self): + """Start the test.""" calls = [] self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, lambda event: calls.append(1)) @@ -59,7 +53,7 @@ class TestHomeAssistant(unittest.TestCase): # @patch('homeassistant.core.time.sleep') def test_block_till_stoped(self): - """ Test if we can block till stop service is called. """ + """Test if we can block till stop service is called.""" with patch('time.sleep'): blocking_thread = threading.Thread( target=self.hass.block_till_stopped) @@ -82,11 +76,13 @@ class TestHomeAssistant(unittest.TestCase): self.assertFalse(blocking_thread.is_alive()) def test_stopping_with_sigterm(self): + """Test for stopping with sigterm.""" calls = [] self.hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, lambda event: calls.append(1)) def send_sigterm(length): + """Send sigterm.""" os.kill(os.getpid(), signal.SIGTERM) with patch('homeassistant.core.time.sleep', send_sigterm): @@ -96,8 +92,10 @@ class TestHomeAssistant(unittest.TestCase): class TestEvent(unittest.TestCase): - """ Test Event class. """ + """A Test Event class.""" + def test_eq(self): + """Test events.""" now = dt_util.utcnow() data = {'some': 'attr'} event1, event2 = [ @@ -108,7 +106,7 @@ class TestEvent(unittest.TestCase): self.assertEqual(event1, event2) def test_repr(self): - """ Test that repr method works. #MoreCoverage """ + """Test that repr method works. #MoreCoverage""" self.assertEqual( "", str(ha.Event("TestEvent"))) @@ -120,6 +118,7 @@ class TestEvent(unittest.TestCase): ha.EventOrigin.remote))) def test_as_dict(self): + """Test as dictionary.""" event_type = 'some_type' now = dt_util.utcnow() data = {'some': 'attr'} @@ -135,19 +134,19 @@ class TestEvent(unittest.TestCase): class TestEventBus(unittest.TestCase): - """ Test EventBus methods. """ + """Test EventBus methods.""" def setUp(self): # pylint: disable=invalid-name - """ things to be run when tests are started. """ + """Setup things to be run when tests are started.""" self.bus = ha.EventBus(ha.create_worker_pool(0)) self.bus.listen('test_event', lambda x: len) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop down stuff we started.""" self.bus._pool.stop() def test_add_remove_listener(self): - """ Test remove_listener method. """ + """Test remove_listener method.""" self.bus._pool.add_worker() old_count = len(self.bus.listeners) @@ -168,7 +167,7 @@ class TestEventBus(unittest.TestCase): self.bus.remove_listener('test', listener) def test_listen_once_event(self): - """ Test listen_once_event method. """ + """Test listen_once_event method.""" runs = [] self.bus.listen_once('test_event', lambda x: runs.append(1)) @@ -183,43 +182,49 @@ class TestEventBus(unittest.TestCase): class TestState(unittest.TestCase): - """ Test EventBus methods. """ + """Test State methods.""" def test_init(self): - """ Test state.init """ + """Test state.init.""" self.assertRaises( InvalidEntityFormatError, ha.State, 'invalid_entity_format', 'test_state') def test_domain(self): + """Test domain.""" state = ha.State('some_domain.hello', 'world') self.assertEqual('some_domain', state.domain) def test_object_id(self): + """Test object ID.""" state = ha.State('domain.hello', 'world') self.assertEqual('hello', state.object_id) def test_name_if_no_friendly_name_attr(self): + """Test if there is no friendly name.""" state = ha.State('domain.hello_world', 'world') self.assertEqual('hello world', state.name) def test_name_if_friendly_name_attr(self): + """Test if there is a friendly name.""" name = 'Some Unique Name' state = ha.State('domain.hello_world', 'world', {ATTR_FRIENDLY_NAME: name}) self.assertEqual(name, state.name) def test_dict_conversion(self): + """Test conversion of dict.""" state = ha.State('domain.hello', 'world', {'some': 'attr'}) self.assertEqual(state, ha.State.from_dict(state.as_dict())) def test_dict_conversion_with_wrong_data(self): + """Test conversion with wrong data.""" self.assertIsNone(ha.State.from_dict(None)) self.assertIsNone(ha.State.from_dict({'state': 'yes'})) self.assertIsNone(ha.State.from_dict({'entity_id': 'yes'})) def test_repr(self): - """ Test state.repr """ + """Test state.repr.""" self.assertEqual("", str(ha.State( "happy.happy", "on", @@ -232,10 +237,10 @@ class TestState(unittest.TestCase): class TestStateMachine(unittest.TestCase): - """ Test EventBus methods. """ + """Test State machine methods. """ def setUp(self): # pylint: disable=invalid-name - """ things to be run when tests are started. """ + """Setup things to be run when tests are started.""" self.pool = ha.create_worker_pool(0) self.bus = ha.EventBus(self.pool) self.states = ha.StateMachine(self.bus) @@ -243,17 +248,17 @@ class TestStateMachine(unittest.TestCase): self.states.set("switch.AC", "off") def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop down stuff we started.""" self.pool.stop() def test_is_state(self): - """ Test is_state method. """ + """Test is_state method.""" self.assertTrue(self.states.is_state('light.Bowl', 'on')) self.assertFalse(self.states.is_state('light.Bowl', 'off')) self.assertFalse(self.states.is_state('light.Non_existing', 'on')) def test_is_state_attr(self): - """ Test is_state_attr method. """ + """Test is_state_attr method.""" self.states.set("light.Bowl", "on", {"brightness": 100}) self.assertTrue( self.states.is_state_attr('light.Bowl', 'brightness', 100)) @@ -265,7 +270,7 @@ class TestStateMachine(unittest.TestCase): self.states.is_state_attr('light.Non_existing', 'brightness', 100)) def test_entity_ids(self): - """ Test get_entity_ids method. """ + """Test get_entity_ids method.""" ent_ids = self.states.entity_ids() self.assertEqual(2, len(ent_ids)) self.assertTrue('light.bowl' in ent_ids) @@ -276,11 +281,12 @@ class TestStateMachine(unittest.TestCase): self.assertTrue('light.bowl' in ent_ids) def test_all(self): + """Test everything.""" states = sorted(state.entity_id for state in self.states.all()) self.assertEqual(['light.bowl', 'switch.ac'], states) def test_remove(self): - """ Test remove method. """ + """Test remove method.""" self.pool.add_worker() events = [] self.bus.listen(EVENT_STATE_CHANGED, @@ -303,6 +309,7 @@ class TestStateMachine(unittest.TestCase): self.assertEqual(1, len(events)) def test_case_insensitivty(self): + """Test insensitivty.""" self.pool.add_worker() runs = [] @@ -315,6 +322,7 @@ class TestStateMachine(unittest.TestCase): self.assertEqual(1, len(runs)) def test_last_changed_not_updated_on_same_state(self): + """Test to not update the existing, same state.""" state = self.states.get('light.Bowl') future = dt_util.utcnow() + timedelta(hours=10) @@ -327,9 +335,10 @@ class TestStateMachine(unittest.TestCase): class TestServiceCall(unittest.TestCase): - """ Test ServiceCall class. """ + """Test ServiceCall class.""" + def test_repr(self): - """ Test repr method. """ + """Test repr method.""" self.assertEqual( "", str(ha.ServiceCall('homeassistant', 'start'))) @@ -340,22 +349,22 @@ class TestServiceCall(unittest.TestCase): class TestServiceRegistry(unittest.TestCase): - """ Test EventBus methods. """ + """ Test ServicerRegistry methods. """ def setUp(self): # pylint: disable=invalid-name - """ things to be run when tests are started. """ + """Setup things to be run when tests are started.""" self.pool = ha.create_worker_pool(0) self.bus = ha.EventBus(self.pool) self.services = ha.ServiceRegistry(self.bus, self.pool) self.services.register("test_domain", "test_service", lambda x: None) def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop down stuff we started.""" if self.pool.worker_count: self.pool.stop() def test_has_service(self): - """ Test has_service method. """ + """Test has_service method.""" self.assertTrue( self.services.has_service("test_domain", "test_service")) self.assertFalse( @@ -364,12 +373,14 @@ class TestServiceRegistry(unittest.TestCase): self.services.has_service("non_existing", "test_service")) def test_services(self): + """Test services.""" expected = { 'test_domain': {'test_service': {'description': '', 'fields': {}}} } self.assertEqual(expected, self.services.services) def test_call_with_blocking_done_in_time(self): + """Test call with blocking.""" self.pool.add_worker() self.pool.add_worker() calls = [] @@ -381,6 +392,7 @@ class TestServiceRegistry(unittest.TestCase): self.assertEqual(1, len(calls)) def test_call_with_blocking_not_done_in_time(self): + """Test with blocking.""" calls = [] self.services.register("test_domain", "register_calls", lambda x: calls.append(1)) @@ -393,6 +405,7 @@ class TestServiceRegistry(unittest.TestCase): ha.SERVICE_CALL_LIMIT = orig_limit def test_call_non_existing_with_blocking(self): + """Test non-existing with blocking.""" self.pool.add_worker() self.pool.add_worker() orig_limit = ha.SERVICE_CALL_LIMIT @@ -403,26 +416,28 @@ class TestServiceRegistry(unittest.TestCase): class TestConfig(unittest.TestCase): + """Test configuration methods.""" + def setUp(self): # pylint: disable=invalid-name - """ things to be run when tests are started. """ + """Setup things to be run when tests are started. """ self.config = ha.Config() def test_config_dir_set_correct(self): - """ Test config dir set correct. """ + """Test config dir set correct.""" data_dir = os.getenv('APPDATA') if os.name == "nt" \ else os.path.expanduser('~') self.assertEqual(os.path.join(data_dir, ".homeassistant"), self.config.config_dir) def test_path_with_file(self): - """ Test get_config_path method. """ + """Test get_config_path method.""" data_dir = os.getenv('APPDATA') if os.name == "nt" \ else os.path.expanduser('~') self.assertEqual(os.path.join(data_dir, ".homeassistant", "test.conf"), self.config.path("test.conf")) def test_path_with_dir_and_file(self): - """ Test get_config_path method. """ + """Test get_config_path method.""" data_dir = os.getenv('APPDATA') if os.name == "nt" \ else os.path.expanduser('~') self.assertEqual( @@ -430,7 +445,7 @@ class TestConfig(unittest.TestCase): self.config.path("dir", "test.conf")) def test_temperature_not_convert_if_no_preference(self): - """ No unit conversion to happen if no preference. """ + """No unit conversion to happen if no preference.""" self.assertEqual( (25, TEMP_CELCIUS), self.config.temperature(25, TEMP_CELCIUS)) @@ -439,19 +454,20 @@ class TestConfig(unittest.TestCase): self.config.temperature(80, TEMP_FAHRENHEIT)) def test_temperature_not_convert_if_invalid_value(self): - """ No unit conversion to happen if no preference. """ + """No unit conversion to happen if no preference.""" self.config.temperature_unit = TEMP_FAHRENHEIT self.assertEqual( ('25a', TEMP_CELCIUS), self.config.temperature('25a', TEMP_CELCIUS)) def test_temperature_not_convert_if_invalid_unit(self): - """ No unit conversion to happen if no preference. """ + """No unit conversion to happen if no preference.""" self.assertEqual( (25, 'Invalid unit'), self.config.temperature(25, 'Invalid unit')) def test_temperature_to_convert_to_celcius(self): + """Test temperature conversion to celsius.""" self.config.temperature_unit = TEMP_CELCIUS self.assertEqual( @@ -462,6 +478,7 @@ class TestConfig(unittest.TestCase): self.config.temperature(80, TEMP_FAHRENHEIT)) def test_temperature_to_convert_to_fahrenheit(self): + """Test temperature conversion to fahrenheit.""" self.config.temperature_unit = TEMP_FAHRENHEIT self.assertEqual( @@ -472,6 +489,7 @@ class TestConfig(unittest.TestCase): self.config.temperature(80, TEMP_FAHRENHEIT)) def test_as_dict(self): + """Test as dict.""" expected = { 'latitude': None, 'longitude': None, @@ -486,7 +504,10 @@ class TestConfig(unittest.TestCase): class TestWorkerPool(unittest.TestCase): + """Test WorkerPool methods.""" + def test_exception_during_job(self): + """Test exception during a job.""" pool = ha.create_worker_pool(1) def malicious_job(_): diff --git a/tests/test_loader.py b/tests/test_loader.py index 7651cdee649..261dafdd187 100644 --- a/tests/test_loader.py +++ b/tests/test_loader.py @@ -1,9 +1,4 @@ -""" -tests.test_loader -~~~~~~~~~~~~~~~~~ - -Provides tests to verify that we can load components. -""" +"""Test to verify that we can load components.""" # pylint: disable=too-many-public-methods,protected-access import unittest @@ -14,28 +9,30 @@ from tests.common import get_test_home_assistant, MockModule class TestLoader(unittest.TestCase): - """ Test the loader module. """ + """Test the loader module.""" + def setUp(self): # pylint: disable=invalid-name + """Setup tests.""" self.hass = get_test_home_assistant() def tearDown(self): # pylint: disable=invalid-name - """ Stop down stuff we started. """ + """Stop everything that was started.""" self.hass.stop() def test_set_component(self): - """ Test if set_component works. """ + """Test if set_component works.""" loader.set_component('switch.test_set', http) self.assertEqual(http, loader.get_component('switch.test_set')) def test_get_component(self): - """ Test if get_component works. """ + """Test if get_component works.""" self.assertEqual(http, loader.get_component('http')) self.assertIsNotNone(loader.get_component('switch.test')) def test_load_order_component(self): - """ Test if we can get the proper load order of components. """ + """Test if we can get the proper load order of components.""" loader.set_component('mod1', MockModule('mod1')) loader.set_component('mod2', MockModule('mod2', ['mod1'])) loader.set_component('mod3', MockModule('mod3', ['mod2'])) @@ -57,6 +54,7 @@ class TestLoader(unittest.TestCase): self.assertEqual([], loader.load_order_component('mod1')) def test_load_order_components(self): + """Setup loading order of components.""" loader.set_component('mod1', MockModule('mod1', ['group'])) loader.set_component('mod2', MockModule('mod2', ['mod1', 'sun'])) loader.set_component('mod3', MockModule('mod3', ['mod2'])) diff --git a/tests/test_remote.py b/tests/test_remote.py index b49aea25244..19616f1ed6e 100644 --- a/tests/test_remote.py +++ b/tests/test_remote.py @@ -1,9 +1,4 @@ -""" -tests.remote -~~~~~~~~~~~~ - -Tests Home Assistant remote methods and classes. -""" +"""Test Home Assistant remote methods and classes.""" # pylint: disable=protected-access,too-many-public-methods import unittest @@ -28,12 +23,12 @@ hass, slave, master_api = None, None, None def _url(path=""): - """ Helper method to generate urls. """ + """Helper method to generate URLs.""" return HTTP_BASE_URL + path def setUpModule(): # pylint: disable=invalid-name - """ Initalizes a Home Assistant server and Slave instance. """ + """Initalization of a Home Assistant server and Slave instance.""" global hass, slave, master_api hass = get_test_home_assistant() @@ -63,20 +58,21 @@ def setUpModule(): # pylint: disable=invalid-name def tearDownModule(): # pylint: disable=invalid-name - """ Stops the Home Assistant server and slave. """ + """Stop the Home Assistant server and slave.""" slave.stop() hass.stop() class TestRemoteMethods(unittest.TestCase): - """ Test the homeassistant.remote module. """ + """Test the homeassistant.remote module.""" def tearDown(self): + """Stop everything that was started.""" slave.pool.block_till_done() hass.pool.block_till_done() def test_validate_api(self): - """ Test Python API validate_api. """ + """Test Python API validate_api.""" self.assertEqual(remote.APIStatus.OK, remote.validate_api(master_api)) self.assertEqual( @@ -88,7 +84,7 @@ class TestRemoteMethods(unittest.TestCase): remote.APIStatus.CANNOT_CONNECT, remote.validate_api(broken_api)) def test_get_event_listeners(self): - """ Test Python API get_event_listeners. """ + """Test Python API get_event_listeners.""" local_data = hass.bus.listeners remote_data = remote.get_event_listeners(master_api) @@ -101,27 +97,23 @@ class TestRemoteMethods(unittest.TestCase): self.assertEqual({}, remote.get_event_listeners(broken_api)) def test_fire_event(self): - """ Test Python API fire_event. """ + """Test Python API fire_event.""" test_value = [] def listener(event): - """ Helper method that will verify our event got called. """ + """Helper method that will verify our event got called.""" test_value.append(1) hass.bus.listen_once("test.event_no_data", listener) - remote.fire_event(master_api, "test.event_no_data") - hass.pool.block_till_done() - self.assertEqual(1, len(test_value)) # Should not trigger any exception remote.fire_event(broken_api, "test.event_no_data") def test_get_state(self): - """ Test Python API get_state. """ - + """Test Python API get_state.""" self.assertEqual( hass.states.get('test.test'), remote.get_state(master_api, 'test.test')) @@ -129,13 +121,12 @@ class TestRemoteMethods(unittest.TestCase): self.assertEqual(None, remote.get_state(broken_api, 'test.test')) def test_get_states(self): - """ Test Python API get_state_entity_ids. """ - + """Test Python API get_state_entity_ids.""" self.assertEqual(hass.states.all(), remote.get_states(master_api)) self.assertEqual([], remote.get_states(broken_api)) def test_remove_state(self): - """ Test Python API set_state. """ + """Test Python API set_state.""" hass.states.set('test.remove_state', 'set_test') self.assertIn('test.remove_state', hass.states.entity_ids()) @@ -143,7 +134,7 @@ class TestRemoteMethods(unittest.TestCase): self.assertNotIn('test.remove_state', hass.states.entity_ids()) def test_set_state(self): - """ Test Python API set_state. """ + """Test Python API set_state.""" remote.set_state(master_api, 'test.test', 'set_test') state = hass.states.get('test.test') @@ -154,8 +145,7 @@ class TestRemoteMethods(unittest.TestCase): self.assertFalse(remote.set_state(broken_api, 'test.test', 'set_test')) def test_is_state(self): - """ Test Python API is_state. """ - + """Test Python API is_state.""" self.assertTrue( remote.is_state(master_api, 'test.test', hass.states.get('test.test').state)) @@ -165,8 +155,7 @@ class TestRemoteMethods(unittest.TestCase): hass.states.get('test.test').state)) def test_get_services(self): - """ Test Python API get_services. """ - + """Test Python API get_services.""" local_services = hass.services.services for serv_domain in remote.get_services(master_api): @@ -177,11 +166,11 @@ class TestRemoteMethods(unittest.TestCase): self.assertEqual({}, remote.get_services(broken_api)) def test_call_service(self): - """ Test Python API services.call. """ + """Test Python API services.call.""" test_value = [] def listener(service_call): - """ Helper method that will verify that our service got called. """ + """Helper method that will verify that our service got called.""" test_value.append(1) hass.services.register("test_domain", "test_service", listener) @@ -196,7 +185,7 @@ class TestRemoteMethods(unittest.TestCase): remote.call_service(broken_api, "test_domain", "test_service") def test_json_encoder(self): - """ Test the JSON Encoder. """ + """Test the JSON Encoder.""" ha_json_enc = remote.JSONEncoder() state = hass.states.get('test.test') @@ -207,14 +196,15 @@ class TestRemoteMethods(unittest.TestCase): class TestRemoteClasses(unittest.TestCase): - """ Test the homeassistant.remote module. """ + """Test the homeassistant.remote module.""" def tearDown(self): + """Stop everything that was started.""" slave.pool.block_till_done() hass.pool.block_till_done() def test_home_assistant_init(self): - """ Test HomeAssistant init. """ + """Test HomeAssistant init.""" # Wrong password self.assertRaises( ha.HomeAssistantError, remote.HomeAssistant, @@ -231,7 +221,7 @@ class TestRemoteClasses(unittest.TestCase): sorted(slave.states.all())) def test_statemachine_set(self): - """ Tests if setting the state on a slave is recorded. """ + """Test if setting the state on a slave is recorded.""" slave.states.set("remote.test", "remote.statemachine test") # Wait till slave tells master @@ -243,6 +233,7 @@ class TestRemoteClasses(unittest.TestCase): slave.states.get("remote.test").state) def test_statemachine_remove_from_master(self): + """Remove statemachine from master.""" hass.states.set("remote.master_remove", "remove me!") hass.pool.block_till_done() @@ -254,6 +245,7 @@ class TestRemoteClasses(unittest.TestCase): self.assertNotIn('remote.master_remove', slave.states.entity_ids()) def test_statemachine_remove_from_slave(self): + """Remove statemachine from slave.""" hass.states.set("remote.slave_remove", "remove me!") hass.pool.block_till_done() @@ -266,15 +258,14 @@ class TestRemoteClasses(unittest.TestCase): self.assertNotIn('remote.slave_remove', slave.states.entity_ids()) def test_eventbus_fire(self): - """ Test if events fired from the eventbus get fired. """ + """Test if events fired from the eventbus get fired.""" test_value = [] def listener(event): - """ Helper method that will verify our event got called. """ + """Helper method that will verify our event got called.""" test_value.append(1) slave.bus.listen_once("test.event_no_data", listener) - slave.bus.fire("test.event_no_data") # Wait till slave tells master diff --git a/tests/util/test_color.py b/tests/util/test_color.py index f74a074bbe6..c5a4d40c81a 100644 --- a/tests/util/test_color.py +++ b/tests/util/test_color.py @@ -1,4 +1,4 @@ -"""Tests Home Assistant color util methods.""" +"""Test Home Assistant color util methods.""" import unittest import homeassistant.util.color as color_util diff --git a/tests/util/test_dt.py b/tests/util/test_dt.py index 78e77d8f14e..0b6a51c9d76 100644 --- a/tests/util/test_dt.py +++ b/tests/util/test_dt.py @@ -1,9 +1,4 @@ -""" -tests.util.test_dt -~~~~~~~~~~~~~~~~~~ - -Tests Home Assistant date util methods. -""" +"""Test Home Assistant date util methods.""" # pylint: disable=too-many-public-methods import unittest from datetime import datetime, timedelta @@ -14,29 +9,31 @@ TEST_TIME_ZONE = 'America/Los_Angeles' class TestDateUtil(unittest.TestCase): - """ Tests util date methods. """ + """Test util date methods.""" def setUp(self): + """Setup the tests.""" self.orig_default_time_zone = dt_util.DEFAULT_TIME_ZONE def tearDown(self): + """Stop everything that was started.""" dt_util.set_default_time_zone(self.orig_default_time_zone) def test_get_time_zone_retrieves_valid_time_zone(self): - """ Test getting a time zone. """ + """Test getting a time zone.""" time_zone = dt_util.get_time_zone(TEST_TIME_ZONE) self.assertIsNotNone(time_zone) self.assertEqual(TEST_TIME_ZONE, time_zone.zone) def test_get_time_zone_returns_none_for_garbage_time_zone(self): - """ Test getting a non existing time zone. """ + """Test getting a non existing time zone.""" time_zone = dt_util.get_time_zone("Non existing time zone") self.assertIsNone(time_zone) def test_set_default_time_zone(self): - """ Test setting default time zone. """ + """Test setting default time zone.""" time_zone = dt_util.get_time_zone(TEST_TIME_ZONE) dt_util.set_default_time_zone(time_zone) @@ -45,14 +42,14 @@ class TestDateUtil(unittest.TestCase): self.assertEqual(time_zone.zone, dt_util.now().tzinfo.zone) def test_utcnow(self): - """ Test the UTC now method. """ + """Test the UTC now method.""" self.assertAlmostEqual( dt_util.utcnow().replace(tzinfo=None), datetime.utcnow(), delta=timedelta(seconds=1)) def test_now(self): - """ Test the now method. """ + """Test the now method.""" dt_util.set_default_time_zone(dt_util.get_time_zone(TEST_TIME_ZONE)) self.assertAlmostEqual( @@ -61,39 +58,41 @@ class TestDateUtil(unittest.TestCase): delta=timedelta(seconds=1)) def test_as_utc_with_naive_object(self): + """Test the now method.""" utcnow = datetime.utcnow() self.assertEqual(utcnow, dt_util.as_utc(utcnow).replace(tzinfo=None)) def test_as_utc_with_utc_object(self): + """Test UTC time with UTC object.""" utcnow = dt_util.utcnow() self.assertEqual(utcnow, dt_util.as_utc(utcnow)) def test_as_utc_with_local_object(self): + """Test the UTC time with local object.""" dt_util.set_default_time_zone(dt_util.get_time_zone(TEST_TIME_ZONE)) - localnow = dt_util.now() - utcnow = dt_util.as_utc(localnow) self.assertEqual(localnow, utcnow) self.assertNotEqual(localnow.tzinfo, utcnow.tzinfo) def test_as_local_with_naive_object(self): + """Test local time with native object.""" now = dt_util.now() - self.assertAlmostEqual( now, dt_util.as_local(datetime.utcnow()), delta=timedelta(seconds=1)) def test_as_local_with_local_object(self): + """Test local with local object.""" now = dt_util.now() - self.assertEqual(now, now) def test_as_local_with_utc_object(self): + """Test local time with UTC object.""" dt_util.set_default_time_zone(dt_util.get_time_zone(TEST_TIME_ZONE)) utcnow = dt_util.utcnow() @@ -103,34 +102,35 @@ class TestDateUtil(unittest.TestCase): self.assertNotEqual(localnow.tzinfo, utcnow.tzinfo) def test_utc_from_timestamp(self): - """ Test utc_from_timestamp method. """ + """Test utc_from_timestamp method.""" self.assertEqual( datetime(1986, 7, 9, tzinfo=dt_util.UTC), dt_util.utc_from_timestamp(521251200)) def test_datetime_to_str(self): - """ Test datetime_to_str. """ + """Test datetime_to_str.""" self.assertEqual( "12:00:00 09-07-1986", dt_util.datetime_to_str(datetime(1986, 7, 9, 12, 0, 0))) def test_datetime_to_local_str(self): - """ Test datetime_to_local_str. """ + """Test datetime_to_local_str.""" self.assertEqual( dt_util.datetime_to_str(dt_util.now()), dt_util.datetime_to_local_str(dt_util.utcnow())) def test_str_to_datetime_converts_correctly(self): - """ Test str_to_datetime converts strings. """ + """Test str_to_datetime converts strings.""" self.assertEqual( datetime(1986, 7, 9, 12, 0, 0, tzinfo=dt_util.UTC), dt_util.str_to_datetime("12:00:00 09-07-1986")) def test_str_to_datetime_returns_none_for_incorrect_format(self): - """ Test str_to_datetime returns None if incorrect format. """ + """Test str_to_datetime returns None if incorrect format.""" self.assertIsNone(dt_util.str_to_datetime("not a datetime string")) def test_strip_microseconds(self): + """Test the now method.""" test_time = datetime(2015, 1, 1, microsecond=5000) self.assertNotEqual(0, test_time.microsecond) diff --git a/tests/util/test_init.py b/tests/util/test_init.py index abe12a0af1b..e60e32cf4a1 100644 --- a/tests/util/test_init.py +++ b/tests/util/test_init.py @@ -1,9 +1,4 @@ -""" -tests.util.test_init -~~~~~~~~~~~~~~~~~~~~ - -Tests Home Assistant util methods. -""" +"""Test Home Assistant util methods.""" # pylint: disable=too-many-public-methods import unittest from unittest.mock import patch @@ -14,9 +9,10 @@ import homeassistant.util.dt as dt_util class TestUtil(unittest.TestCase): - """ Tests util methods. """ + """Test util methods.""" + def test_sanitize_filename(self): - """ Test sanitize_filename. """ + """Test sanitize_filename.""" self.assertEqual("test", util.sanitize_filename("test")) self.assertEqual("test", util.sanitize_filename("/test")) self.assertEqual("test", util.sanitize_filename("..test")) @@ -24,20 +20,20 @@ class TestUtil(unittest.TestCase): self.assertEqual("test", util.sanitize_filename("\\../test")) def test_sanitize_path(self): - """ Test sanitize_path. """ + """Test sanitize_path.""" self.assertEqual("test/path", util.sanitize_path("test/path")) self.assertEqual("test/path", util.sanitize_path("~test/path")) self.assertEqual("//test/path", util.sanitize_path("~/../test/path")) def test_slugify(self): - """ Test slugify. """ + """Test slugify.""" self.assertEqual("test", util.slugify("T-!@#$!#@$!$est")) self.assertEqual("test_more", util.slugify("Test More")) self.assertEqual("test_more", util.slugify("Test_(More)")) def test_repr_helper(self): - """ Test repr_helper. """ + """Test repr_helper.""" self.assertEqual("A", util.repr_helper("A")) self.assertEqual("5", util.repr_helper(5)) self.assertEqual("True", util.repr_helper(True)) @@ -47,7 +43,7 @@ class TestUtil(unittest.TestCase): util.repr_helper(datetime(1986, 7, 9, 12, 0, 0))) def test_convert(self): - """ Test convert. """ + """Test convert.""" self.assertEqual(5, util.convert("5", int)) self.assertEqual(5.0, util.convert("5", float)) self.assertEqual(True, util.convert("True", bool)) @@ -56,7 +52,7 @@ class TestUtil(unittest.TestCase): self.assertEqual(1, util.convert(object, int, 1)) def test_ensure_unique_string(self): - """ Test ensure_unique_string. """ + """Test ensure_unique_string.""" self.assertEqual( "Beer_3", util.ensure_unique_string("Beer", ["Beer", "Beer_2"])) @@ -65,10 +61,10 @@ class TestUtil(unittest.TestCase): util.ensure_unique_string("Beer", ["Wine", "Soda"])) def test_ordered_enum(self): - """ Test the ordered enum class. """ + """Test the ordered enum class.""" class TestEnum(util.OrderedEnum): - """ Test enum that can be ordered. """ + """Test enum that can be ordered.""" FIRST = 1 SECOND = 2 THIRD = 3 @@ -104,6 +100,7 @@ class TestUtil(unittest.TestCase): lambda x, y: x >= y, TestEnum.FIRST, 1) def test_ordered_set(self): + """Test ordering of set.""" set1 = util.OrderedSet([1, 2, 3, 4]) set2 = util.OrderedSet([3, 4, 5]) @@ -164,7 +161,7 @@ class TestUtil(unittest.TestCase): self.assertEqual([2, 3, 1, 5, 6], set1) def test_throttle(self): - """ Test the add cooldown decorator. """ + """Test the add cooldown decorator.""" calls1 = [] calls2 = [] @@ -216,21 +213,27 @@ class TestUtil(unittest.TestCase): self.assertEqual(2, len(calls2)) def test_throttle_per_instance(self): - """ Test that the throttle method is done per instance of a class. """ + """Test that the throttle method is done per instance of a class.""" class Tester(object): + """A tester class for the throttle.""" + @util.Throttle(timedelta(seconds=1)) def hello(self): + """Test the throttle.""" return True self.assertTrue(Tester().hello()) self.assertTrue(Tester().hello()) def test_throttle_on_method(self): - """ Test that throttle works when wrapping a method. """ + """Test that throttle works when wrapping a method.""" class Tester(object): + """A tester class for the throttle.""" + def hello(self): + """Test the throttle.""" return True tester = Tester() @@ -240,15 +243,19 @@ class TestUtil(unittest.TestCase): self.assertIsNone(throttled()) def test_throttle_on_two_method(self): - """ Test that throttle works when wrapping two methods. """ + """Test that throttle works when wrapping two methods.""" class Tester(object): + """A test class for the throttle.""" + @util.Throttle(timedelta(seconds=1)) def hello(self): + """Test the throttle.""" return True @util.Throttle(timedelta(seconds=1)) def goodbye(self): + """Test the throttle.""" return True tester = Tester() diff --git a/tests/util/test_package.py b/tests/util/test_package.py index f17eb681c08..840fe3d0ff8 100644 --- a/tests/util/test_package.py +++ b/tests/util/test_package.py @@ -1,9 +1,4 @@ -""" -tests.util.test_packages -~~~~~~~~~~~~~~~~~~~~~~~~ - -Tests Home Assistant package util methods. -""" +"""Test Home Assistant package util methods.""" import os import tempfile import unittest @@ -21,26 +16,26 @@ TEST_ZIP_REQ = 'file://{}#{}' \ class TestPackageUtil(unittest.TestCase): - """ Tests for homeassistant.util.package module. """ + """Test for homeassistant.util.package module.""" def setUp(self): - """ Create local library for testing. """ + """Create local library for testing.""" self.tmp_dir = tempfile.TemporaryDirectory() self.lib_dir = os.path.join(self.tmp_dir.name, 'lib') def tearDown(self): - """ Remove local library. """ + """Stop everything that was started.""" self.tmp_dir.cleanup() def test_install_existing_package(self): - """ Test an install attempt on an existing package. """ + """Test an install attempt on an existing package.""" self.assertTrue(package.check_package_exists( TEST_EXIST_REQ, self.lib_dir)) self.assertTrue(package.install_package(TEST_EXIST_REQ)) def test_install_package_zip(self): - """ Test an install attempt from a zip path. """ + """Test an install attempt from a zip path.""" self.assertFalse(package.check_package_exists( TEST_ZIP_REQ, self.lib_dir)) self.assertFalse(package.check_package_exists(