Fix PEP257 issues

This commit is contained in:
Fabian Affolter 2016-03-09 11:15:04 +01:00
parent 986c9c55bf
commit f22a40c3e8
22 changed files with 95 additions and 79 deletions

View File

@ -44,6 +44,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
# pylint: disable=too-many-arguments
class CommandBinarySensor(BinarySensorDevice):
"""Represent a command line binary sensor."""
def __init__(self, hass, data, name, payload_on,
payload_off, value_template):
"""Initialize the Command line binary sensor."""

View File

@ -33,7 +33,6 @@ DEVICE_MAPPINGS = {
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Z-Wave platform for sensors."""
if discovery_info is None or NETWORK is None:
return
@ -63,9 +62,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class ZWaveBinarySensor(BinarySensorDevice, ZWaveDeviceEntity):
"""Represents a binary sensor within Z-Wave."""
"""Representation of a binary sensor within Z-Wave."""
def __init__(self, value, sensor_class):
"""Initialize the sensor."""
self._sensor_type = sensor_class
# pylint: disable=import-error
from openzwave.network import ZWaveNetwork
@ -98,12 +98,10 @@ class ZWaveBinarySensor(BinarySensorDevice, ZWaveDeviceEntity):
class ZWaveTriggerSensor(ZWaveBinarySensor):
"""
Represents a stateless sensor which triggers events just 'On'
within Z-Wave.
"""
"""Representation of a stateless sensor within Z-Wave."""
def __init__(self, sensor_value, sensor_class, hass, re_arm_sec=60):
"""Initialize the sensor."""
super(ZWaveTriggerSensor, self).__init__(sensor_value, sensor_class)
self._hass = hass
self.re_arm_sec = re_arm_sec

View File

@ -25,7 +25,7 @@ _LOGGER = logging.getLogger(__name__)
def get_scanner(hass, config):
"""Validate the configuration and return a TP-Link scanner. """
"""Validate the configuration and return a TP-Link scanner."""
if not validate_config(config,
{DOMAIN: [CONF_HOST, CONF_USERNAME, CONF_PASSWORD]},
_LOGGER):

View File

@ -1,9 +1,4 @@
"""
homeassistant.components.frontend
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides a frontend for Home Assistant.
"""
"""Handle the frontend for Home Assistant."""
import re
import os
import logging
@ -32,7 +27,7 @@ _FINGERPRINT = re.compile(r'^(\w+)-[a-z0-9]{32}\.(\w+)$', re.IGNORECASE)
def setup(hass, config):
""" Setup serving the frontend. """
"""Setup serving the frontend."""
for url in FRONTEND_URLS:
hass.http.register_path('GET', url, _handle_get_root, False)
@ -58,7 +53,7 @@ def setup(hass, config):
def _handle_get_api_bootstrap(handler, path_match, data):
""" Returns all data needed to bootstrap Home Assistant. """
"""Return all data needed to bootstrap Home Assistant."""
hass = handler.server.hass
handler.write_json({
@ -70,7 +65,7 @@ def _handle_get_api_bootstrap(handler, path_match, data):
def _handle_get_root(handler, path_match, data):
""" Renders the frontend. """
"""Render the frontend."""
handler.send_response(HTTP_OK)
handler.send_header('Content-type', 'text/html; charset=utf-8')
handler.end_headers()
@ -95,7 +90,7 @@ def _handle_get_root(handler, path_match, data):
def _handle_get_service_worker(handler, path_match, data):
""" Returns service worker for the frontend. """
"""Return service worker for the frontend."""
if handler.server.development:
sw_path = "home-assistant-polymer/build/service_worker.js"
else:
@ -106,7 +101,7 @@ def _handle_get_service_worker(handler, path_match, data):
def _handle_get_static(handler, path_match, data):
""" Returns a static file for the frontend. """
"""Return a static file for the frontend."""
req_file = util.sanitize_path(path_match.group('file'))
# Strip md5 hash out
@ -120,9 +115,7 @@ def _handle_get_static(handler, path_match, data):
def _handle_get_local(handler, path_match, data):
"""
Returns a static file from the hass.config.path/www for the frontend.
"""
"""Return a static file from the hass.config.path/www for the frontend."""
req_file = util.sanitize_path(path_match.group('file'))
path = handler.server.hass.config.path('www', req_file)

View File

@ -1,2 +1,2 @@
""" DO NOT MODIFY. Auto-generated by update_mdi script """
"""DO NOT MODIFY. Auto-generated by update_mdi script."""
VERSION = "2f4adc5d3ad6d2f73bf69ed29b7594fd"

View File

@ -1,2 +1,2 @@
""" DO NOT MODIFY. Auto-generated by build_frontend script """
"""DO NOT MODIFY. Auto-generated by build_frontend script."""
VERSION = "625d9bc6f119ee8f815b30104b70cb43"

View File

@ -1,12 +1,9 @@
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Gets powerview scenes from a powerview hub
defined by a Hunter Douglas powerview app.
Support for Powerview scenes from a Powerview hub.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/scene/
"""
import logging
from homeassistant.components.scene import Scene
@ -21,7 +18,7 @@ HUB_ADDRESS = 'address'
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""sets up the powerview scenes stored in a powerview hub"""
"""Setup the powerview scenes stored in a Powerview hub."""
import powerview
hub_address = config.get(HUB_ADDRESS)
@ -41,15 +38,17 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class PowerViewScene(Scene):
""" A scene is a group of entities and the states we want them to be. """
"""Representation of a Powerview scene."""
def __init__(self, hass, scene_data, room_data, pv_instance):
"""Initialize the scene."""
self.pv_instance = pv_instance
self.hass = hass
self.scene_data = scene_data
self._sync_room_data(room_data)
def _sync_room_data(self, room_data):
"""Sync the room data."""
room = next((room for room in room_data["roomData"]
if room["id"] == self.scene_data["roomId"]), None)
if room is not None:
@ -57,12 +56,14 @@ class PowerViewScene(Scene):
@property
def name(self):
"""Return the name of the scene."""
return self.scene_data["name"]
@property
def device_state_attributes(self):
"""Return the state attributes."""
return {"roomName": self.scene_data["roomName"]}
def activate(self):
""" Activates scene. Tries to get entities into requested state. """
"""Activate the scene. Tries to get entities into requested state."""
self.pv_instance.activate_scene(self.scene_data["id"])

View File

@ -256,6 +256,7 @@ def forgiving_float(value):
class TemplateEnvironment(ImmutableSandboxedEnvironment):
"""The Home Assistant template environment."""
def is_safe_callable(self, obj):
"""Test if callback is safe."""
return isinstance(obj, AllStates) or super().is_safe_callable(obj)

View File

@ -1,8 +1,5 @@
#!/usr/bin/env python3
"""
Generate an updated requirements_all.txt
"""
"""Generate an updated requirements_all.txt."""
import importlib
import os
import pkgutil
@ -17,7 +14,7 @@ COMMENT_REQUIREMENTS = [
def explore_module(package, explore_children):
""" Explore the modules. """
"""Explore the modules."""
module = importlib.import_module(package)
found = []
@ -35,7 +32,7 @@ def explore_module(package, explore_children):
def core_requirements():
""" Gather core requirements out of setup.py. """
"""Gather core requirements out of setup.py."""
with open('setup.py') as inp:
reqs_raw = re.search(
r'REQUIRES = \[(.*?)\]', inp.read(), re.S).group(1)
@ -43,12 +40,12 @@ def core_requirements():
def comment_requirement(req):
""" Some requirements don't install on all systems. """
"""Some requirements don't install on all systems."""
return any(ign in req for ign in COMMENT_REQUIREMENTS)
def gather_modules():
""" Collect the information and construct the output. """
"""Collect the information and construct the output."""
reqs = {}
errors = []
@ -95,19 +92,19 @@ def gather_modules():
def write_file(data):
""" Writes the modules to the requirements_all.txt. """
"""Write the modules to the requirements_all.txt."""
with open('requirements_all.txt', 'w+') as req_file:
req_file.write(data)
def validate_file(data):
""" Validates if requirements_all.txt is up to date. """
"""Validate if requirements_all.txt is up to date."""
with open('requirements_all.txt', 'r') as req_file:
return data == ''.join(req_file)
def main():
""" Main """
"""Main section of the script."""
if not os.path.isfile('requirements_all.txt'):
print('Run this from HA root dir')
return

View File

@ -1,7 +1,8 @@
#! /usr/bin/python
"""
Query the Home Assistant API for available entities then print them and any
desired attributes to the screen.
Query the Home Assistant API for available entities.
Output is printed to stdout.
"""
import sys
@ -17,19 +18,19 @@ import json
def main(password, askpass, attrs, address, port):
""" fetch Home Assistant api json page and post process """
# ask for password
"""Fetch Home Assistant API JSON page and post process."""
# Ask for password
if askpass:
password = getpass.getpass('Home Assistant API Password: ')
# fetch API result
# Fetch API result
url = mk_url(address, port, password)
response = urlopen(url).read()
if PYTHON == 3:
response = response.decode('utf-8')
data = json.loads(response)
# parse data
# Parse data
output = {'entity_id': []}
output.update([(attr, []) for attr in attrs])
for item in data:
@ -37,18 +38,18 @@ def main(password, askpass, attrs, address, port):
for attr in attrs:
output[attr].append(item['attributes'].get(attr, ''))
# output data
# Output data
print_table(output, ['entity_id'] + attrs)
def print_table(data, columns):
""" format and print a table of data from a dictionary """
# get column lengths
"""Format and print a table of data from a dictionary."""
# Get column lengths
lengths = {}
for key, value in data.items():
lengths[key] = max([len(str(val)) for val in value] + [len(key)])
# print header
# Print header
for item in columns:
itemup = item.upper()
sys.stdout.write(itemup + ' ' * (lengths[item] - len(item) + 4))
@ -63,7 +64,7 @@ def print_table(data, columns):
def mk_url(address, port, password):
""" construct the url call for the api states page """
"""Construct the URL call for the API states page."""
url = ''
if address.startswith('http://'):
url += address

View File

@ -1,7 +1,5 @@
#!/usr/bin/env python3
"""
Downloads the latest Polymer v1 iconset version for materialdesignicons.com
"""
"""Download the latest Polymer v1 iconset for materialdesignicons.com."""
import hashlib
import os
import re
@ -21,7 +19,7 @@ ICONSET_OUTPUT = os.path.join(OUTPUT_BASE, 'www_static', 'mdi.html')
def get_local_version():
""" Parse local version. """
"""Parse the local version."""
try:
with open(VERSION_OUTPUT) as inp:
for line in inp:
@ -34,7 +32,7 @@ def get_local_version():
def get_remote_version():
""" Get current version and download link. """
"""Get current version and download link."""
gs_page = requests.get(GETTING_STARTED_URL).text
mdi_download = re.search(DOWNLOAD_LINK, gs_page)
@ -50,12 +48,12 @@ def get_remote_version():
def clean_component(source):
""" Clean component. """
"""Clean component."""
return source[source.index(START_ICONSET):]
def write_component(version, source):
""" Write component. """
"""Write component."""
with open(ICONSET_OUTPUT, 'w') as outp:
print('Writing icons to', ICONSET_OUTPUT)
outp.write(source)
@ -68,6 +66,7 @@ def write_component(version, source):
def main():
"""Main section of the script."""
# All scripts should have their current work dir set to project root
if os.path.basename(os.getcwd()) == 'script':
os.chdir('..')

View File

@ -102,6 +102,7 @@ def ensure_sun_set(hass):
def mock_state_change_event(hass, new_state, old_state=None):
"""Mock state change envent."""
event_data = {
'entity_id': new_state.entity_id,
'new_state': new_state,
@ -133,14 +134,17 @@ def mock_mqtt_component(hass, mock_mqtt):
class MockHTTP(object):
"""Mock the HTTP module."""
def register_path(self, method, url, callback, require_auth=True):
"""Register a path."""
pass
class MockModule(object):
""" Provides a fake module. """
"""Representation of a fake module."""
def __init__(self, domain=None, dependencies=[], setup=None):
"""Initialize the mock module."""
self.DOMAIN = domain
self.DEPENDENCIES = dependencies
# Setup a mock setup if none given.
@ -166,7 +170,9 @@ class MockPlatform(object):
class MockToggleDevice(ToggleEntity):
"""Provide a mock toggle device."""
def __init__(self, name, state):
"""Initialize the mock device."""
self._name = name or DEVICE_DEFAULT_NAME
self._state = state
self.calls = []
@ -179,7 +185,7 @@ class MockToggleDevice(ToggleEntity):
@property
def state(self):
"""Returns the name of the device if any."""
"""Return the name of the device if any."""
self.calls.append(('state', {}))
return self._state

View File

@ -2,7 +2,7 @@
def get_scanner(hass, config):
"""Returns a mock scanner."""
"""Return a mock scanner."""
return SCANNER

View File

@ -0,0 +1 @@
"""The tests for the helpers."""

View File

@ -12,7 +12,7 @@ class TestHelpersEntity(unittest.TestCase):
"""Test homeassistant.helpers.entity module."""
def setUp(self): # pylint: disable=invalid-name
"""Init needed objects."""
"""Setup things to be run when tests are started."""
self.entity = entity.Entity()
self.entity.entity_id = 'test.overwrite_hidden_true'
self.hass = self.entity.hass = get_test_home_assistant()

View File

@ -1,4 +1,4 @@
"""Test the entity component helper."""
"""The tests for the Entity component helper."""
# pylint: disable=protected-access,too-many-public-methods
from collections import OrderedDict
import logging
@ -20,7 +20,10 @@ DOMAIN = "test_domain"
class EntityTest(Entity):
"""Test for the Entity component."""
def __init__(self, **values):
"""Initialize an entity."""
self._values = values
if 'entity_id' in values:
@ -28,24 +31,28 @@ class EntityTest(Entity):
@property
def name(self):
"""Return the name of the entity."""
return self._handle('name')
@property
def should_poll(self):
"""Return the ste of the polling."""
return self._handle('should_poll')
@property
def unique_id(self):
"""Return the unique ID of the entity."""
return self._handle('unique_id')
def _handle(self, attr):
"""Helper for the attributes."""
if attr in self._values:
return self._values[attr]
return getattr(super(), attr)
class TestHelpersEntityComponent(unittest.TestCase):
""" Tests homeassistant.helpers.entity_component module. """
"""Test homeassistant.helpers.entity_component module."""
def setUp(self): # pylint: disable=invalid-name
"""Initialize a test Home Assistant instance."""
@ -56,6 +63,7 @@ class TestHelpersEntityComponent(unittest.TestCase):
self.hass.stop()
def test_setting_up_group(self):
"""Setup the setting of a group."""
component = EntityComponent(_LOGGER, DOMAIN, self.hass,
group_name='everyone')
@ -82,6 +90,7 @@ class TestHelpersEntityComponent(unittest.TestCase):
sorted(group.attributes.get('entity_id'))
def test_polling_only_updates_entities_it_should_poll(self):
"""Test the polling of only updated entities."""
component = EntityComponent(_LOGGER, DOMAIN, self.hass, 20)
no_poll_ent = EntityTest(should_poll=False)
@ -117,6 +126,7 @@ class TestHelpersEntityComponent(unittest.TestCase):
assert 2 == len(self.hass.states.entity_ids())
def test_not_adding_duplicate_entities(self):
"""Test for not adding duplicate entities."""
component = EntityComponent(_LOGGER, DOMAIN, self.hass)
assert 0 == len(self.hass.states.entity_ids())
@ -130,6 +140,7 @@ class TestHelpersEntityComponent(unittest.TestCase):
assert 1 == len(self.hass.states.entity_ids())
def test_not_assigning_entity_id_if_prescribes_one(self):
"""Test for not assigning an entity ID."""
component = EntityComponent(_LOGGER, DOMAIN, self.hass)
assert 'hello.world' not in self.hass.states.entity_ids()
@ -139,6 +150,7 @@ class TestHelpersEntityComponent(unittest.TestCase):
assert 'hello.world' in self.hass.states.entity_ids()
def test_extract_from_service_returns_all_if_no_entity_id(self):
"""Test the extraction of everything from service."""
component = EntityComponent(_LOGGER, DOMAIN, self.hass)
component.add_entities([
EntityTest(name='test_1'),
@ -152,6 +164,7 @@ class TestHelpersEntityComponent(unittest.TestCase):
component.extract_from_service(call))
def test_extract_from_service_filter_out_non_existing_entities(self):
"""Test the extraction of non existing entities from service."""
component = EntityComponent(_LOGGER, DOMAIN, self.hass)
component.add_entities([
EntityTest(name='test_1'),
@ -166,6 +179,7 @@ class TestHelpersEntityComponent(unittest.TestCase):
[ent.entity_id for ent in component.extract_from_service(call)]
def test_setup_loads_platforms(self):
"""Test the loading of the platforms."""
component_setup = Mock(return_value=True)
platform_setup = Mock(return_value=None)
loader.set_component(
@ -189,6 +203,7 @@ class TestHelpersEntityComponent(unittest.TestCase):
assert platform_setup.called
def test_setup_recovers_when_setup_raises(self):
"""Test the setup if exceptions are happening."""
platform1_setup = Mock(side_effect=Exception('Broken'))
platform2_setup = Mock(return_value=None)
@ -212,6 +227,7 @@ class TestHelpersEntityComponent(unittest.TestCase):
@patch('homeassistant.helpers.entity_component.EntityComponent'
'._setup_platform')
def test_setup_does_discovery(self, mock_setup):
"""Test setup for discovery."""
component = EntityComponent(
_LOGGER, DOMAIN, self.hass, discovery_platforms={
'discovery.test': 'platform_test',
@ -232,7 +248,9 @@ class TestHelpersEntityComponent(unittest.TestCase):
@patch('homeassistant.helpers.entity_component.track_utc_time_change')
def test_set_scan_interval_via_config(self, mock_track):
"""Test the setting of the scan interval via configuration."""
def platform_setup(hass, config, add_devices, discovery_info=None):
"""Test the platform setup."""
add_devices([EntityTest(should_poll=True)])
loader.set_component('test_domain.platform',
@ -252,7 +270,9 @@ class TestHelpersEntityComponent(unittest.TestCase):
@patch('homeassistant.helpers.entity_component.track_utc_time_change')
def test_set_scan_interval_via_platform(self, mock_track):
"""Test the setting of the scan interval via platform."""
def platform_setup(hass, config, add_devices, discovery_info=None):
"""Test the platform setup."""
add_devices([EntityTest(should_poll=True)])
platform = MockPlatform(platform_setup)

View File

@ -21,7 +21,7 @@ class TestEventDecoratorHelpers(unittest.TestCase):
"""Test the Home Assistant event helpers."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started. """
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.states.set("light.Bowl", "on")
self.hass.states.set("switch.AC", "off")
@ -29,7 +29,7 @@ class TestEventDecoratorHelpers(unittest.TestCase):
event_decorators.HASS = self.hass
def tearDown(self): # pylint: disable=invalid-name
""" Stop down stuff we started. """
"""Stop everything that was started."""
self.hass.stop()
event_decorators.HASS = None

View File

@ -23,7 +23,7 @@ def create_file(path):
class TestConfig(unittest.TestCase):
"""Test the configutils. """
"""Test the configutils."""
def tearDown(self): # pylint: disable=invalid-name
"""Clean up."""
@ -65,7 +65,7 @@ class TestConfig(unittest.TestCase):
self.assertEqual('', content)
def test_load_yaml_config_converts_empty_files_to_dict(self):
""" Test that loading an empty file returns an empty dict. """
"""Test that loading an empty file returns an empty dict."""
create_file(YAML_PATH)
self.assertIsInstance(

View File

@ -35,7 +35,7 @@ class TestHomeAssistant(unittest.TestCase):
self.hass.states.set("switch.AC", "off")
def tearDown(self): # pylint: disable=invalid-name
"""Stop down stuff we started."""
"""Stop everything that was started."""
try:
self.hass.stop()
except HomeAssistantError:
@ -106,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."""
self.assertEqual(
"<Event TestEvent[L]>",
str(ha.Event("TestEvent")))
@ -237,7 +237,7 @@ class TestState(unittest.TestCase):
class TestStateMachine(unittest.TestCase):
"""Test State machine methods. """
"""Test State machine methods."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
@ -349,7 +349,7 @@ class TestServiceCall(unittest.TestCase):
class TestServiceRegistry(unittest.TestCase):
""" Test ServicerRegistry methods. """
"""Test ServicerRegistry methods."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
@ -419,7 +419,7 @@ class TestConfig(unittest.TestCase):
"""Test configuration methods."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started. """
"""Setup things to be run when tests are started."""
self.config = ha.Config()
def test_config_dir_set_correct(self):

View File

@ -216,7 +216,7 @@ class TestRemoteClasses(unittest.TestCase):
remote.API('127.0.0.1', API_PASSWORD, BROKEN_PORT))
def test_statemachine_init(self):
""" Tests if remote.StateMachine copies all states on init. """
"""Test if remote.StateMachine copies all states on init."""
self.assertEqual(sorted(hass.states.all()),
sorted(slave.states.all()))

View File

@ -0,0 +1 @@
"""The tests for the utilities."""

View File

@ -62,9 +62,9 @@ class TestUtil(unittest.TestCase):
def test_ordered_enum(self):
"""Test the ordered enum class."""
class TestEnum(util.OrderedEnum):
"""Test enum that can be ordered."""
FIRST = 1
SECOND = 2
THIRD = 3
@ -214,7 +214,6 @@ class TestUtil(unittest.TestCase):
def test_throttle_per_instance(self):
"""Test that the throttle method is done per instance of a class."""
class Tester(object):
"""A tester class for the throttle."""
@ -228,7 +227,6 @@ class TestUtil(unittest.TestCase):
def test_throttle_on_method(self):
"""Test that throttle works when wrapping a method."""
class Tester(object):
"""A tester class for the throttle."""
@ -244,7 +242,6 @@ class TestUtil(unittest.TestCase):
def test_throttle_on_two_method(self):
"""Test that throttle works when wrapping two methods."""
class Tester(object):
"""A test class for the throttle."""