input
stringlengths
53
297k
output
stringclasses
604 values
repo_name
stringclasses
376 values
test_path
stringclasses
583 values
code_path
stringlengths
7
116
import tempfile from os import listdir, mkdir, makedirs, path from shutil import copy, copyfile, rmtree from subprocess import check_output, CalledProcessError, STDOUT import sys from fauxfactory import gen_alphanumeric from cfme.utils import conf from cfme.utils.providers import providers_data from cfme.utils.appliance import current_appliance from git import Repo from yaml import load, dump local_git_repo = "manageiq_ansible_module" yml_path = path.join(path.dirname(__file__), local_git_repo) yml_templates_path = path.join(path.dirname(__file__), 'ansible_conf') basic_script = "basic_script.yml" yml = ".yml" random_token = str(gen_alphanumeric(906)) random_miq_user = str(gen_alphanumeric(8)) pulled_repo_library_path = path.join(local_git_repo, 'library') remote_git_repo_url = "git://github.com/dkorn/manageiq-ansible-module.git" def create_tmp_directory(): global lib_path lib_path = tempfile.mkdtemp() lib_sub_path = 'ansible_conf' lib_sub_path_library = path.join(lib_sub_path, 'library') makedirs(path.join((lib_path), lib_sub_path_library)) global library_path_to_copy_to global basic_yml_path library_path_to_copy_to = path.join(lib_path, lib_sub_path_library) basic_yml_path = path.join(lib_path, lib_sub_path) def fetch_miq_ansible_module(): if path.isdir(local_git_repo): rmtree(local_git_repo) mkdir(local_git_repo) if path.isdir(library_path_to_copy_to): rmtree(library_path_to_copy_to) mkdir(library_path_to_copy_to) Repo.clone_from(remote_git_repo_url, local_git_repo) src_files = listdir(pulled_repo_library_path) for file_name in src_files: full_file_name = path.join(pulled_repo_library_path, file_name) if path.isfile(full_file_name): copy(full_file_name, library_path_to_copy_to) rmtree(local_git_repo) def get_values_for_providers_test(provider): return { 'name': provider.name, 'state': 'present', 'miq_url': config_formatter(), 'miq_username': conf.credentials['default'].username, 'miq_password': conf.credentials['default'].password, 'provider_api_hostname': providers_data[provider.name]['endpoints']['default'].hostname, 'provider_api_port': providers_data[provider.name]['endpoints']['default'].api_port, 'provider_api_auth_token': providers_data[provider.name]['endpoints']['default'].token, 'monitoring_hostname': providers_data[provider.name]['endpoints']['hawkular'].hostname, 'monitoring_port': providers_data[provider.name]['endpoints']['hawkular'].api_port } def get_values_for_users_test(): return { 'fullname': 'MIQUser', 'name': 'MIQU', 'password': 'smartvm', 'state': 'present', 'miq_url': config_formatter(), 'miq_username': conf.credentials['default'].username, 'miq_password': conf.credentials['default'].password, } def get_values_for_custom_attributes_test(provider): return { 'entity_type': 'provider', 'entity_name': conf.cfme_data.get('management_systems', {}) [provider.key].get('name', []), 'miq_url': config_formatter(), 'miq_username': conf.credentials['default'].username, 'miq_password': conf.credentials['default'].password, } def get_values_for_tags_test(provider): return { 'resource': 'provider', 'resource_name': provider.name, 'miq_url': config_formatter(), 'miq_username': conf.credentials['default'].username, 'miq_password': conf.credentials['default'].password, } def get_values_from_conf(provider, script_type): if script_type == 'providers': return get_values_for_providers_test(provider) if script_type == 'users': return get_values_for_users_test() if script_type == 'custom_attributes': return get_values_for_custom_attributes_test(provider) if script_type == 'tags': return get_values_for_tags_test(provider) # TODO Avoid reading files every time def read_yml(script, value): with open(yml_path + script + yml, 'r') as f: doc = load(f) return doc[0]['tasks'][0]['manageiq_provider'][value] def get_yml_value(script, value): with open(path.join(basic_yml_path, script) + yml, 'r') as f: doc = load(f) return doc[0]['tasks'][0]['manageiq_provider'][value] def setup_basic_script(provider, script_type): script_path_source = path.join(yml_templates_path, script_type + "_" + basic_script) script_path = path.join(basic_yml_path, script_type + "_" + basic_script) copyfile(script_path_source, script_path) with open(script_path, 'rw') as f: doc = load(f) values_dict = get_values_from_conf(provider, script_type) for key in values_dict: if script_type == 'providers': doc[0]['tasks'][0]['manageiq_provider'][key] = values_dict[key] elif script_type == 'users': doc[0]['tasks'][0]['manageiq_user'][key] = values_dict[key] elif script_type == 'custom_attributes': doc[0]['tasks'][0]['manageiq_custom_attributes'][key] = values_dict[key] elif script_type == 'tags': doc[0]['tasks'][0]['manageiq_tag_assignment'][key] = values_dict[key] with open(script_path, 'w') as f: f.write(dump(doc)) def open_yml(script, script_type): copyfile((path.join(basic_yml_path, script_type + "_" + basic_script)), path.join(basic_yml_path, script + yml)) with open(path.join(basic_yml_path, script + yml), 'rw') as f: return load(f) def write_yml(script, doc): with open(path.join(basic_yml_path, script + yml), 'w') as f: f.write(dump(doc)) def setup_ansible_script(provider, script, script_type=None, values_to_update=None): # This function prepares the ansible scripts to work with the correct # appliance configs that will be received from Jenkins setup_basic_script(provider, script_type) doc = open_yml(script, script_type) if script == 'add_provider': write_yml(script, doc) if script == 'add_provider_ssl': doc[0]['tasks'][0]['manageiq_provider']['provider_verify_ssl'] = 'True' write_yml(script, doc) elif script == 'update_provider': for key in values_to_update: doc[0]['tasks'][0]['manageiq_provider'][key] = values_to_update[key] write_yml(script, doc) elif script == 'remove_provider': doc[0]['tasks'][0]['manageiq_provider']['state'] = 'absent' write_yml(script, doc) elif script == 'remove_non_existing_provider': doc[0]['tasks'][0]['manageiq_provider']['state'] = 'absent' doc[0]['tasks'][0]['manageiq_provider']['name'] = random_miq_user write_yml(script, doc) elif script == 'remove_provider_bad_user': doc[0]['tasks'][0]['manageiq_provider']['miq_username'] = random_miq_user write_yml(script, doc) elif script == 'add_provider_bad_token': doc[0]['tasks'][0]['manageiq_provider']['provider_api_auth_token'] = random_token write_yml(script, doc) elif script == 'add_provider_bad_user': doc[0]['tasks'][0]['manageiq_provider']['miq_username'] = random_miq_user write_yml(script, doc) elif script == 'update_non_existing_provider': doc[0]['tasks'][0]['manageiq_provider']['provider_api_hostname'] = random_miq_user write_yml(script, doc) elif script == 'update_provider_bad_user': for key in values_to_update: doc[0]['tasks'][0]['manageiq_provider'][key] = values_to_update[key] doc[0]['tasks'][0]['manageiq_provider']['miq_username'] = random_miq_user write_yml(script, doc) elif script == 'create_user': for key in values_to_update: doc[0]['tasks'][0]['manageiq_user'][key] = values_to_update[key] write_yml(script, doc) elif script == 'update_user': for key in values_to_update: doc[0]['tasks'][0]['manageiq_user'][key] = values_to_update[key] write_yml(script, doc) elif script == 'create_user_bad_user_name': doc[0]['tasks'][0]['manageiq_user']['miq_username'] = random_miq_user for key in values_to_update: doc[0]['tasks'][0]['manageiq_user'][key] = values_to_update[key] write_yml(script, doc) elif script == 'delete_user': doc[0]['tasks'][0]['manageiq_user']['name'] = values_to_update doc[0]['tasks'][0]['manageiq_user']['state'] = 'absent' write_yml(script, doc) elif script == 'add_custom_attributes': count = 0 while count < len(values_to_update): for key in values_to_update: doc[0]['tasks'][0]['manageiq_custom_attributes']['custom_attributes'][count] = key count += 1 write_yml(script, doc) elif script == 'add_custom_attributes_bad_user': doc[0]['tasks'][0]['manageiq_custom_attributes']['miq_username'] = str(random_miq_user) write_yml(script, doc) elif script == 'remove_custom_attributes': count = 0 doc[0]['tasks'][0]['manageiq_custom_attributes']['state'] = 'absent' while count < len(values_to_update): for key in values_to_update: doc[0]['tasks'][0]['manageiq_custom_attributes']['custom_attributes'][count] = key count += 1 write_yml(script, doc) elif script == 'add_tags': count = 0 while count < len(values_to_update): for key in values_to_update: doc[0]['tasks'][0]['manageiq_tag_assignment']['tags'][count]['category'] = \ values_to_update[count]['category'] doc[0]['tasks'][0]['manageiq_tag_assignment']['tags'][count]['name'] = \ values_to_update[count]['name'] count += 1 doc[0]['tasks'][0]['manageiq_tag_assignment']['state'] = 'present' write_yml(script, doc) elif script == 'remove_tags': count = 0 while count < len(values_to_update): for key in values_to_update: doc[0]['tasks'][0]['manageiq_tag_assignment']['tags'][count]['category'] = \ values_to_update[count]['category'] doc[0]['tasks'][0]['manageiq_tag_assignment']['tags'][count]['name'] = \ values_to_update[count]['name'] count += 1 doc[0]['tasks'][0]['manageiq_tag_assignment']['state'] = 'absent' write_yml(script, doc) def run_ansible(script): ansible_playbook_cmd = "ansible-playbook -e ansible_python_interpreter=" interpreter_path = sys.executable script_path = path.join(basic_yml_path, script + ".yml") cmd = '{}{} {}'.format(ansible_playbook_cmd, interpreter_path, script_path) return run_cmd(cmd) def run_cmd(cmd): try: response = check_output(cmd, shell=True, stderr=STDOUT) except CalledProcessError as exc: print("Status : FAIL", exc.returncode, exc.output) return exc.output else: print("Output: \n{}\n".format(response)) # TODO For further usage with reply statuses test. Not being used at the moment def reply_status(reply): ok_status = reply['stats']['localhost']['ok'] changed_status = reply['stats']['localhost']['changed'] failures_status = reply['stats']['localhost']['failures'] skipped_status = reply['stats']['localhost']['skipped'] message_status = reply['plays'][0]['tasks'][2]['hosts']['localhost']['result']['msg'] if not ok_status == '0': ok_status = 'OK' else: ok_status = 'Failed' if changed_status: return 'Changed', message_status, ok_status elif skipped_status: return 'Skipped', message_status, ok_status elif failures_status: return 'Failed', message_status, ok_status else: return 'No Change', message_status, ok_status def config_formatter(appliance=None): appliance = appliance or current_appliance() return appliance.url def remove_tmp_files(): rmtree(lib_path, ignore_errors=True)
# -*- coding: utf-8 -*- """ Tests checking the basic functionality of the Control/Explorer section. Whether we can create/update/delete/assign/... these objects. Nothing with deep meaning. Can be also used as a unit-test for page model coverage. """ import random from collections import namedtuple import fauxfactory import pytest from cfme import test_requirements from cfme.control.explorer import alert_profiles, conditions, policies from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.blockers import BZ from cfme.utils.update import update from cfme.utils.version import current_version pytestmark = [ pytest.mark.long_running, test_requirements.control ] EXPRESSIONS_TO_TEST = [ ( "Field", "fill_field({} : Last Compliance Timestamp, BEFORE, 03/04/2014)", '{} : Last Compliance Timestamp BEFORE "03/04/2014 00:00"' ), ( "Count", "fill_count({}.Compliance History, >, 0)", 'COUNT OF {}.Compliance History > 0' ), ( "Tag", "fill_tag({}.User.My Company Tags : Location, Chicago)", "{}.User.My Company Tags : Location CONTAINS 'Chicago'" ), ( "Find", "fill_find({}.Compliance History : Event Type, INCLUDES, some_string, Check Any," "Resource Type, =, another_string)", 'FIND {}.Compliance History : Event Type INCLUDES "some_string" CHECK ANY Resource Type' ' = "another_string"' ) ] COMPLIANCE_POLICIES = [ policies.HostCompliancePolicy, policies.VMCompliancePolicy, policies.ReplicatorCompliancePolicy, policies.PodCompliancePolicy, policies.ContainerNodeCompliancePolicy, policies.ContainerImageCompliancePolicy, ] CONTROL_POLICIES = [ policies.HostControlPolicy, policies.VMControlPolicy, policies.ReplicatorControlPolicy, policies.PodControlPolicy, policies.ContainerNodeControlPolicy, policies.ContainerImageControlPolicy ] POLICIES = COMPLIANCE_POLICIES + CONTROL_POLICIES CONDITIONS = [ conditions.HostCondition, conditions.VMCondition, conditions.ReplicatorCondition, conditions.PodCondition, conditions.ContainerNodeCondition, conditions.ContainerImageCondition, conditions.ProviderCondition ] PolicyAndCondition = namedtuple('PolicyAndCondition', ['name', 'policy', 'condition']) POLICIES_AND_CONDITIONS = [ PolicyAndCondition(name=obj[0].__name__, policy=obj[0], condition=obj[1]) for obj in zip(CONTROL_POLICIES, CONDITIONS) ] EVENTS = [ "Datastore Analysis Complete", "Datastore Analysis Request", "Host Auth Changed", "Host Auth Error", "Host Auth Incomplete Credentials", "Host Auth Invalid", "Host Auth Unreachable", "Host Auth Valid", "Provider Auth Changed", "Provider Auth Error", "Provider Auth Incomplete Credentials", "Provider Auth Invalid", "Provider Auth Unreachable", "Provider Auth Valid", "Tag Complete", "Tag Parent Cluster Complete", "Tag Parent Datastore Complete", "Tag Parent Host Complete", "Tag Parent Resource Pool Complete", "Tag Request", "Un-Tag Complete", "Un-Tag Parent Cluster Complete", "Un-Tag Parent Datastore Complete", "Un-Tag Parent Host Complete", "Un-Tag Parent Resource Pool Complete", "Un-Tag Request", "Container Image Compliance Failed", "Container Image Compliance Passed", "Container Node Compliance Failed", "Container Node Compliance Passed", "Host Compliance Failed", "Host Compliance Passed", "Pod Compliance Failed", "Pod Compliance Passed", "Replicator Compliance Failed", "Replicator Compliance Passed", "VM Compliance Failed", "VM Compliance Passed", "Container Image Analysis Complete", "Container Image Discovered", "Container Node Failed Mount", "Container Node Invalid Disk Capacity", "Container Node Not Ready", "Container Node Not Schedulable", "Container Node Ready", "Container Node Rebooted", "Container Node Schedulable", "Pod Deadline Exceeded", "Pod Failed Scheduling", "Pod Failed Sync", "Pod Failed Validation", "Pod Insufficient Free CPU", "Pod Insufficient Free Memory", "Pod Out of Disk", "Pod Scheduled", "Pod hostPort Conflict", "Pod nodeSelector Mismatching", "Replicator Failed Creating Pod", "Replicator Successfully Created Pod", "Host Added to Cluster", "Host Analysis Complete", "Host Analysis Request", "Host Connect", "Host Disconnect", "Host Maintenance Enter Request", "Host Maintenance Exit Request", "Host Provision Complete", "Host Reboot Request", "Host Removed from Cluster", "Host Reset Request", "Host Shutdown Request", "Host Standby Request", "Host Start Request", "Host Stop Request", "Host Vmotion Disable Request", "Host Vmotion Enable Request", "Service Provision Complete", "Service Retire Request", "Service Retired", "Service Retirement Warning", "Service Start Request", "Service Started", "Service Stop Request", "Service Stopped", "VM Clone Complete", "VM Clone Start", "VM Create Complete", "VM Delete (from Disk) Request", "VM Renamed Event", "VM Settings Change", "VM Template Create Complete", "VM Provision Complete", "VM Retire Request", "VM Retired", "VM Retirement Warning", "VM Analysis Complete", "VM Analysis Failure", "VM Analysis Request", "VM Analysis Start", "VM Guest Reboot", "VM Guest Reboot Request", "VM Guest Shutdown", "VM Guest Shutdown Request", "VM Live Migration (VMOTION)", "VM Pause", "VM Pause Request", "VM Power Off", "VM Power Off Request", "VM Power On", "VM Power On Request", "VM Remote Console Connected", "VM Removal from Inventory", "VM Removal from Inventory Request", "VM Reset", "VM Reset Request", "VM Resume", "VM Shelve", "VM Shelve Offload", "VM Shelve Offload Request", "VM Shelve Request", "VM Snapshot Create Complete", "VM Snapshot Create Request", "VM Snapshot Create Started", "VM Standby of Guest", "VM Standby of Guest Request", "VM Suspend", "VM Suspend Request" ] ALERT_PROFILES = [ alert_profiles.ClusterAlertProfile, alert_profiles.DatastoreAlertProfile, alert_profiles.HostAlertProfile, alert_profiles.ProviderAlertProfile, alert_profiles.ServerAlertProfile, alert_profiles.VMInstanceAlertProfile ] @pytest.fixture(scope="module") def policy_profile_collection(appliance): return appliance.collections.policy_profiles @pytest.fixture(scope="module") def policy_collection(appliance): return appliance.collections.policies @pytest.fixture(scope="module") def condition_collection(appliance): return appliance.collections.conditions @pytest.fixture(scope="module") def action_collection(appliance): return appliance.collections.actions @pytest.fixture(scope="module") def alert_collection(appliance): return appliance.collections.alerts @pytest.fixture(scope="module") def alert_profile_collection(appliance): return appliance.collections.alert_profiles @pytest.yield_fixture def two_random_policies(policy_collection): policy_1 = policy_collection.create( random.choice(POLICIES), fauxfactory.gen_alphanumeric() ) policy_2 = policy_collection.create( random.choice(POLICIES), fauxfactory.gen_alphanumeric() ) yield policy_1, policy_2 policy_collection.delete(policy_1, policy_2) @pytest.fixture(params=POLICIES, ids=lambda policy_class: policy_class.__name__) def policy_class(request): return request.param @pytest.fixture(params=ALERT_PROFILES, ids=lambda alert_profile: alert_profile.__name__) def alert_profile_class(request): return request.param @pytest.yield_fixture def policy(policy_collection, policy_class): policy_ = policy_collection.create(policy_class, fauxfactory.gen_alphanumeric()) yield policy_ policy_.delete() @pytest.yield_fixture(params=CONDITIONS, ids=lambda condition_class: condition_class.__name__, scope="module") def condition_for_expressions(request, condition_collection): condition_class = request.param condition = condition_collection.create( condition_class, fauxfactory.gen_alphanumeric(), expression="fill_field({} : Name, IS NOT EMPTY)".format(condition_class.FIELD_VALUE), scope="fill_field({} : Name, INCLUDES, {})".format(condition_class.FIELD_VALUE, fauxfactory.gen_alpha()) ) yield condition condition.delete() @pytest.fixture(params=CONDITIONS, ids=lambda condition_class: condition_class.__name__) def condition_prerequisites(request, condition_collection): condition_class = request.param expression = "fill_field({} : Name, =, {})".format( condition_class.FIELD_VALUE, fauxfactory.gen_alphanumeric() ) scope = "fill_field({} : Name, =, {})".format( condition_class.FIELD_VALUE, fauxfactory.gen_alphanumeric() ) return condition_class, scope, expression @pytest.yield_fixture(params=CONTROL_POLICIES, ids=lambda policy_class: policy_class.__name__) def control_policy(request, policy_collection): policy_class = request.param policy = policy_collection.create(policy_class, fauxfactory.gen_alphanumeric()) yield policy policy.delete() @pytest.yield_fixture def action(action_collection): action_ = action_collection.create( fauxfactory.gen_alphanumeric(), action_type="Tag", action_values={"tag": ("My Company Tags", "Department", "Accounting")} ) yield action_ action_.delete() @pytest.yield_fixture def alert(alert_collection): alert_ = alert_collection.create( fauxfactory.gen_alphanumeric(), based_on=random.choice(ALERT_PROFILES).TYPE, timeline_event=True, driving_event="Hourly Timer" ) yield alert_ alert_.delete() @pytest.yield_fixture def alert_profile(alert_profile_class, alert_collection, alert_profile_collection): alert = alert_collection.create( fauxfactory.gen_alphanumeric(), based_on=alert_profile_class.TYPE, timeline_event=True, driving_event="Hourly Timer" ) alert_profile_ = alert_profile_collection.create( alert_profile_class, fauxfactory.gen_alphanumeric(), alerts=[alert.description] ) yield alert_profile_ alert_profile_.delete() alert.delete() @pytest.yield_fixture(params=POLICIES_AND_CONDITIONS, ids=lambda item: item.name) def policy_and_condition(request, policy_collection, condition_collection): condition_class = request.param.condition policy_class = request.param.policy expression = "fill_field({} : Name, =, {})".format( condition_class.FIELD_VALUE, fauxfactory.gen_alphanumeric() ) condition = condition_collection.create( condition_class, fauxfactory.gen_alphanumeric(), expression=expression ) policy = policy_collection.create( policy_class, fauxfactory.gen_alphanumeric() ) yield policy, condition policy.delete() condition.delete() @pytest.mark.sauce @pytest.mark.tier(2) def test_condition_crud(condition_collection, condition_prerequisites): # CR condition_class, scope, expression = condition_prerequisites condition = condition_collection.create( condition_class, fauxfactory.gen_alphanumeric(), scope=scope, expression=expression ) with update(condition): condition.notes = "Modified!" # D condition.delete() @pytest.mark.sauce @pytest.mark.tier(2) def test_action_crud(action_collection): # CR action = action_collection.create( fauxfactory.gen_alphanumeric(), action_type="Tag", action_values={"tag": ("My Company Tags", "Department", "Accounting")} ) # U with update(action): action.description = "w00t w00t" # D action.delete() @pytest.mark.sauce @pytest.mark.tier(2) def test_policy_crud(policy_collection, policy_class): # CR policy = policy_collection.create(policy_class, fauxfactory.gen_alphanumeric()) # U with update(policy): policy.notes = "Modified!" # D policy.delete() @pytest.mark.tier(3) def test_policy_copy(policy): random_policy_copy = policy.copy() assert random_policy_copy.exists random_policy_copy.delete() @pytest.mark.tier(3) def test_assign_two_random_events_to_control_policy(control_policy, soft_assert): random_events = random.sample(EVENTS, 2) control_policy.assign_events(*random_events) soft_assert(control_policy.is_event_assigned(random_events[0])) soft_assert(control_policy.is_event_assigned(random_events[1])) @pytest.mark.tier(2) @pytest.mark.meta(blockers=[BZ(1491576, forced_streams=["5.7.4"])]) def test_control_assign_actions_to_event(request, policy, action): if type(policy) in CONTROL_POLICIES: event = random.choice(EVENTS) policy.assign_events(event) request.addfinalizer(policy.assign_events) else: prefix = policy.TREE_NODE if not policy.TREE_NODE == "Vm" else policy.TREE_NODE.upper() event = "{} Compliance Check".format(prefix) request.addfinalizer(lambda: policy.assign_actions_to_event( event, {"Mark as Non-Compliant": False})) policy.assign_actions_to_event(event, action) assert str(action) == policy.assigned_actions_to_event(event)[0] @pytest.mark.tier(3) def test_assign_condition_to_control_policy(request, policy_and_condition): """This test checks if a condition is assigned to a control policy. Steps: * Create a control policy. * Assign a condition to the created policy. """ policy, condition = policy_and_condition policy.assign_conditions(condition) request.addfinalizer(policy.assign_conditions) assert policy.is_condition_assigned(condition) @pytest.mark.sauce @pytest.mark.tier(2) def test_policy_profile_crud(policy_profile_collection, two_random_policies): profile = policy_profile_collection.create( fauxfactory.gen_alphanumeric(), policies=two_random_policies ) with update(profile): profile.notes = "Modified!" profile.delete() @pytest.mark.tier(3) @pytest.mark.parametrize("fill_type,expression,verify", EXPRESSIONS_TO_TEST, ids=[ expr[0] for expr in EXPRESSIONS_TO_TEST]) def test_modify_condition_expression(condition_for_expressions, fill_type, expression, verify): with update(condition_for_expressions): condition_for_expressions.expression = expression.format( condition_for_expressions.FIELD_VALUE) assert condition_for_expressions.read_expression() == verify.format( condition_for_expressions.FIELD_VALUE) @pytest.mark.sauce @pytest.mark.tier(2) def test_alert_crud(alert_collection): # CR alert = alert_collection.create( fauxfactory.gen_alphanumeric(), timeline_event=True, driving_event="Hourly Timer" ) # U with update(alert): alert.notification_frequency = "2 Hours" # D alert.delete() @pytest.mark.tier(3) @pytest.mark.meta(blockers=[1303645], automates=[1303645]) def test_control_alert_copy(alert): alert_copy = alert.copy(description=fauxfactory.gen_alphanumeric()) assert alert_copy.exists alert_copy.delete() @pytest.mark.sauce @pytest.mark.tier(2) def test_alert_profile_crud(request, alert_profile_class, alert_collection, alert_profile_collection): alert = alert_collection.create( fauxfactory.gen_alphanumeric(), based_on=alert_profile_class.TYPE, timeline_event=True, driving_event="Hourly Timer" ) request.addfinalizer(alert.delete) alert_profile = alert_profile_collection.create( alert_profile_class, fauxfactory.gen_alphanumeric(), alerts=[alert.description] ) with update(alert_profile): alert_profile.notes = "Modified!" alert_profile.delete() @pytest.mark.tier(2) @pytest.mark.meta(blockers=[BZ(1416311, forced_streams=["5.7"])]) def test_alert_profile_assigning(alert_profile): if isinstance(alert_profile, alert_profiles.ServerAlertProfile): if BZ(1489697, forced_streams=["5.8"]).blocks: pytest.skip("BZ 1489697") alert_profile.assign_to("Selected Servers", selections=["Servers", "EVM"]) else: alert_profile.assign_to("The Enterprise") @pytest.mark.tier(2) @pytest.mark.uncollectif(lambda: current_version() < "5.8") def test_control_is_ansible_playbook_available_in_actions_dropdown(action_collection): view = navigate_to(action_collection, "Add") assert "Run Ansible Playbook" in [option.text for option in view.action_type.all_options]
quarckster/cfme_tests
cfme/tests/control/test_basic.py
cfme/utils/ansible.py
"""Monitor Memory on a CFME/Miq appliance and builds report&graphs displaying usage per process.""" import matplotlib.dates as mdates import matplotlib.pyplot as plt import os import time import traceback import yaml from cfme.utils.conf import cfme_performance from cfme.utils.log import logger from cfme.utils.path import results_path from cfme.utils.version import get_version from cfme.utils.version import current_version from collections import OrderedDict from cycler import cycler from datetime import datetime from threading import Thread from yaycl import AttrDict import json import matplotlib as mpl mpl.use('Agg') miq_workers = [ 'MiqGenericWorker', 'MiqPriorityWorker', 'MiqScheduleWorker', 'MiqUiWorker', 'MiqWebServiceWorker', 'MiqWebsocketWorker', 'MiqReportingWorker', 'MiqReplicationWorker', 'MiqSmartProxyWorker', 'MiqVimBrokerWorker', 'MiqEmsRefreshCoreWorker', # Refresh Workers: 'ManageIQ::Providers::Microsoft::InfraManager::RefreshWorker', 'ManageIQ::Providers::Openstack::InfraManager::RefreshWorker', 'ManageIQ::Providers::Redhat::InfraManager::RefreshWorker', 'ManageIQ::Providers::Vmware::InfraManager::RefreshWorker', 'MiqEmsRefreshWorkerMicrosoft', # 5.4 'MiqEmsRefreshWorkerRedhat', # 5.4 'MiqEmsRefreshWorkerVmware', # 5.4 'ManageIQ::Providers::Amazon::CloudManager::RefreshWorker', 'ManageIQ::Providers::Azure::CloudManager::RefreshWorker', 'ManageIQ::Providers::Google::CloudManager::RefreshWorker', 'ManageIQ::Providers::Openstack::CloudManager::RefreshWorker', 'MiqEmsRefreshWorkerAmazon', # 5.4 'MiqEmsRefreshWorkerOpenstack', # 5.4 'ManageIQ::Providers::AnsibleTower::ConfigurationManager::RefreshWorker', 'ManageIQ::Providers::Foreman::ConfigurationManager::RefreshWorker', 'ManageIQ::Providers::Foreman::ProvisioningManager::RefreshWorker', 'MiqEmsRefreshWorkerForemanConfiguration', # 5.4 'MiqEmsRefreshWorkerForemanProvisioning', # 5.4 'ManageIQ::Providers::Atomic::ContainerManager::RefreshWorker', 'ManageIQ::Providers::AtomicEnterprise::ContainerManager::RefreshWorker', 'ManageIQ::Providers::Kubernetes::ContainerManager::RefreshWorker', 'ManageIQ::Providers::Openshift::ContainerManager::RefreshWorker', 'ManageIQ::Providers::OpenshiftEnterprise::ContainerManager::RefreshWorker', 'ManageIQ::Providers::StorageManager::CinderManager::RefreshWorker', 'ManageIQ::Providers::StorageManager::SwiftManager::RefreshWorker', 'ManageIQ::Providers::Amazon::NetworkManager::RefreshWorker', 'ManageIQ::Providers::Azure::NetworkManager::RefreshWorker', 'ManageIQ::Providers::Google::NetworkManager::RefreshWorker', 'ManageIQ::Providers::Openstack::NetworkManager::RefreshWorker', 'MiqNetappRefreshWorker', 'MiqSmisRefreshWorker', # Event Workers: 'MiqEventHandler', 'ManageIQ::Providers::Openstack::InfraManager::EventCatcher', 'ManageIQ::Providers::StorageManager::CinderManager::EventCatcher', 'ManageIQ::Providers::Redhat::InfraManager::EventCatcher', 'ManageIQ::Providers::Vmware::InfraManager::EventCatcher', 'MiqEventCatcherRedhat', # 5.4 'MiqEventCatcherVmware', # 5.4 'ManageIQ::Providers::Amazon::CloudManager::EventCatcher', 'ManageIQ::Providers::Azure::CloudManager::EventCatcher', 'ManageIQ::Providers::Google::CloudManager::EventCatcher', 'ManageIQ::Providers::Openstack::CloudManager::EventCatcher', 'MiqEventCatcherAmazon', # 5.4 'MiqEventCatcherOpenstack', # 5.4 'ManageIQ::Providers::Atomic::ContainerManager::EventCatcher', 'ManageIQ::Providers::AtomicEnterprise::ContainerManager::EventCatcher', 'ManageIQ::Providers::Kubernetes::ContainerManager::EventCatcher', 'ManageIQ::Providers::Openshift::ContainerManager::EventCatcher', 'ManageIQ::Providers::OpenshiftEnterprise::ContainerManager::EventCatcher', 'ManageIQ::Providers::Openstack::NetworkManager::EventCatcher', # Metrics Processor/Collector Workers 'MiqEmsMetricsProcessorWorker', 'ManageIQ::Providers::Openstack::InfraManager::MetricsCollectorWorker', 'ManageIQ::Providers::Redhat::InfraManager::MetricsCollectorWorker', 'ManageIQ::Providers::Vmware::InfraManager::MetricsCollectorWorker', 'MiqEmsMetricsCollectorWorkerRedhat', # 5.4 'MiqEmsMetricsCollectorWorkerVmware', # 5.4 'ManageIQ::Providers::Amazon::CloudManager::MetricsCollectorWorker', 'ManageIQ::Providers::Azure::CloudManager::MetricsCollectorWorker', 'ManageIQ::Providers::Openstack::CloudManager::MetricsCollectorWorker', 'MiqEmsMetricsCollectorWorkerAmazon', # 5.4 'MiqEmsMetricsCollectorWorkerOpenstack', # 5.4 'ManageIQ::Providers::Atomic::ContainerManager::MetricsCollectorWorker', 'ManageIQ::Providers::AtomicEnterprise::ContainerManager::MetricsCollectorWorker', 'ManageIQ::Providers::Kubernetes::ContainerManager::MetricsCollectorWorker', 'ManageIQ::Providers::Openshift::ContainerManager::MetricsCollectorWorker', 'ManageIQ::Providers::OpenshiftEnterprise::ContainerManager::MetricsCollectorWorker', 'ManageIQ::Providers::Openstack::NetworkManager::MetricsCollectorWorker', 'MiqStorageMetricsCollectorWorker', 'MiqVmdbStorageBridgeWorker'] ruby_processes = list(miq_workers) ruby_processes.extend(['evm:dbsync:replicate', 'MIQ Server (evm_server.rb)', 'evm_watchdog.rb', 'appliance_console.rb']) process_order = list(ruby_processes) process_order.extend(['memcached', 'postgres', 'httpd', 'collectd']) # Timestamp created at first import, thus grouping all reports of like workload test_ts = time.strftime('%Y%m%d%H%M%S') # 10s sample interval (occasionally sampling can take almost 4s on an appliance doing a lot of work) SAMPLE_INTERVAL = 10 class SmemMemoryMonitor(Thread): def __init__(self, ssh_client, scenario_data): super(SmemMemoryMonitor, self).__init__() self.ssh_client = ssh_client self.scenario_data = scenario_data self.grafana_urls = {} self.miq_server_id = '' self.use_slab = False self.signal = True def create_process_result(self, process_results, starttime, process_pid, process_name, memory_by_pid): if process_pid in memory_by_pid.keys(): if process_name not in process_results: process_results[process_name] = OrderedDict() process_results[process_name][process_pid] = OrderedDict() if process_pid not in process_results[process_name]: process_results[process_name][process_pid] = OrderedDict() process_results[process_name][process_pid][starttime] = {} rss_mem = memory_by_pid[process_pid]['rss'] pss_mem = memory_by_pid[process_pid]['pss'] uss_mem = memory_by_pid[process_pid]['uss'] vss_mem = memory_by_pid[process_pid]['vss'] swap_mem = memory_by_pid[process_pid]['swap'] process_results[process_name][process_pid][starttime]['rss'] = rss_mem process_results[process_name][process_pid][starttime]['pss'] = pss_mem process_results[process_name][process_pid][starttime]['uss'] = uss_mem process_results[process_name][process_pid][starttime]['vss'] = vss_mem process_results[process_name][process_pid][starttime]['swap'] = swap_mem del memory_by_pid[process_pid] else: logger.warn('Process {} PID, not found: {}'.format(process_name, process_pid)) def get_appliance_memory(self, appliance_results, plottime): # 5.5/5.6 - RHEL 7 / Centos 7 # Application Memory Used : MemTotal - (MemFree + Slab + Cached) # 5.4 - RHEL 6 / Centos 6 # Application Memory Used : MemTotal - (MemFree + Buffers + Cached) # Available memory could potentially be better metric appliance_results[plottime] = {} exit_status, meminfo_raw = self.ssh_client.run_command('cat /proc/meminfo') if exit_status: logger.error('Exit_status nonzero in get_appliance_memory: {}, {}'.format(exit_status, meminfo_raw)) del appliance_results[plottime] else: meminfo_raw = meminfo_raw.replace('kB', '').strip() meminfo = OrderedDict((k.strip(), v.strip()) for k, v in (value.strip().split(':') for value in meminfo_raw.split('\n'))) appliance_results[plottime]['total'] = float(meminfo['MemTotal']) / 1024 appliance_results[plottime]['free'] = float(meminfo['MemFree']) / 1024 if 'MemAvailable' in meminfo: # 5.5, RHEL 7/Centos 7 self.use_slab = True mem_used = (float(meminfo['MemTotal']) - (float(meminfo['MemFree']) + float( meminfo['Slab']) + float(meminfo['Cached']))) / 1024 else: # 5.4, RHEL 6/Centos 6 mem_used = (float(meminfo['MemTotal']) - (float(meminfo['MemFree']) + float( meminfo['Buffers']) + float(meminfo['Cached']))) / 1024 appliance_results[plottime]['used'] = mem_used appliance_results[plottime]['buffers'] = float(meminfo['Buffers']) / 1024 appliance_results[plottime]['cached'] = float(meminfo['Cached']) / 1024 appliance_results[plottime]['slab'] = float(meminfo['Slab']) / 1024 appliance_results[plottime]['swap_total'] = float(meminfo['SwapTotal']) / 1024 appliance_results[plottime]['swap_free'] = float(meminfo['SwapFree']) / 1024 def get_evm_workers(self): exit_status, worker_types = self.ssh_client.run_command( 'psql -t -q -d vmdb_production -c ' '\"select pid,type from miq_workers where miq_server_id = \'{}\'\"'.format( self.miq_server_id)) if worker_types.strip(): workers = {} for worker in worker_types.strip().split('\n'): pid_worker = worker.strip().split('|') if len(pid_worker) == 2: workers[pid_worker[0].strip()] = pid_worker[1].strip() else: logger.error('Unexpected output from psql: {}'.format(worker)) return workers else: return {} # Old method of obtaining per process memory (Appliances without smem) # def get_pids_memory(self): # exit_status, ps_memory = self.ssh_client.run_command( # 'ps -A -o pid,rss,vsz,comm,cmd | sed 1d') # pids_memory = ps_memory.strip().split('\n') # memory_by_pid = {} # for line in pids_memory: # values = [s for s in line.strip().split(' ') if s] # pid = values[0] # memory_by_pid[pid] = {} # memory_by_pid[pid]['rss'] = float(values[1]) / 1024 # memory_by_pid[pid]['vss'] = float(values[2]) / 1024 # memory_by_pid[pid]['name'] = values[3] # memory_by_pid[pid]['cmd'] = ' '.join(values[4:]) # return memory_by_pid def get_miq_server_id(self): # Obtain the Miq Server GUID: exit_status, miq_server_guid = self.ssh_client.run_command('cat /var/www/miq/vmdb/GUID') logger.info('Obtained appliance GUID: {}'.format(miq_server_guid.strip())) # Get server id: exit_status, miq_server_id = self.ssh_client.run_command( 'psql -t -q -d vmdb_production -c "select id from miq_servers where guid = \'{}\'"' ''.format(miq_server_guid.strip())) logger.info('Obtained miq_server_id: {}'.format(miq_server_id.strip())) self.miq_server_id = miq_server_id.strip() def get_pids_memory(self): exit_status, smem_out = self.ssh_client.run_command( 'smem -c \'pid rss pss uss vss swap name command\' | sed 1d') pids_memory = smem_out.strip().split('\n') memory_by_pid = {} for line in pids_memory: if line.strip(): try: values = [s for s in line.strip().split(' ') if s] pid = values[0] int(pid) memory_by_pid[pid] = {} memory_by_pid[pid]['rss'] = float(values[1]) / 1024 memory_by_pid[pid]['pss'] = float(values[2]) / 1024 memory_by_pid[pid]['uss'] = float(values[3]) / 1024 memory_by_pid[pid]['vss'] = float(values[4]) / 1024 memory_by_pid[pid]['swap'] = float(values[5]) / 1024 memory_by_pid[pid]['name'] = values[6] memory_by_pid[pid]['cmd'] = ' '.join(values[7:]) except Exception as e: logger.error('Processing smem output error: {}'.format(e.__class__.__name__, e)) logger.error('Issue with pid: {} line: {}'.format(pid, line)) logger.error('Complete smem output: {}'.format(smem_out)) return memory_by_pid def _real_run(self): """ Result dictionaries: appliance_results[timestamp][measurement] = value appliance_results[timestamp]['total'] = value appliance_results[timestamp]['free'] = value appliance_results[timestamp]['used'] = value appliance_results[timestamp]['buffers'] = value appliance_results[timestamp]['cached'] = value appliance_results[timestamp]['slab'] = value appliance_results[timestamp]['swap_total'] = value appliance_results[timestamp]['swap_free'] = value appliance measurements: total/free/used/buffers/cached/slab/swap_total/swap_free process_results[name][pid][timestamp][measurement] = value process_results[name][pid][timestamp]['rss'] = value process_results[name][pid][timestamp]['pss'] = value process_results[name][pid][timestamp]['uss'] = value process_results[name][pid][timestamp]['vss'] = value process_results[name][pid][timestamp]['swap'] = value """ appliance_results = OrderedDict() process_results = OrderedDict() install_smem(self.ssh_client) self.get_miq_server_id() logger.info('Starting Monitoring Thread.') while self.signal: starttime = time.time() plottime = datetime.now() self.get_appliance_memory(appliance_results, plottime) workers = self.get_evm_workers() memory_by_pid = self.get_pids_memory() for worker_pid in workers: self.create_process_result(process_results, plottime, worker_pid, workers[worker_pid], memory_by_pid) for pid in sorted(memory_by_pid.keys()): if memory_by_pid[pid]['name'] == 'httpd': self.create_process_result(process_results, plottime, pid, 'httpd', memory_by_pid) elif memory_by_pid[pid]['name'] == 'postgres': self.create_process_result(process_results, plottime, pid, 'postgres', memory_by_pid) elif memory_by_pid[pid]['name'] == 'postmaster': self.create_process_result(process_results, plottime, pid, 'postgres', memory_by_pid) elif memory_by_pid[pid]['name'] == 'memcached': self.create_process_result(process_results, plottime, pid, 'memcached', memory_by_pid) elif memory_by_pid[pid]['name'] == 'collectd': self.create_process_result(process_results, plottime, pid, 'collectd', memory_by_pid) elif memory_by_pid[pid]['name'] == 'ruby': if 'evm_server.rb' in memory_by_pid[pid]['cmd']: self.create_process_result(process_results, plottime, pid, 'MIQ Server (evm_server.rb)', memory_by_pid) elif 'MIQ Server' in memory_by_pid[pid]['cmd']: self.create_process_result(process_results, plottime, pid, 'MIQ Server (evm_server.rb)', memory_by_pid) elif 'evm_watchdog.rb' in memory_by_pid[pid]['cmd']: self.create_process_result(process_results, plottime, pid, 'evm_watchdog.rb', memory_by_pid) elif 'appliance_console.rb' in memory_by_pid[pid]['cmd']: self.create_process_result(process_results, plottime, pid, 'appliance_console.rb', memory_by_pid) elif 'evm:dbsync:replicate' in memory_by_pid[pid]['cmd']: self.create_process_result(process_results, plottime, pid, 'evm:dbsync:replicate', memory_by_pid) else: logger.debug('Unaccounted for ruby pid: {}'.format(pid)) timediff = time.time() - starttime logger.debug('Monitoring sampled in {}s'.format(round(timediff, 4))) # Sleep Monitoring interval # Roughly 10s samples, accounts for collection of memory measurements time_to_sleep = abs(SAMPLE_INTERVAL - timediff) time.sleep(time_to_sleep) logger.info('Monitoring CFME Memory Terminating') create_report(self.scenario_data, appliance_results, process_results, self.use_slab, self.grafana_urls) def run(self): try: self._real_run() except Exception as e: logger.error('Error in Monitoring Thread: {}'.format(e)) logger.error('{}'.format(traceback.format_exc())) def install_smem(ssh_client): # smem is included by default in 5.6 appliances logger.info('Installing smem.') ver = get_version() if ver == '55': ssh_client.run_command('rpm -i {}'.format(cfme_performance['tools']['rpms']['epel7_rpm'])) ssh_client.run_command('yum install -y smem') # Patch smem to display longer command line names logger.info('Patching smem') ssh_client.run_command('sed -i s/\.27s/\.200s/g /usr/bin/smem') def create_report(scenario_data, appliance_results, process_results, use_slab, grafana_urls): logger.info('Creating Memory Monitoring Report.') ver = current_version() provider_names = 'No Providers' if 'providers' in scenario_data['scenario']: provider_names = ', '.join(scenario_data['scenario']['providers']) workload_path = results_path.join('{}-{}-{}'.format(test_ts, scenario_data['test_dir'], ver)) if not os.path.exists(str(workload_path)): os.makedirs(str(workload_path)) scenario_path = workload_path.join(scenario_data['scenario']['name']) if os.path.exists(str(scenario_path)): logger.warn('Duplicate Workload-Scenario Name: {}'.format(scenario_path)) scenario_path = workload_path.join('{}-{}'.format(time.strftime('%Y%m%d%H%M%S'), scenario_data['scenario']['name'])) logger.warn('Using: {}'.format(scenario_path)) os.mkdir(str(scenario_path)) mem_graphs_path = scenario_path.join('graphs') if not os.path.exists(str(mem_graphs_path)): os.mkdir(str(mem_graphs_path)) mem_rawdata_path = scenario_path.join('rawdata') if not os.path.exists(str(mem_rawdata_path)): os.mkdir(str(mem_rawdata_path)) graph_appliance_measurements(mem_graphs_path, ver, appliance_results, use_slab, provider_names) graph_individual_process_measurements(mem_graphs_path, process_results, provider_names) graph_same_miq_workers(mem_graphs_path, process_results, provider_names) graph_all_miq_workers(mem_graphs_path, process_results, provider_names) # Dump scenario Yaml: with open(str(scenario_path.join('scenario.yml')), 'w') as scenario_file: yaml.dump(dict(scenario_data['scenario']), scenario_file, default_flow_style=False) generate_summary_csv(scenario_path.join('{}-summary.csv'.format(ver)), appliance_results, process_results, provider_names, ver) generate_raw_data_csv(mem_rawdata_path, appliance_results, process_results) generate_summary_html(scenario_path, ver, appliance_results, process_results, scenario_data, provider_names, grafana_urls) generate_workload_html(scenario_path, ver, scenario_data, provider_names, grafana_urls) logger.info('Finished Creating Report') def compile_per_process_results(procs_to_compile, process_results, ts_end): alive_pids = 0 recycled_pids = 0 total_running_rss = 0 total_running_pss = 0 total_running_uss = 0 total_running_vss = 0 total_running_swap = 0 for process in procs_to_compile: if process in process_results: for pid in process_results[process]: if ts_end in process_results[process][pid]: alive_pids += 1 total_running_rss += process_results[process][pid][ts_end]['rss'] total_running_pss += process_results[process][pid][ts_end]['pss'] total_running_uss += process_results[process][pid][ts_end]['uss'] total_running_vss += process_results[process][pid][ts_end]['vss'] total_running_swap += process_results[process][pid][ts_end]['swap'] else: recycled_pids += 1 return alive_pids, recycled_pids, total_running_rss, total_running_pss, total_running_uss, \ total_running_vss, total_running_swap def generate_raw_data_csv(directory, appliance_results, process_results): starttime = time.time() file_name = str(directory.join('appliance.csv')) with open(file_name, 'w') as csv_file: csv_file.write('TimeStamp,Total,Free,Used,Buffers,Cached,Slab,Swap_Total,Swap_Free\n') for ts in appliance_results: csv_file.write('{},{},{},{},{},{},{},{},{}\n'.format(ts, appliance_results[ts]['total'], appliance_results[ts]['free'], appliance_results[ts]['used'], appliance_results[ts]['buffers'], appliance_results[ts]['cached'], appliance_results[ts]['slab'], appliance_results[ts]['swap_total'], appliance_results[ts]['swap_free'])) for process_name in process_results: for process_pid in process_results[process_name]: file_name = str(directory.join('{}-{}.csv'.format(process_pid, process_name))) with open(file_name, 'w') as csv_file: csv_file.write('TimeStamp,RSS,PSS,USS,VSS,SWAP\n') for ts in process_results[process_name][process_pid]: csv_file.write('{},{},{},{},{},{}\n'.format(ts, process_results[process_name][process_pid][ts]['rss'], process_results[process_name][process_pid][ts]['pss'], process_results[process_name][process_pid][ts]['uss'], process_results[process_name][process_pid][ts]['vss'], process_results[process_name][process_pid][ts]['swap'])) timediff = time.time() - starttime logger.info('Generated Raw Data CSVs in: {}'.format(timediff)) def generate_summary_csv(file_name, appliance_results, process_results, provider_names, version_string): starttime = time.time() with open(str(file_name), 'w') as csv_file: csv_file.write('Version: {}, Provider(s): {}\n'.format(version_string, provider_names)) csv_file.write('Measurement,Start of test,End of test\n') start = appliance_results.keys()[0] end = appliance_results.keys()[-1] csv_file.write('Appliance Total Memory,{},{}\n'.format( round(appliance_results[start]['total'], 2), round(appliance_results[end]['total'], 2))) csv_file.write('Appliance Free Memory,{},{}\n'.format( round(appliance_results[start]['free'], 2), round(appliance_results[end]['free'], 2))) csv_file.write('Appliance Used Memory,{},{}\n'.format( round(appliance_results[start]['used'], 2), round(appliance_results[end]['used'], 2))) csv_file.write('Appliance Buffers,{},{}\n'.format( round(appliance_results[start]['buffers'], 2), round(appliance_results[end]['buffers'], 2))) csv_file.write('Appliance Cached,{},{}\n'.format( round(appliance_results[start]['cached'], 2), round(appliance_results[end]['cached'], 2))) csv_file.write('Appliance Slab,{},{}\n'.format( round(appliance_results[start]['slab'], 2), round(appliance_results[end]['slab'], 2))) csv_file.write('Appliance Total Swap,{},{}\n'.format( round(appliance_results[start]['swap_total'], 2), round(appliance_results[end]['swap_total'], 2))) csv_file.write('Appliance Free Swap,{},{}\n'.format( round(appliance_results[start]['swap_free'], 2), round(appliance_results[end]['swap_free'], 2))) summary_csv_measurement_dump(csv_file, process_results, 'rss') summary_csv_measurement_dump(csv_file, process_results, 'pss') summary_csv_measurement_dump(csv_file, process_results, 'uss') summary_csv_measurement_dump(csv_file, process_results, 'vss') summary_csv_measurement_dump(csv_file, process_results, 'swap') timediff = time.time() - starttime logger.info('Generated Summary CSV in: {}'.format(timediff)) def generate_summary_html(directory, version_string, appliance_results, process_results, scenario_data, provider_names, grafana_urls): starttime = time.time() file_name = str(directory.join('index.html')) with open(file_name, 'w') as html_file: html_file.write('<html>\n') html_file.write('<head><title>{} - {} Memory Usage Performance</title></head>'.format( version_string, provider_names)) html_file.write('<body>\n') html_file.write('<b>CFME {} {} Test Results</b><br>\n'.format(version_string, scenario_data['test_name'].title())) html_file.write('<b>Appliance Roles:</b> {}<br>\n'.format( scenario_data['appliance_roles'].replace(',', ', '))) html_file.write('<b>Provider(s):</b> {}<br>\n'.format(provider_names)) html_file.write('<b><a href=\'https://{}/\' target="_blank">{}</a></b>\n'.format( scenario_data['appliance_ip'], scenario_data['appliance_name'])) if grafana_urls: for g_name in sorted(grafana_urls.keys()): html_file.write( ' : <b><a href=\'{}\' target="_blank">{}</a></b>'.format(grafana_urls[g_name], g_name)) html_file.write('<br>\n') html_file.write('<b><a href=\'{}-summary.csv\'>Summary CSV</a></b>'.format(version_string)) html_file.write(' : <b><a href=\'workload.html\'>Workload Info</a></b>') html_file.write(' : <b><a href=\'graphs/\'>Graphs directory</a></b>\n') html_file.write(' : <b><a href=\'rawdata/\'>CSVs directory</a></b><br>\n') start = appliance_results.keys()[0] end = appliance_results.keys()[-1] timediff = end - start total_proc_count = 0 for proc_name in process_results: total_proc_count += len(process_results[proc_name].keys()) growth = appliance_results[end]['used'] - appliance_results[start]['used'] max_used_memory = 0 for ts in appliance_results: if appliance_results[ts]['used'] > max_used_memory: max_used_memory = appliance_results[ts]['used'] html_file.write('<table border="1">\n') html_file.write('<tr><td>\n') # Appliance Wide Results html_file.write('<table style="width:100%" border="1">\n') html_file.write('<tr>\n') html_file.write('<td><b>Version</b></td>\n') html_file.write('<td><b>Start Time</b></td>\n') html_file.write('<td><b>End Time</b></td>\n') html_file.write('<td><b>Total Test Time</b></td>\n') html_file.write('<td><b>Total Memory</b></td>\n') html_file.write('<td><b>Start Used Memory</b></td>\n') html_file.write('<td><b>End Used Memory</b></td>\n') html_file.write('<td><b>Used Memory Growth</b></td>\n') html_file.write('<td><b>Max Used Memory</b></td>\n') html_file.write('<td><b>Total Tracked Processes</b></td>\n') html_file.write('</tr>\n') html_file.write('<td><a href=\'rawdata/appliance.csv\'>{}</a></td>\n'.format( version_string)) html_file.write('<td>{}</td>\n'.format(start.replace(microsecond=0))) html_file.write('<td>{}</td>\n'.format(end.replace(microsecond=0))) html_file.write('<td>{}</td>\n'.format(unicode(timediff).partition('.')[0])) html_file.write('<td>{}</td>\n'.format(round(appliance_results[end]['total'], 2))) html_file.write('<td>{}</td>\n'.format(round(appliance_results[start]['used'], 2))) html_file.write('<td>{}</td>\n'.format(round(appliance_results[end]['used'], 2))) html_file.write('<td>{}</td>\n'.format(round(growth, 2))) html_file.write('<td>{}</td>\n'.format(round(max_used_memory, 2))) html_file.write('<td>{}</td>\n'.format(total_proc_count)) html_file.write('</table>\n') # CFME/Miq Worker Results html_file.write('<table style="width:100%" border="1">\n') html_file.write('<tr>\n') html_file.write('<td><b>Total CFME/Miq Workers</b></td>\n') html_file.write('<td><b>End Running Workers</b></td>\n') html_file.write('<td><b>Recycled Workers</b></td>\n') html_file.write('<td><b>End Total Worker RSS</b></td>\n') html_file.write('<td><b>End Total Worker PSS</b></td>\n') html_file.write('<td><b>End Total Worker USS</b></td>\n') html_file.write('<td><b>End Total Worker VSS</b></td>\n') html_file.write('<td><b>End Total Worker SWAP</b></td>\n') html_file.write('</tr>\n') a_pids, r_pids, t_rss, t_pss, t_uss, t_vss, t_swap = compile_per_process_results( miq_workers, process_results, end) html_file.write('<tr>\n') html_file.write('<td>{}</td>\n'.format(a_pids + r_pids)) html_file.write('<td>{}</td>\n'.format(a_pids)) html_file.write('<td>{}</td>\n'.format(r_pids)) html_file.write('<td>{}</td>\n'.format(round(t_rss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_pss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_uss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_vss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_swap, 2))) html_file.write('</tr>\n') html_file.write('</table>\n') # Per Process Summaries: html_file.write('<table style="width:100%" border="1">\n') html_file.write('<tr>\n') html_file.write('<td><b>Application/Process Group</b></td>\n') html_file.write('<td><b>Total Processes</b></td>\n') html_file.write('<td><b>End Running Processes</b></td>\n') html_file.write('<td><b>Recycled Processes</b></td>\n') html_file.write('<td><b>End Total Process RSS</b></td>\n') html_file.write('<td><b>End Total Process PSS</b></td>\n') html_file.write('<td><b>End Total Process USS</b></td>\n') html_file.write('<td><b>End Total Process VSS</b></td>\n') html_file.write('<td><b>End Total Process SWAP</b></td>\n') html_file.write('</tr>\n') a_pids, r_pids, t_rss, t_pss, t_uss, t_vss, t_swap = compile_per_process_results( ruby_processes, process_results, end) t_a_pids = a_pids t_r_pids = r_pids tt_rss = t_rss tt_pss = t_pss tt_uss = t_uss tt_vss = t_vss tt_swap = t_swap html_file.write('<tr>\n') html_file.write('<td>ruby</td>\n') html_file.write('<td>{}</td>\n'.format(a_pids + r_pids)) html_file.write('<td>{}</td>\n'.format(a_pids)) html_file.write('<td>{}</td>\n'.format(r_pids)) html_file.write('<td>{}</td>\n'.format(round(t_rss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_pss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_uss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_vss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_swap, 2))) html_file.write('</tr>\n') # memcached Summary a_pids, r_pids, t_rss, t_pss, t_uss, t_vss, t_swap = compile_per_process_results( ['memcached'], process_results, end) t_a_pids += a_pids t_r_pids += r_pids tt_rss += t_rss tt_pss += t_pss tt_uss += t_uss tt_vss += t_vss tt_swap += t_swap html_file.write('<tr>\n') html_file.write('<td>memcached</td>\n') html_file.write('<td>{}</td>\n'.format(a_pids + r_pids)) html_file.write('<td>{}</td>\n'.format(a_pids)) html_file.write('<td>{}</td>\n'.format(r_pids)) html_file.write('<td>{}</td>\n'.format(round(t_rss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_pss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_uss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_vss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_swap, 2))) html_file.write('</tr>\n') # Postgres Summary a_pids, r_pids, t_rss, t_pss, t_uss, t_vss, t_swap = compile_per_process_results( ['postgres'], process_results, end) t_a_pids += a_pids t_r_pids += r_pids tt_rss += t_rss tt_pss += t_pss tt_uss += t_uss tt_vss += t_vss tt_swap += t_swap html_file.write('<tr>\n') html_file.write('<td>postgres</td>\n') html_file.write('<td>{}</td>\n'.format(a_pids + r_pids)) html_file.write('<td>{}</td>\n'.format(a_pids)) html_file.write('<td>{}</td>\n'.format(r_pids)) html_file.write('<td>{}</td>\n'.format(round(t_rss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_pss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_uss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_vss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_swap, 2))) html_file.write('</tr>\n') # httpd Summary a_pids, r_pids, t_rss, t_pss, t_uss, t_vss, t_swap = compile_per_process_results(['httpd'], process_results, end) t_a_pids += a_pids t_r_pids += r_pids tt_rss += t_rss tt_pss += t_pss tt_uss += t_uss tt_vss += t_vss tt_swap += t_swap html_file.write('<tr>\n') html_file.write('<td>httpd</td>\n') html_file.write('<td>{}</td>\n'.format(a_pids + r_pids)) html_file.write('<td>{}</td>\n'.format(a_pids)) html_file.write('<td>{}</td>\n'.format(r_pids)) html_file.write('<td>{}</td>\n'.format(round(t_rss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_pss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_uss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_vss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_swap, 2))) html_file.write('</tr>\n') # collectd Summary a_pids, r_pids, t_rss, t_pss, t_uss, t_vss, t_swap = compile_per_process_results( ['collectd'], process_results, end) t_a_pids += a_pids t_r_pids += r_pids tt_rss += t_rss tt_pss += t_pss tt_uss += t_uss tt_vss += t_vss tt_swap += t_swap html_file.write('<tr>\n') html_file.write('<td>collectd</td>\n') html_file.write('<td>{}</td>\n'.format(a_pids + r_pids)) html_file.write('<td>{}</td>\n'.format(a_pids)) html_file.write('<td>{}</td>\n'.format(r_pids)) html_file.write('<td>{}</td>\n'.format(round(t_rss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_pss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_uss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_vss, 2))) html_file.write('<td>{}</td>\n'.format(round(t_swap, 2))) html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>total</td>\n') html_file.write('<td>{}</td>\n'.format(t_a_pids + t_r_pids)) html_file.write('<td>{}</td>\n'.format(t_a_pids)) html_file.write('<td>{}</td>\n'.format(t_r_pids)) html_file.write('<td>{}</td>\n'.format(round(tt_rss, 2))) html_file.write('<td>{}</td>\n'.format(round(tt_pss, 2))) html_file.write('<td>{}</td>\n'.format(round(tt_uss, 2))) html_file.write('<td>{}</td>\n'.format(round(tt_vss, 2))) html_file.write('<td>{}</td>\n'.format(round(tt_swap, 2))) html_file.write('</tr>\n') html_file.write('</table>\n') # Appliance Graph html_file.write('</td></tr><tr><td>\n') file_name = '{}-appliance_memory.png'.format(version_string) html_file.write('<img src=\'graphs/{}\'>\n'.format(file_name)) file_name = '{}-appliance_swap.png'.format(version_string) # Check for swap usage through out time frame: max_swap_used = 0 for ts in appliance_results: swap_used = appliance_results[ts]['swap_total'] - appliance_results[ts]['swap_free'] if swap_used > max_swap_used: max_swap_used = swap_used if max_swap_used < 10: # Less than 10MiB Max, then hide graph html_file.write('<br><a href=\'graphs/{}\'>Swap Graph '.format(file_name)) html_file.write('(Hidden, max_swap_used < 10 MiB)</a>\n') else: html_file.write('<img src=\'graphs/{}\'>\n'.format(file_name)) html_file.write('</td></tr><tr><td>\n') # Per Process Results html_file.write('<table style="width:100%" border="1"><tr>\n') html_file.write('<td><b>Process Name</b></td>\n') html_file.write('<td><b>Process Pid</b></td>\n') html_file.write('<td><b>Start Time</b></td>\n') html_file.write('<td><b>End Time</b></td>\n') html_file.write('<td><b>Time Alive</b></td>\n') html_file.write('<td><b>RSS Mem Start</b></td>\n') html_file.write('<td><b>RSS Mem End</b></td>\n') html_file.write('<td><b>RSS Mem Change</b></td>\n') html_file.write('<td><b>PSS Mem Start</b></td>\n') html_file.write('<td><b>PSS Mem End</b></td>\n') html_file.write('<td><b>PSS Mem Change</b></td>\n') html_file.write('<td><b>CSV</b></td>\n') html_file.write('</tr>\n') # By Worker Type Memory Used for ordered_name in process_order: if ordered_name in process_results: for pid in process_results[ordered_name]: start = process_results[ordered_name][pid].keys()[0] end = process_results[ordered_name][pid].keys()[-1] timediff = end - start html_file.write('<tr>\n') if len(process_results[ordered_name]) > 1: html_file.write('<td><a href=\'#{}\'>{}</a></td>\n'.format(ordered_name, ordered_name)) html_file.write('<td><a href=\'graphs/{}-{}.png\'>{}</a></td>\n'.format( ordered_name, pid, pid)) else: html_file.write('<td>{}</td>\n'.format(ordered_name)) html_file.write('<td><a href=\'#{}-{}.png\'>{}</a></td>\n'.format( ordered_name, pid, pid)) html_file.write('<td>{}</td>\n'.format(start.replace(microsecond=0))) html_file.write('<td>{}</td>\n'.format(end.replace(microsecond=0))) html_file.write('<td>{}</td>\n'.format(unicode(timediff).partition('.')[0])) rss_change = process_results[ordered_name][pid][end]['rss'] - \ process_results[ordered_name][pid][start]['rss'] html_file.write('<td>{}</td>\n'.format( round(process_results[ordered_name][pid][start]['rss'], 2))) html_file.write('<td>{}</td>\n'.format( round(process_results[ordered_name][pid][end]['rss'], 2))) html_file.write('<td>{}</td>\n'.format(round(rss_change, 2))) pss_change = process_results[ordered_name][pid][end]['pss'] - \ process_results[ordered_name][pid][start]['pss'] html_file.write('<td>{}</td>\n'.format( round(process_results[ordered_name][pid][start]['pss'], 2))) html_file.write('<td>{}</td>\n'.format( round(process_results[ordered_name][pid][end]['pss'], 2))) html_file.write('<td>{}</td>\n'.format(round(pss_change, 2))) html_file.write('<td><a href=\'rawdata/{}-{}.csv\'>csv</a></td>\n'.format( pid, ordered_name)) html_file.write('</tr>\n') else: logger.debug('Process/Worker not part of test: {}'.format(ordered_name)) html_file.write('</table>\n') # Worker Graphs for ordered_name in process_order: if ordered_name in process_results: html_file.write('<tr><td>\n') html_file.write('<div id=\'{}\'>Process name: {}</div><br>\n'.format( ordered_name, ordered_name)) if len(process_results[ordered_name]) > 1: file_name = '{}-all.png'.format(ordered_name) html_file.write('<img id=\'{}\' src=\'graphs/{}\'><br>\n'.format(file_name, file_name)) else: for pid in sorted(process_results[ordered_name]): file_name = '{}-{}.png'.format(ordered_name, pid) html_file.write('<img id=\'{}\' src=\'graphs/{}\'><br>\n'.format( file_name, file_name)) html_file.write('</td></tr>\n') html_file.write('</table>\n') html_file.write('</body>\n') html_file.write('</html>\n') timediff = time.time() - starttime logger.info('Generated Summary html in: {}'.format(timediff)) def generate_workload_html(directory, ver, scenario_data, provider_names, grafana_urls): starttime = time.time() file_name = str(directory.join('workload.html')) with open(file_name, 'w') as html_file: html_file.write('<html>\n') html_file.write('<head><title>{} - {}</title></head>'.format( scenario_data['test_name'], provider_names)) html_file.write('<body>\n') html_file.write('<b>CFME {} {} Test Results</b><br>\n'.format(ver, scenario_data['test_name'].title())) html_file.write('<b>Appliance Roles:</b> {}<br>\n'.format( scenario_data['appliance_roles'].replace(',', ', '))) html_file.write('<b>Provider(s):</b> {}<br>\n'.format(provider_names)) html_file.write('<b><a href=\'https://{}/\' target="_blank">{}</a></b>\n'.format( scenario_data['appliance_ip'], scenario_data['appliance_name'])) if grafana_urls: for g_name in sorted(grafana_urls.keys()): html_file.write( ' : <b><a href=\'{}\' target="_blank">{}</a></b>'.format(grafana_urls[g_name], g_name)) html_file.write('<br>\n') html_file.write('<b><a href=\'{}-summary.csv\'>Summary CSV</a></b>'.format(ver)) html_file.write(' : <b><a href=\'index.html\'>Memory Info</a></b>') html_file.write(' : <b><a href=\'graphs/\'>Graphs directory</a></b>\n') html_file.write(' : <b><a href=\'rawdata/\'>CSVs directory</a></b><br>\n') html_file.write('<br><b>Scenario Data: </b><br>\n') yaml_html = get_scenario_html(scenario_data['scenario']) html_file.write(yaml_html + '\n') html_file.write('<br>\n<br>\n<br>\n<b>Quantifier Data: </b>\n<br>\n<br>\n<br>\n<br>\n') html_file.write('<table border="1">\n') html_file.write('<tr>\n') html_file.write('<td><b><font size="4"> System Information</font></b></td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>\n') system_path = ('../version_info/system.csv') html_file.write('<a href="{}" download="System_Versions-{}-{}"> System Versions</a>' .format(system_path, test_ts, scenario_data['scenario']['name'])) html_file.write('</td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>&nbsp</td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>&nbsp</td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td><b><font size="4"> Process Information</font></b></td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>\n') process_path = ('../version_info/processes.csv') html_file.write('<a href="{}" download="Process_Versions-{}-{}"> Process Versions</a>' .format(process_path, test_ts, scenario_data['scenario']['name'])) html_file.write('</td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>&nbsp</td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>&nbsp</td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td><b><font size="4"> Ruby Gem Information</font></b></td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>\n') gems_path = ('../version_info/gems.csv') html_file.write('<a href="{}" download="Gem_Versions-{}-{}"> Ruby Gem Versions</a>' .format(gems_path, test_ts, scenario_data['scenario']['name'])) html_file.write('</td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>&nbsp</td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>&nbsp</td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td><b><font size="4"> RPM Information</font></b></td>\n') html_file.write('</tr>\n') html_file.write('<tr>\n') html_file.write('<td>\n') rpms_path = ('../version_info/rpms.csv') html_file.write('<a href="{}" download="RPM_Versions-{}-{}"> RPM Versions</a>' .format(rpms_path, test_ts, scenario_data['scenario']['name'])) html_file.write('</td>\n') html_file.write('</tr>\n') html_file.write('</table>\n') html_file.write('</body>\n') html_file.write('</html>\n') timediff = time.time() - starttime logger.info('Generated Workload html in: {}'.format(timediff)) def add_workload_quantifiers(quantifiers, scenario_data): starttime = time.time() ver = current_version() workload_path = results_path.join('{}-{}-{}'.format(test_ts, scenario_data['test_dir'], ver)) directory = workload_path.join(scenario_data['scenario']['name']) file_name = str(directory.join('workload.html')) marker = '<b>Quantifier Data: </b>' yaml_dict = quantifiers yaml_string = str(json.dumps(yaml_dict, indent=4)) yaml_html = yaml_string.replace('\n', '<br>\n') with open(file_name, 'r+') as html_file: line = '' while marker not in line: line = html_file.readline() marker_pos = html_file.tell() remainder = html_file.read() html_file.seek(marker_pos) html_file.write('{} \n'.format(yaml_html)) html_file.write(remainder) timediff = time.time() - starttime logger.info('Added quantifiers in: {}'.format(timediff)) def get_scenario_html(scenario_data): scenario_dict = create_dict(scenario_data) scenario_yaml = yaml.dump(scenario_dict) scenario_html = scenario_yaml.replace('\n', '<br>\n') scenario_html = scenario_html.replace(', ', '<br>\n &nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;') scenario_html = scenario_html.replace(' ', '&nbsp;') scenario_html = scenario_html.replace('[', '<br>\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;') scenario_html = scenario_html.replace(']', '\n') return scenario_html def create_dict(attr_dict): main_dict = dict(attr_dict) for key, value in main_dict.iteritems(): if type(value) == AttrDict: main_dict[key] = create_dict(value) return main_dict def graph_appliance_measurements(graphs_path, ver, appliance_results, use_slab, provider_names): starttime = time.time() dates = appliance_results.keys() total_memory_list = list(appliance_results[ts]['total'] for ts in appliance_results.keys()) free_memory_list = list(appliance_results[ts]['free'] for ts in appliance_results.keys()) used_memory_list = list(appliance_results[ts]['used'] for ts in appliance_results.keys()) buffers_memory_list = list( appliance_results[ts]['buffers'] for ts in appliance_results.keys()) cache_memory_list = list(appliance_results[ts]['cached'] for ts in appliance_results.keys()) slab_memory_list = list(appliance_results[ts]['slab'] for ts in appliance_results.keys()) swap_total_list = list(appliance_results[ts]['swap_total'] for ts in appliance_results.keys()) swap_free_list = list(appliance_results[ts]['swap_free'] for ts in appliance_results.keys()) # Stack Plot Memory Usage file_name = graphs_path.join('{}-appliance_memory.png'.format(ver)) mpl.rcParams['axes.prop_cycle'] = cycler('color', ['firebrick', 'coral', 'steelblue', 'forestgreen']) fig, ax = plt.subplots() plt.title('Provider(s): {}\nAppliance Memory'.format(provider_names)) plt.xlabel('Date / Time') plt.ylabel('Memory (MiB)') if use_slab: y = [used_memory_list, slab_memory_list, cache_memory_list, free_memory_list] else: y = [used_memory_list, buffers_memory_list, cache_memory_list, free_memory_list] plt.stackplot(dates, *y, baseline='zero') ax.annotate(str(round(total_memory_list[0], 2)), xy=(dates[0], total_memory_list[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(total_memory_list[-1], 2)), xy=(dates[-1], total_memory_list[-1]), xytext=(4, -4), textcoords='offset points') if use_slab: ax.annotate(str(round(slab_memory_list[0], 2)), xy=(dates[0], used_memory_list[0] + slab_memory_list[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(slab_memory_list[-1], 2)), xy=(dates[-1], used_memory_list[-1] + slab_memory_list[-1]), xytext=(4, -4), textcoords='offset points') ax.annotate(str(round(cache_memory_list[0], 2)), xy=(dates[0], used_memory_list[0] + slab_memory_list[0] + cache_memory_list[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(cache_memory_list[-1], 2)), xy=( dates[-1], used_memory_list[-1] + slab_memory_list[-1] + cache_memory_list[-1]), xytext=(4, -4), textcoords='offset points') else: ax.annotate(str(round(buffers_memory_list[0], 2)), xy=( dates[0], used_memory_list[0] + buffers_memory_list[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(buffers_memory_list[-1], 2)), xy=(dates[-1], used_memory_list[-1] + buffers_memory_list[-1]), xytext=(4, -4), textcoords='offset points') ax.annotate(str(round(cache_memory_list[0], 2)), xy=(dates[0], used_memory_list[0] + buffers_memory_list[0] + cache_memory_list[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(cache_memory_list[-1], 2)), xy=( dates[-1], used_memory_list[-1] + buffers_memory_list[-1] + cache_memory_list[-1]), xytext=(4, -4), textcoords='offset points') ax.annotate(str(round(used_memory_list[0], 2)), xy=(dates[0], used_memory_list[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(used_memory_list[-1], 2)), xy=(dates[-1], used_memory_list[-1]), xytext=(4, -4), textcoords='offset points') datefmt = mdates.DateFormatter('%m-%d %H-%M') ax.xaxis.set_major_formatter(datefmt) ax.grid(True) p1 = plt.Rectangle((0, 0), 1, 1, fc='firebrick') p2 = plt.Rectangle((0, 0), 1, 1, fc='coral') p3 = plt.Rectangle((0, 0), 1, 1, fc='steelblue') p4 = plt.Rectangle((0, 0), 1, 1, fc='forestgreen') if use_slab: ax.legend([p1, p2, p3, p4], ['Used', 'Slab', 'Cached', 'Free'], bbox_to_anchor=(1.45, 0.22), fancybox=True) else: ax.legend([p1, p2, p3, p4], ['Used', 'Buffers', 'Cached', 'Free'], bbox_to_anchor=(1.45, 0.22), fancybox=True) fig.autofmt_xdate() plt.savefig(str(file_name), bbox_inches='tight') plt.close() # Stack Plot Swap usage mpl.rcParams['axes.prop_cycle'] = cycler('color', ['firebrick', 'forestgreen']) file_name = graphs_path.join('{}-appliance_swap.png'.format(ver)) fig, ax = plt.subplots() plt.title('Provider(s): {}\nAppliance Swap'.format(provider_names)) plt.xlabel('Date / Time') plt.ylabel('Swap (MiB)') swap_used_list = [t - f for f, t in zip(swap_free_list, swap_total_list)] y = [swap_used_list, swap_free_list] plt.stackplot(dates, *y, baseline='zero') ax.annotate(str(round(swap_total_list[0], 2)), xy=(dates[0], swap_total_list[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(swap_total_list[-1], 2)), xy=(dates[-1], swap_total_list[-1]), xytext=(4, -4), textcoords='offset points') ax.annotate(str(round(swap_used_list[0], 2)), xy=(dates[0], swap_used_list[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(swap_used_list[-1], 2)), xy=(dates[-1], swap_used_list[-1]), xytext=(4, -4), textcoords='offset points') datefmt = mdates.DateFormatter('%m-%d %H-%M') ax.xaxis.set_major_formatter(datefmt) ax.grid(True) p1 = plt.Rectangle((0, 0), 1, 1, fc='firebrick') p2 = plt.Rectangle((0, 0), 1, 1, fc='forestgreen') ax.legend([p1, p2], ['Used Swap', 'Free Swap'], bbox_to_anchor=(1.45, 0.22), fancybox=True) fig.autofmt_xdate() plt.savefig(str(file_name), bbox_inches='tight') plt.close() # Reset Colors mpl.rcdefaults() timediff = time.time() - starttime logger.info('Plotted Appliance Memory in: {}'.format(timediff)) def graph_all_miq_workers(graph_file_path, process_results, provider_names): starttime = time.time() file_name = graph_file_path.join('all-processes.png') fig, ax = plt.subplots() plt.title('Provider(s): {}\nAll Workers/Monitored Processes'.format(provider_names)) plt.xlabel('Date / Time') plt.ylabel('Memory (MiB)') for process_name in process_results: if 'Worker' in process_name or 'Handler' in process_name or 'Catcher' in process_name: for process_pid in process_results[process_name]: dates = process_results[process_name][process_pid].keys() rss_samples = list(process_results[process_name][process_pid][ts]['rss'] for ts in process_results[process_name][process_pid].keys()) vss_samples = list(process_results[process_name][process_pid][ts]['vss'] for ts in process_results[process_name][process_pid].keys()) plt.plot(dates, rss_samples, linewidth=1, label='{} {} RSS'.format(process_pid, process_name)) plt.plot(dates, vss_samples, linewidth=1, label='{} {} VSS'.format( process_pid, process_name)) datefmt = mdates.DateFormatter('%m-%d %H-%M') ax.xaxis.set_major_formatter(datefmt) ax.grid(True) plt.legend(loc='upper center', bbox_to_anchor=(1.2, 0.1), fancybox=True) fig.autofmt_xdate() plt.savefig(str(file_name), bbox_inches='tight') plt.close() timediff = time.time() - starttime logger.info('Plotted All Type/Process Memory in: {}'.format(timediff)) def graph_individual_process_measurements(graph_file_path, process_results, provider_names): starttime = time.time() for process_name in process_results: for process_pid in process_results[process_name]: file_name = graph_file_path.join('{}-{}.png'.format(process_name, process_pid)) dates = process_results[process_name][process_pid].keys() rss_samples = list(process_results[process_name][process_pid][ts]['rss'] for ts in process_results[process_name][process_pid].keys()) pss_samples = list(process_results[process_name][process_pid][ts]['pss'] for ts in process_results[process_name][process_pid].keys()) uss_samples = list(process_results[process_name][process_pid][ts]['uss'] for ts in process_results[process_name][process_pid].keys()) vss_samples = list(process_results[process_name][process_pid][ts]['vss'] for ts in process_results[process_name][process_pid].keys()) swap_samples = list(process_results[process_name][process_pid][ts]['swap'] for ts in process_results[process_name][process_pid].keys()) fig, ax = plt.subplots() plt.title('Provider(s)/Size: {}\nProcess/Worker: {}\nPID: {}'.format(provider_names, process_name, process_pid)) plt.xlabel('Date / Time') plt.ylabel('Memory (MiB)') plt.plot(dates, rss_samples, linewidth=1, label='RSS') plt.plot(dates, pss_samples, linewidth=1, label='PSS') plt.plot(dates, uss_samples, linewidth=1, label='USS') plt.plot(dates, vss_samples, linewidth=1, label='VSS') plt.plot(dates, swap_samples, linewidth=1, label='Swap') if rss_samples: ax.annotate(str(round(rss_samples[0], 2)), xy=(dates[0], rss_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(rss_samples[-1], 2)), xy=(dates[-1], rss_samples[-1]), xytext=(4, -4), textcoords='offset points') if pss_samples: ax.annotate(str(round(pss_samples[0], 2)), xy=(dates[0], pss_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(pss_samples[-1], 2)), xy=(dates[-1], pss_samples[-1]), xytext=(4, -4), textcoords='offset points') if uss_samples: ax.annotate(str(round(uss_samples[0], 2)), xy=(dates[0], uss_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(uss_samples[-1], 2)), xy=(dates[-1], uss_samples[-1]), xytext=(4, -4), textcoords='offset points') if vss_samples: ax.annotate(str(round(vss_samples[0], 2)), xy=(dates[0], vss_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(vss_samples[-1], 2)), xy=(dates[-1], vss_samples[-1]), xytext=(4, -4), textcoords='offset points') if swap_samples: ax.annotate(str(round(swap_samples[0], 2)), xy=(dates[0], swap_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(swap_samples[-1], 2)), xy=(dates[-1], swap_samples[-1]), xytext=(4, -4), textcoords='offset points') datefmt = mdates.DateFormatter('%m-%d %H-%M') ax.xaxis.set_major_formatter(datefmt) ax.grid(True) plt.legend(loc='upper center', bbox_to_anchor=(1.2, 0.1), fancybox=True) fig.autofmt_xdate() plt.savefig(str(file_name), bbox_inches='tight') plt.close() timediff = time.time() - starttime logger.info('Plotted Individual Process Memory in: {}'.format(timediff)) def graph_same_miq_workers(graph_file_path, process_results, provider_names): starttime = time.time() for process_name in process_results: if len(process_results[process_name]) > 1: logger.debug('Plotting {} {} processes on single graph.'.format( len(process_results[process_name]), process_name)) file_name = graph_file_path.join('{}-all.png'.format(process_name)) fig, ax = plt.subplots() pids = 'PIDs: ' for i, pid in enumerate(process_results[process_name], 1): pids = '{}{}'.format(pids, '{},{}'.format(pid, [' ', '\n'][i % 6 == 0])) pids = pids[0:-2] plt.title('Provider: {}\nProcess/Worker: {}\n{}'.format(provider_names, process_name, pids)) plt.xlabel('Date / Time') plt.ylabel('Memory (MiB)') for process_pid in process_results[process_name]: dates = process_results[process_name][process_pid].keys() rss_samples = list(process_results[process_name][process_pid][ts]['rss'] for ts in process_results[process_name][process_pid].keys()) pss_samples = list(process_results[process_name][process_pid][ts]['pss'] for ts in process_results[process_name][process_pid].keys()) uss_samples = list(process_results[process_name][process_pid][ts]['uss'] for ts in process_results[process_name][process_pid].keys()) vss_samples = list(process_results[process_name][process_pid][ts]['vss'] for ts in process_results[process_name][process_pid].keys()) swap_samples = list(process_results[process_name][process_pid][ts]['swap'] for ts in process_results[process_name][process_pid].keys()) plt.plot(dates, rss_samples, linewidth=1, label='{} RSS'.format(process_pid)) plt.plot(dates, pss_samples, linewidth=1, label='{} PSS'.format(process_pid)) plt.plot(dates, uss_samples, linewidth=1, label='{} USS'.format(process_pid)) plt.plot(dates, vss_samples, linewidth=1, label='{} VSS'.format(process_pid)) plt.plot(dates, swap_samples, linewidth=1, label='{} SWAP'.format(process_pid)) if rss_samples: ax.annotate(str(round(rss_samples[0], 2)), xy=(dates[0], rss_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(rss_samples[-1], 2)), xy=(dates[-1], rss_samples[-1]), xytext=(4, -4), textcoords='offset points') if pss_samples: ax.annotate(str(round(pss_samples[0], 2)), xy=(dates[0], pss_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(pss_samples[-1], 2)), xy=(dates[-1], pss_samples[-1]), xytext=(4, -4), textcoords='offset points') if uss_samples: ax.annotate(str(round(uss_samples[0], 2)), xy=(dates[0], uss_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(uss_samples[-1], 2)), xy=(dates[-1], uss_samples[-1]), xytext=(4, -4), textcoords='offset points') if vss_samples: ax.annotate(str(round(vss_samples[0], 2)), xy=(dates[0], vss_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(vss_samples[-1], 2)), xy=(dates[-1], vss_samples[-1]), xytext=(4, -4), textcoords='offset points') if swap_samples: ax.annotate(str(round(swap_samples[0], 2)), xy=(dates[0], swap_samples[0]), xytext=(4, 4), textcoords='offset points') ax.annotate(str(round(swap_samples[-1], 2)), xy=(dates[-1], swap_samples[-1]), xytext=(4, -4), textcoords='offset points') datefmt = mdates.DateFormatter('%m-%d %H-%M') ax.xaxis.set_major_formatter(datefmt) ax.grid(True) plt.legend(loc='upper center', bbox_to_anchor=(1.2, 0.1), fancybox=True) fig.autofmt_xdate() plt.savefig(str(file_name), bbox_inches='tight') plt.close() timediff = time.time() - starttime logger.info('Plotted Same Type/Process Memory in: {}'.format(timediff)) def summary_csv_measurement_dump(csv_file, process_results, measurement): csv_file.write('---------------------------------------------\n') csv_file.write('Per Process {} Memory Usage\n'.format(measurement.upper())) csv_file.write('---------------------------------------------\n') csv_file.write('Process/Worker Type,PID,Start of test,End of test\n') for ordered_name in process_order: if ordered_name in process_results: for process_pid in sorted(process_results[ordered_name]): start = process_results[ordered_name][process_pid].keys()[0] end = process_results[ordered_name][process_pid].keys()[-1] csv_file.write('{},{},{},{}\n'.format(ordered_name, process_pid, round(process_results[ordered_name][process_pid][start][measurement], 2), round(process_results[ordered_name][process_pid][end][measurement], 2)))
# -*- coding: utf-8 -*- """ Tests checking the basic functionality of the Control/Explorer section. Whether we can create/update/delete/assign/... these objects. Nothing with deep meaning. Can be also used as a unit-test for page model coverage. """ import random from collections import namedtuple import fauxfactory import pytest from cfme import test_requirements from cfme.control.explorer import alert_profiles, conditions, policies from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.blockers import BZ from cfme.utils.update import update from cfme.utils.version import current_version pytestmark = [ pytest.mark.long_running, test_requirements.control ] EXPRESSIONS_TO_TEST = [ ( "Field", "fill_field({} : Last Compliance Timestamp, BEFORE, 03/04/2014)", '{} : Last Compliance Timestamp BEFORE "03/04/2014 00:00"' ), ( "Count", "fill_count({}.Compliance History, >, 0)", 'COUNT OF {}.Compliance History > 0' ), ( "Tag", "fill_tag({}.User.My Company Tags : Location, Chicago)", "{}.User.My Company Tags : Location CONTAINS 'Chicago'" ), ( "Find", "fill_find({}.Compliance History : Event Type, INCLUDES, some_string, Check Any," "Resource Type, =, another_string)", 'FIND {}.Compliance History : Event Type INCLUDES "some_string" CHECK ANY Resource Type' ' = "another_string"' ) ] COMPLIANCE_POLICIES = [ policies.HostCompliancePolicy, policies.VMCompliancePolicy, policies.ReplicatorCompliancePolicy, policies.PodCompliancePolicy, policies.ContainerNodeCompliancePolicy, policies.ContainerImageCompliancePolicy, ] CONTROL_POLICIES = [ policies.HostControlPolicy, policies.VMControlPolicy, policies.ReplicatorControlPolicy, policies.PodControlPolicy, policies.ContainerNodeControlPolicy, policies.ContainerImageControlPolicy ] POLICIES = COMPLIANCE_POLICIES + CONTROL_POLICIES CONDITIONS = [ conditions.HostCondition, conditions.VMCondition, conditions.ReplicatorCondition, conditions.PodCondition, conditions.ContainerNodeCondition, conditions.ContainerImageCondition, conditions.ProviderCondition ] PolicyAndCondition = namedtuple('PolicyAndCondition', ['name', 'policy', 'condition']) POLICIES_AND_CONDITIONS = [ PolicyAndCondition(name=obj[0].__name__, policy=obj[0], condition=obj[1]) for obj in zip(CONTROL_POLICIES, CONDITIONS) ] EVENTS = [ "Datastore Analysis Complete", "Datastore Analysis Request", "Host Auth Changed", "Host Auth Error", "Host Auth Incomplete Credentials", "Host Auth Invalid", "Host Auth Unreachable", "Host Auth Valid", "Provider Auth Changed", "Provider Auth Error", "Provider Auth Incomplete Credentials", "Provider Auth Invalid", "Provider Auth Unreachable", "Provider Auth Valid", "Tag Complete", "Tag Parent Cluster Complete", "Tag Parent Datastore Complete", "Tag Parent Host Complete", "Tag Parent Resource Pool Complete", "Tag Request", "Un-Tag Complete", "Un-Tag Parent Cluster Complete", "Un-Tag Parent Datastore Complete", "Un-Tag Parent Host Complete", "Un-Tag Parent Resource Pool Complete", "Un-Tag Request", "Container Image Compliance Failed", "Container Image Compliance Passed", "Container Node Compliance Failed", "Container Node Compliance Passed", "Host Compliance Failed", "Host Compliance Passed", "Pod Compliance Failed", "Pod Compliance Passed", "Replicator Compliance Failed", "Replicator Compliance Passed", "VM Compliance Failed", "VM Compliance Passed", "Container Image Analysis Complete", "Container Image Discovered", "Container Node Failed Mount", "Container Node Invalid Disk Capacity", "Container Node Not Ready", "Container Node Not Schedulable", "Container Node Ready", "Container Node Rebooted", "Container Node Schedulable", "Pod Deadline Exceeded", "Pod Failed Scheduling", "Pod Failed Sync", "Pod Failed Validation", "Pod Insufficient Free CPU", "Pod Insufficient Free Memory", "Pod Out of Disk", "Pod Scheduled", "Pod hostPort Conflict", "Pod nodeSelector Mismatching", "Replicator Failed Creating Pod", "Replicator Successfully Created Pod", "Host Added to Cluster", "Host Analysis Complete", "Host Analysis Request", "Host Connect", "Host Disconnect", "Host Maintenance Enter Request", "Host Maintenance Exit Request", "Host Provision Complete", "Host Reboot Request", "Host Removed from Cluster", "Host Reset Request", "Host Shutdown Request", "Host Standby Request", "Host Start Request", "Host Stop Request", "Host Vmotion Disable Request", "Host Vmotion Enable Request", "Service Provision Complete", "Service Retire Request", "Service Retired", "Service Retirement Warning", "Service Start Request", "Service Started", "Service Stop Request", "Service Stopped", "VM Clone Complete", "VM Clone Start", "VM Create Complete", "VM Delete (from Disk) Request", "VM Renamed Event", "VM Settings Change", "VM Template Create Complete", "VM Provision Complete", "VM Retire Request", "VM Retired", "VM Retirement Warning", "VM Analysis Complete", "VM Analysis Failure", "VM Analysis Request", "VM Analysis Start", "VM Guest Reboot", "VM Guest Reboot Request", "VM Guest Shutdown", "VM Guest Shutdown Request", "VM Live Migration (VMOTION)", "VM Pause", "VM Pause Request", "VM Power Off", "VM Power Off Request", "VM Power On", "VM Power On Request", "VM Remote Console Connected", "VM Removal from Inventory", "VM Removal from Inventory Request", "VM Reset", "VM Reset Request", "VM Resume", "VM Shelve", "VM Shelve Offload", "VM Shelve Offload Request", "VM Shelve Request", "VM Snapshot Create Complete", "VM Snapshot Create Request", "VM Snapshot Create Started", "VM Standby of Guest", "VM Standby of Guest Request", "VM Suspend", "VM Suspend Request" ] ALERT_PROFILES = [ alert_profiles.ClusterAlertProfile, alert_profiles.DatastoreAlertProfile, alert_profiles.HostAlertProfile, alert_profiles.ProviderAlertProfile, alert_profiles.ServerAlertProfile, alert_profiles.VMInstanceAlertProfile ] @pytest.fixture(scope="module") def policy_profile_collection(appliance): return appliance.collections.policy_profiles @pytest.fixture(scope="module") def policy_collection(appliance): return appliance.collections.policies @pytest.fixture(scope="module") def condition_collection(appliance): return appliance.collections.conditions @pytest.fixture(scope="module") def action_collection(appliance): return appliance.collections.actions @pytest.fixture(scope="module") def alert_collection(appliance): return appliance.collections.alerts @pytest.fixture(scope="module") def alert_profile_collection(appliance): return appliance.collections.alert_profiles @pytest.yield_fixture def two_random_policies(policy_collection): policy_1 = policy_collection.create( random.choice(POLICIES), fauxfactory.gen_alphanumeric() ) policy_2 = policy_collection.create( random.choice(POLICIES), fauxfactory.gen_alphanumeric() ) yield policy_1, policy_2 policy_collection.delete(policy_1, policy_2) @pytest.fixture(params=POLICIES, ids=lambda policy_class: policy_class.__name__) def policy_class(request): return request.param @pytest.fixture(params=ALERT_PROFILES, ids=lambda alert_profile: alert_profile.__name__) def alert_profile_class(request): return request.param @pytest.yield_fixture def policy(policy_collection, policy_class): policy_ = policy_collection.create(policy_class, fauxfactory.gen_alphanumeric()) yield policy_ policy_.delete() @pytest.yield_fixture(params=CONDITIONS, ids=lambda condition_class: condition_class.__name__, scope="module") def condition_for_expressions(request, condition_collection): condition_class = request.param condition = condition_collection.create( condition_class, fauxfactory.gen_alphanumeric(), expression="fill_field({} : Name, IS NOT EMPTY)".format(condition_class.FIELD_VALUE), scope="fill_field({} : Name, INCLUDES, {})".format(condition_class.FIELD_VALUE, fauxfactory.gen_alpha()) ) yield condition condition.delete() @pytest.fixture(params=CONDITIONS, ids=lambda condition_class: condition_class.__name__) def condition_prerequisites(request, condition_collection): condition_class = request.param expression = "fill_field({} : Name, =, {})".format( condition_class.FIELD_VALUE, fauxfactory.gen_alphanumeric() ) scope = "fill_field({} : Name, =, {})".format( condition_class.FIELD_VALUE, fauxfactory.gen_alphanumeric() ) return condition_class, scope, expression @pytest.yield_fixture(params=CONTROL_POLICIES, ids=lambda policy_class: policy_class.__name__) def control_policy(request, policy_collection): policy_class = request.param policy = policy_collection.create(policy_class, fauxfactory.gen_alphanumeric()) yield policy policy.delete() @pytest.yield_fixture def action(action_collection): action_ = action_collection.create( fauxfactory.gen_alphanumeric(), action_type="Tag", action_values={"tag": ("My Company Tags", "Department", "Accounting")} ) yield action_ action_.delete() @pytest.yield_fixture def alert(alert_collection): alert_ = alert_collection.create( fauxfactory.gen_alphanumeric(), based_on=random.choice(ALERT_PROFILES).TYPE, timeline_event=True, driving_event="Hourly Timer" ) yield alert_ alert_.delete() @pytest.yield_fixture def alert_profile(alert_profile_class, alert_collection, alert_profile_collection): alert = alert_collection.create( fauxfactory.gen_alphanumeric(), based_on=alert_profile_class.TYPE, timeline_event=True, driving_event="Hourly Timer" ) alert_profile_ = alert_profile_collection.create( alert_profile_class, fauxfactory.gen_alphanumeric(), alerts=[alert.description] ) yield alert_profile_ alert_profile_.delete() alert.delete() @pytest.yield_fixture(params=POLICIES_AND_CONDITIONS, ids=lambda item: item.name) def policy_and_condition(request, policy_collection, condition_collection): condition_class = request.param.condition policy_class = request.param.policy expression = "fill_field({} : Name, =, {})".format( condition_class.FIELD_VALUE, fauxfactory.gen_alphanumeric() ) condition = condition_collection.create( condition_class, fauxfactory.gen_alphanumeric(), expression=expression ) policy = policy_collection.create( policy_class, fauxfactory.gen_alphanumeric() ) yield policy, condition policy.delete() condition.delete() @pytest.mark.sauce @pytest.mark.tier(2) def test_condition_crud(condition_collection, condition_prerequisites): # CR condition_class, scope, expression = condition_prerequisites condition = condition_collection.create( condition_class, fauxfactory.gen_alphanumeric(), scope=scope, expression=expression ) with update(condition): condition.notes = "Modified!" # D condition.delete() @pytest.mark.sauce @pytest.mark.tier(2) def test_action_crud(action_collection): # CR action = action_collection.create( fauxfactory.gen_alphanumeric(), action_type="Tag", action_values={"tag": ("My Company Tags", "Department", "Accounting")} ) # U with update(action): action.description = "w00t w00t" # D action.delete() @pytest.mark.sauce @pytest.mark.tier(2) def test_policy_crud(policy_collection, policy_class): # CR policy = policy_collection.create(policy_class, fauxfactory.gen_alphanumeric()) # U with update(policy): policy.notes = "Modified!" # D policy.delete() @pytest.mark.tier(3) def test_policy_copy(policy): random_policy_copy = policy.copy() assert random_policy_copy.exists random_policy_copy.delete() @pytest.mark.tier(3) def test_assign_two_random_events_to_control_policy(control_policy, soft_assert): random_events = random.sample(EVENTS, 2) control_policy.assign_events(*random_events) soft_assert(control_policy.is_event_assigned(random_events[0])) soft_assert(control_policy.is_event_assigned(random_events[1])) @pytest.mark.tier(2) @pytest.mark.meta(blockers=[BZ(1491576, forced_streams=["5.7.4"])]) def test_control_assign_actions_to_event(request, policy, action): if type(policy) in CONTROL_POLICIES: event = random.choice(EVENTS) policy.assign_events(event) request.addfinalizer(policy.assign_events) else: prefix = policy.TREE_NODE if not policy.TREE_NODE == "Vm" else policy.TREE_NODE.upper() event = "{} Compliance Check".format(prefix) request.addfinalizer(lambda: policy.assign_actions_to_event( event, {"Mark as Non-Compliant": False})) policy.assign_actions_to_event(event, action) assert str(action) == policy.assigned_actions_to_event(event)[0] @pytest.mark.tier(3) def test_assign_condition_to_control_policy(request, policy_and_condition): """This test checks if a condition is assigned to a control policy. Steps: * Create a control policy. * Assign a condition to the created policy. """ policy, condition = policy_and_condition policy.assign_conditions(condition) request.addfinalizer(policy.assign_conditions) assert policy.is_condition_assigned(condition) @pytest.mark.sauce @pytest.mark.tier(2) def test_policy_profile_crud(policy_profile_collection, two_random_policies): profile = policy_profile_collection.create( fauxfactory.gen_alphanumeric(), policies=two_random_policies ) with update(profile): profile.notes = "Modified!" profile.delete() @pytest.mark.tier(3) @pytest.mark.parametrize("fill_type,expression,verify", EXPRESSIONS_TO_TEST, ids=[ expr[0] for expr in EXPRESSIONS_TO_TEST]) def test_modify_condition_expression(condition_for_expressions, fill_type, expression, verify): with update(condition_for_expressions): condition_for_expressions.expression = expression.format( condition_for_expressions.FIELD_VALUE) assert condition_for_expressions.read_expression() == verify.format( condition_for_expressions.FIELD_VALUE) @pytest.mark.sauce @pytest.mark.tier(2) def test_alert_crud(alert_collection): # CR alert = alert_collection.create( fauxfactory.gen_alphanumeric(), timeline_event=True, driving_event="Hourly Timer" ) # U with update(alert): alert.notification_frequency = "2 Hours" # D alert.delete() @pytest.mark.tier(3) @pytest.mark.meta(blockers=[1303645], automates=[1303645]) def test_control_alert_copy(alert): alert_copy = alert.copy(description=fauxfactory.gen_alphanumeric()) assert alert_copy.exists alert_copy.delete() @pytest.mark.sauce @pytest.mark.tier(2) def test_alert_profile_crud(request, alert_profile_class, alert_collection, alert_profile_collection): alert = alert_collection.create( fauxfactory.gen_alphanumeric(), based_on=alert_profile_class.TYPE, timeline_event=True, driving_event="Hourly Timer" ) request.addfinalizer(alert.delete) alert_profile = alert_profile_collection.create( alert_profile_class, fauxfactory.gen_alphanumeric(), alerts=[alert.description] ) with update(alert_profile): alert_profile.notes = "Modified!" alert_profile.delete() @pytest.mark.tier(2) @pytest.mark.meta(blockers=[BZ(1416311, forced_streams=["5.7"])]) def test_alert_profile_assigning(alert_profile): if isinstance(alert_profile, alert_profiles.ServerAlertProfile): if BZ(1489697, forced_streams=["5.8"]).blocks: pytest.skip("BZ 1489697") alert_profile.assign_to("Selected Servers", selections=["Servers", "EVM"]) else: alert_profile.assign_to("The Enterprise") @pytest.mark.tier(2) @pytest.mark.uncollectif(lambda: current_version() < "5.8") def test_control_is_ansible_playbook_available_in_actions_dropdown(action_collection): view = navigate_to(action_collection, "Add") assert "Run Ansible Playbook" in [option.text for option in view.action_type.all_options]
quarckster/cfme_tests
cfme/tests/control/test_basic.py
cfme/utils/smem_memory_monitor.py
"""Support for Aruba Access Points.""" import logging import re import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA, DeviceScanner) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME _LOGGER = logging.getLogger(__name__) _DEVICES_REGEX = re.compile( r'(?P<name>([^\s]+)?)\s+' + r'(?P<ip>([0-9]{1,3}[\.]){3}[0-9]{1,3})\s+' + r'(?P<mac>([0-9a-f]{2}[:-]){5}([0-9a-f]{2}))\s+') PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string }) def get_scanner(hass, config): """Validate the configuration and return a Aruba scanner.""" scanner = ArubaDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class ArubaDeviceScanner(DeviceScanner): """This class queries a Aruba Access Point for connected devices.""" def __init__(self, config): """Initialize the scanner.""" self.host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.last_results = {} # Test the router is accessible. data = self.get_aruba_data() self.success_init = data is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [client['mac'] for client in self.last_results] def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if not self.last_results: return None for client in self.last_results: if client['mac'] == device: return client['name'] return None def _update_info(self): """Ensure the information from the Aruba Access Point is up to date. Return boolean if scanning successful. """ if not self.success_init: return False data = self.get_aruba_data() if not data: return False self.last_results = data.values() return True def get_aruba_data(self): """Retrieve data from Aruba Access Point and return parsed result.""" import pexpect connect = 'ssh {}@{}' ssh = pexpect.spawn(connect.format(self.username, self.host)) query = ssh.expect(['password:', pexpect.TIMEOUT, pexpect.EOF, 'continue connecting (yes/no)?', 'Host key verification failed.', 'Connection refused', 'Connection timed out'], timeout=120) if query == 1: _LOGGER.error("Timeout") return if query == 2: _LOGGER.error("Unexpected response from router") return if query == 3: ssh.sendline('yes') ssh.expect('password:') elif query == 4: _LOGGER.error("Host key changed") return elif query == 5: _LOGGER.error("Connection refused by server") return elif query == 6: _LOGGER.error("Connection timed out") return ssh.sendline(self.password) ssh.expect('#') ssh.sendline('show clients') ssh.expect('#') devices_result = ssh.before.split(b'\r\n') ssh.sendline('exit') devices = {} for device in devices_result: match = _DEVICES_REGEX.search(device.decode('utf-8')) if match: devices[match.group('ip')] = { 'ip': match.group('ip'), 'mac': match.group('mac').upper(), 'name': match.group('name') } return devices
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/aruba/device_tracker.py
"""Support for the Pico TTS speech service.""" import logging import os import shutil import subprocess import tempfile import voluptuous as vol from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider _LOGGER = logging.getLogger(__name__) SUPPORT_LANGUAGES = ['en-US', 'en-GB', 'de-DE', 'es-ES', 'fr-FR', 'it-IT'] DEFAULT_LANG = 'en-US' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.In(SUPPORT_LANGUAGES), }) def get_engine(hass, config): """Set up Pico speech component.""" if shutil.which("pico2wave") is None: _LOGGER.error("'pico2wave' was not found") return False return PicoProvider(config[CONF_LANG]) class PicoProvider(Provider): """The Pico TTS API provider.""" def __init__(self, lang): """Initialize Pico TTS provider.""" self._lang = lang self.name = 'PicoTTS' @property def default_language(self): """Return the default language.""" return self._lang @property def supported_languages(self): """Return list of supported languages.""" return SUPPORT_LANGUAGES def get_tts_audio(self, message, language, options=None): """Load TTS using pico2wave.""" with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmpf: fname = tmpf.name cmd = ['pico2wave', '--wave', fname, '-l', language, message] subprocess.call(cmd) data = None try: with open(fname, 'rb') as voice: data = voice.read() except OSError: _LOGGER.error("Error trying to read %s", fname) return (None, None) finally: os.remove(fname) if data: return ("wav", data) return (None, None)
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/picotts/tts.py
"""Config flow for Geofency.""" from homeassistant.helpers import config_entry_flow from .const import DOMAIN config_entry_flow.register_webhook_flow( DOMAIN, 'Geofency Webhook', { 'docs_url': 'https://www.home-assistant.io/components/geofency/' } )
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/geofency/config_flow.py
"""Support for Cameras with FFmpeg as decoder.""" import asyncio import logging import voluptuous as vol from homeassistant.components.camera import ( PLATFORM_SCHEMA, Camera, SUPPORT_STREAM) from homeassistant.const import CONF_NAME from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream import homeassistant.helpers.config_validation as cv from . import CONF_EXTRA_ARGUMENTS, CONF_INPUT, DATA_FFMPEG _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = 'FFmpeg' DEFAULT_ARGUMENTS = "-pred 1" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_INPUT): cv.string, vol.Optional(CONF_EXTRA_ARGUMENTS, default=DEFAULT_ARGUMENTS): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, }) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up a FFmpeg camera.""" async_add_entities([FFmpegCamera(hass, config)]) class FFmpegCamera(Camera): """An implementation of an FFmpeg camera.""" def __init__(self, hass, config): """Initialize a FFmpeg camera.""" super().__init__() self._manager = hass.data[DATA_FFMPEG] self._name = config.get(CONF_NAME) self._input = config.get(CONF_INPUT) self._extra_arguments = config.get(CONF_EXTRA_ARGUMENTS) @property def supported_features(self): """Return supported features.""" return SUPPORT_STREAM async def stream_source(self): """Return the stream source.""" return self._input.split(' ')[-1] async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._manager.binary, loop=self.hass.loop) image = await asyncio.shield(ffmpeg.get_image( self._input, output_format=IMAGE_JPEG, extra_cmd=self._extra_arguments)) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg stream = CameraMjpeg(self._manager.binary, loop=self.hass.loop) await stream.open_camera( self._input, extra_cmd=self._extra_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._manager.ffmpeg_stream_content_type) finally: await stream.close() @property def name(self): """Return the name of this camera.""" return self._name
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/ffmpeg/camera.py
"""Support for Plex media server monitoring.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.switch import PLATFORM_SCHEMA from homeassistant.const import ( CONF_NAME, CONF_USERNAME, CONF_PASSWORD, CONF_HOST, CONF_PORT, CONF_TOKEN, CONF_SSL, CONF_VERIFY_SSL) from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_SERVER = 'server' DEFAULT_HOST = 'localhost' DEFAULT_NAME = 'Plex' DEFAULT_PORT = 32400 DEFAULT_SSL = False DEFAULT_VERIFY_SSL = True MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=1) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, vol.Optional(CONF_TOKEN): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SERVER): cv.string, vol.Optional(CONF_USERNAME): cv.string, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Plex sensor.""" name = config.get(CONF_NAME) plex_user = config.get(CONF_USERNAME) plex_password = config.get(CONF_PASSWORD) plex_server = config.get(CONF_SERVER) plex_host = config.get(CONF_HOST) plex_port = config.get(CONF_PORT) plex_token = config.get(CONF_TOKEN) plex_url = '{}://{}:{}'.format('https' if config.get(CONF_SSL) else 'http', plex_host, plex_port) import plexapi.exceptions try: add_entities([PlexSensor( name, plex_url, plex_user, plex_password, plex_server, plex_token, config.get(CONF_VERIFY_SSL))], True) except (plexapi.exceptions.BadRequest, plexapi.exceptions.Unauthorized, plexapi.exceptions.NotFound) as error: _LOGGER.error(error) return class PlexSensor(Entity): """Representation of a Plex now playing sensor.""" def __init__(self, name, plex_url, plex_user, plex_password, plex_server, plex_token, verify_ssl): """Initialize the sensor.""" from plexapi.myplex import MyPlexAccount from plexapi.server import PlexServer from requests import Session self._name = name self._state = 0 self._now_playing = [] cert_session = None if not verify_ssl: _LOGGER.info("Ignoring SSL verification") cert_session = Session() cert_session.verify = False if plex_token: self._server = PlexServer(plex_url, plex_token, cert_session) elif plex_user and plex_password: user = MyPlexAccount(plex_user, plex_password) server = plex_server if plex_server else user.resources()[0].name self._server = user.resource(server).connect() else: self._server = PlexServer(plex_url, None, cert_session) @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit this state is expressed in.""" return "Watching" @property def device_state_attributes(self): """Return the state attributes.""" return {content[0]: content[1] for content in self._now_playing} @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Update method for Plex sensor.""" sessions = self._server.sessions() now_playing = [] for sess in sessions: user = sess.usernames[0] device = sess.players[0].title now_playing_user = "{0} - {1}".format(user, device) now_playing_title = "" if sess.TYPE == 'episode': # example: # "Supernatural (2005) - S01 · E13 - Route 666" season_title = sess.grandparentTitle if sess.show().year is not None: season_title += " ({0})".format(sess.show().year) season_episode = "S{0}".format(sess.parentIndex) if sess.index is not None: season_episode += " · E{0}".format(sess.index) episode_title = sess.title now_playing_title = "{0} - {1} - {2}".format(season_title, season_episode, episode_title) elif sess.TYPE == 'track': # example: # "Billy Talent - Afraid of Heights - Afraid of Heights" track_artist = sess.grandparentTitle track_album = sess.parentTitle track_title = sess.title now_playing_title = "{0} - {1} - {2}".format(track_artist, track_album, track_title) else: # example: # "picture_of_last_summer_camp (2015)" # "The Incredible Hulk (2008)" now_playing_title = sess.title if sess.year is not None: now_playing_title += " ({0})".format(sess.year) now_playing.append((now_playing_user, now_playing_title)) self._state = len(sessions) self._now_playing = now_playing
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/plex/sensor.py
"""Support for Abode Security System sensors.""" import logging from homeassistant.const import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE, DEVICE_CLASS_TEMPERATURE) from . import DOMAIN as ABODE_DOMAIN, AbodeDevice _LOGGER = logging.getLogger(__name__) # Sensor types: Name, icon SENSOR_TYPES = { 'temp': ['Temperature', DEVICE_CLASS_TEMPERATURE], 'humidity': ['Humidity', DEVICE_CLASS_HUMIDITY], 'lux': ['Lux', DEVICE_CLASS_ILLUMINANCE], } def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a sensor for an Abode device.""" import abodepy.helpers.constants as CONST data = hass.data[ABODE_DOMAIN] devices = [] for device in data.abode.get_devices(generic_type=CONST.TYPE_SENSOR): if data.is_excluded(device): continue for sensor_type in SENSOR_TYPES: devices.append(AbodeSensor(data, device, sensor_type)) data.devices.extend(devices) add_entities(devices) class AbodeSensor(AbodeDevice): """A sensor implementation for Abode devices.""" def __init__(self, data, device, sensor_type): """Initialize a sensor for an Abode device.""" super().__init__(data, device) self._sensor_type = sensor_type self._name = '{0} {1}'.format( self._device.name, SENSOR_TYPES[self._sensor_type][0]) self._device_class = SENSOR_TYPES[self._sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def device_class(self): """Return the device class.""" return self._device_class @property def state(self): """Return the state of the sensor.""" if self._sensor_type == 'temp': return self._device.temp if self._sensor_type == 'humidity': return self._device.humidity if self._sensor_type == 'lux': return self._device.lux @property def unit_of_measurement(self): """Return the units of measurement.""" if self._sensor_type == 'temp': return self._device.temp_unit if self._sensor_type == 'humidity': return self._device.humidity_unit if self._sensor_type == 'lux': return self._device.lux_unit
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/abode/sensor.py
"""Support for Blink system camera control.""" from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.const import CONF_MONITORED_CONDITIONS from . import BINARY_SENSORS, BLINK_DATA def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the blink binary sensors.""" if discovery_info is None: return data = hass.data[BLINK_DATA] devs = [] for camera in data.cameras: for sensor_type in discovery_info[CONF_MONITORED_CONDITIONS]: devs.append(BlinkBinarySensor(data, camera, sensor_type)) add_entities(devs, True) class BlinkBinarySensor(BinarySensorDevice): """Representation of a Blink binary sensor.""" def __init__(self, data, camera, sensor_type): """Initialize the sensor.""" self.data = data self._type = sensor_type name, icon = BINARY_SENSORS[sensor_type] self._name = "{} {} {}".format(BLINK_DATA, camera, name) self._icon = icon self._camera = data.cameras[camera] self._state = None self._unique_id = "{}-{}".format(self._camera.serial, self._type) @property def name(self): """Return the name of the blink sensor.""" return self._name @property def is_on(self): """Return the status of the sensor.""" return self._state def update(self): """Update sensor state.""" self.data.refresh() self._state = self._camera.attributes[self._type]
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/blink/binary_sensor.py
"""MySensors platform that offers a Climate (MySensors-HVAC) component.""" from homeassistant.components import mysensors from homeassistant.components.climate import ClimateDevice from homeassistant.components.climate.const import ( ATTR_TARGET_TEMP_HIGH, ATTR_TARGET_TEMP_LOW, DOMAIN, STATE_AUTO, STATE_COOL, STATE_HEAT, SUPPORT_FAN_MODE, SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE, SUPPORT_TARGET_TEMPERATURE_HIGH, SUPPORT_TARGET_TEMPERATURE_LOW) from homeassistant.const import ( ATTR_TEMPERATURE, STATE_OFF, TEMP_CELSIUS, TEMP_FAHRENHEIT) DICT_HA_TO_MYS = { STATE_AUTO: 'AutoChangeOver', STATE_COOL: 'CoolOn', STATE_HEAT: 'HeatOn', STATE_OFF: 'Off', } DICT_MYS_TO_HA = { 'AutoChangeOver': STATE_AUTO, 'CoolOn': STATE_COOL, 'HeatOn': STATE_HEAT, 'Off': STATE_OFF, } FAN_LIST = ['Auto', 'Min', 'Normal', 'Max'] OPERATION_LIST = [STATE_OFF, STATE_AUTO, STATE_COOL, STATE_HEAT] async def async_setup_platform( hass, config, async_add_entities, discovery_info=None): """Set up the mysensors climate.""" mysensors.setup_mysensors_platform( hass, DOMAIN, discovery_info, MySensorsHVAC, async_add_entities=async_add_entities) class MySensorsHVAC(mysensors.device.MySensorsEntity, ClimateDevice): """Representation of a MySensors HVAC.""" @property def supported_features(self): """Return the list of supported features.""" features = SUPPORT_OPERATION_MODE set_req = self.gateway.const.SetReq if set_req.V_HVAC_SPEED in self._values: features = features | SUPPORT_FAN_MODE if (set_req.V_HVAC_SETPOINT_COOL in self._values and set_req.V_HVAC_SETPOINT_HEAT in self._values): features = ( features | SUPPORT_TARGET_TEMPERATURE_HIGH | SUPPORT_TARGET_TEMPERATURE_LOW) else: features = features | SUPPORT_TARGET_TEMPERATURE return features @property def assumed_state(self): """Return True if unable to access real state of entity.""" return self.gateway.optimistic @property def temperature_unit(self): """Return the unit of measurement.""" return TEMP_CELSIUS if self.gateway.metric else TEMP_FAHRENHEIT @property def current_temperature(self): """Return the current temperature.""" value = self._values.get(self.gateway.const.SetReq.V_TEMP) if value is not None: value = float(value) return value @property def target_temperature(self): """Return the temperature we try to reach.""" set_req = self.gateway.const.SetReq if set_req.V_HVAC_SETPOINT_COOL in self._values and \ set_req.V_HVAC_SETPOINT_HEAT in self._values: return None temp = self._values.get(set_req.V_HVAC_SETPOINT_COOL) if temp is None: temp = self._values.get(set_req.V_HVAC_SETPOINT_HEAT) return float(temp) if temp is not None else None @property def target_temperature_high(self): """Return the highbound target temperature we try to reach.""" set_req = self.gateway.const.SetReq if set_req.V_HVAC_SETPOINT_HEAT in self._values: temp = self._values.get(set_req.V_HVAC_SETPOINT_COOL) return float(temp) if temp is not None else None @property def target_temperature_low(self): """Return the lowbound target temperature we try to reach.""" set_req = self.gateway.const.SetReq if set_req.V_HVAC_SETPOINT_COOL in self._values: temp = self._values.get(set_req.V_HVAC_SETPOINT_HEAT) return float(temp) if temp is not None else None @property def current_operation(self): """Return current operation ie. heat, cool, idle.""" return self._values.get(self.value_type) @property def operation_list(self): """List of available operation modes.""" return OPERATION_LIST @property def current_fan_mode(self): """Return the fan setting.""" return self._values.get(self.gateway.const.SetReq.V_HVAC_SPEED) @property def fan_list(self): """List of available fan modes.""" return FAN_LIST async def async_set_temperature(self, **kwargs): """Set new target temperature.""" set_req = self.gateway.const.SetReq temp = kwargs.get(ATTR_TEMPERATURE) low = kwargs.get(ATTR_TARGET_TEMP_LOW) high = kwargs.get(ATTR_TARGET_TEMP_HIGH) heat = self._values.get(set_req.V_HVAC_SETPOINT_HEAT) cool = self._values.get(set_req.V_HVAC_SETPOINT_COOL) updates = [] if temp is not None: if heat is not None: # Set HEAT Target temperature value_type = set_req.V_HVAC_SETPOINT_HEAT elif cool is not None: # Set COOL Target temperature value_type = set_req.V_HVAC_SETPOINT_COOL if heat is not None or cool is not None: updates = [(value_type, temp)] elif all(val is not None for val in (low, high, heat, cool)): updates = [ (set_req.V_HVAC_SETPOINT_HEAT, low), (set_req.V_HVAC_SETPOINT_COOL, high)] for value_type, value in updates: self.gateway.set_child_value( self.node_id, self.child_id, value_type, value) if self.gateway.optimistic: # Optimistically assume that device has changed state self._values[value_type] = value self.async_schedule_update_ha_state() async def async_set_fan_mode(self, fan_mode): """Set new target temperature.""" set_req = self.gateway.const.SetReq self.gateway.set_child_value( self.node_id, self.child_id, set_req.V_HVAC_SPEED, fan_mode) if self.gateway.optimistic: # Optimistically assume that device has changed state self._values[set_req.V_HVAC_SPEED] = fan_mode self.async_schedule_update_ha_state() async def async_set_operation_mode(self, operation_mode): """Set new target temperature.""" self.gateway.set_child_value( self.node_id, self.child_id, self.value_type, DICT_HA_TO_MYS[operation_mode]) if self.gateway.optimistic: # Optimistically assume that device has changed state self._values[self.value_type] = operation_mode self.async_schedule_update_ha_state() async def async_update(self): """Update the controller with the latest value from a sensor.""" await super().async_update() self._values[self.value_type] = DICT_MYS_TO_HA[ self._values[self.value_type]]
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/mysensors/climate.py
"""Support for interfacing with NAD receivers through RS-232.""" import logging import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.media_player import ( MediaPlayerDevice, PLATFORM_SCHEMA) from homeassistant.components.media_player.const import ( SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_VOLUME_STEP) from homeassistant.const import CONF_NAME, STATE_OFF, STATE_ON, CONF_HOST _LOGGER = logging.getLogger(__name__) DEFAULT_TYPE = 'RS232' DEFAULT_SERIAL_PORT = '/dev/ttyUSB0' DEFAULT_PORT = 53 DEFAULT_NAME = 'NAD Receiver' DEFAULT_MIN_VOLUME = -92 DEFAULT_MAX_VOLUME = -20 DEFAULT_VOLUME_STEP = 4 SUPPORT_NAD = SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \ SUPPORT_TURN_ON | SUPPORT_TURN_OFF | SUPPORT_VOLUME_STEP | \ SUPPORT_SELECT_SOURCE CONF_TYPE = 'type' CONF_SERIAL_PORT = 'serial_port' # for NADReceiver CONF_PORT = 'port' # for NADReceiverTelnet CONF_MIN_VOLUME = 'min_volume' CONF_MAX_VOLUME = 'max_volume' CONF_VOLUME_STEP = 'volume_step' # for NADReceiverTCP CONF_SOURCE_DICT = 'sources' # for NADReceiver SOURCE_DICT_SCHEMA = vol.Schema({ vol.Range(min=1, max=10): cv.string }) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_TYPE, default=DEFAULT_TYPE): vol.In(['RS232', 'Telnet', 'TCP']), vol.Optional(CONF_SERIAL_PORT, default=DEFAULT_SERIAL_PORT): cv.string, vol.Optional(CONF_HOST): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): int, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_MIN_VOLUME, default=DEFAULT_MIN_VOLUME): int, vol.Optional(CONF_MAX_VOLUME, default=DEFAULT_MAX_VOLUME): int, vol.Optional(CONF_SOURCE_DICT, default={}): SOURCE_DICT_SCHEMA, vol.Optional(CONF_VOLUME_STEP, default=DEFAULT_VOLUME_STEP): int, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the NAD platform.""" if config.get(CONF_TYPE) == 'RS232': from nad_receiver import NADReceiver add_entities([NAD( config.get(CONF_NAME), NADReceiver(config.get(CONF_SERIAL_PORT)), config.get(CONF_MIN_VOLUME), config.get(CONF_MAX_VOLUME), config.get(CONF_SOURCE_DICT) )], True) elif config.get(CONF_TYPE) == 'Telnet': from nad_receiver import NADReceiverTelnet add_entities([NAD( config.get(CONF_NAME), NADReceiverTelnet(config.get(CONF_HOST), config.get(CONF_PORT)), config.get(CONF_MIN_VOLUME), config.get(CONF_MAX_VOLUME), config.get(CONF_SOURCE_DICT) )], True) else: from nad_receiver import NADReceiverTCP add_entities([NADtcp( config.get(CONF_NAME), NADReceiverTCP(config.get(CONF_HOST)), config.get(CONF_MIN_VOLUME), config.get(CONF_MAX_VOLUME), config.get(CONF_VOLUME_STEP), )], True) class NAD(MediaPlayerDevice): """Representation of a NAD Receiver.""" def __init__(self, name, nad_receiver, min_volume, max_volume, source_dict): """Initialize the NAD Receiver device.""" self._name = name self._nad_receiver = nad_receiver self._min_volume = min_volume self._max_volume = max_volume self._source_dict = source_dict self._reverse_mapping = {value: key for key, value in self._source_dict.items()} self._volume = self._state = self._mute = self._source = None @property def name(self): """Return the name of the device.""" return self._name @property def state(self): """Return the state of the device.""" return self._state @property def volume_level(self): """Volume level of the media player (0..1).""" return self._volume @property def is_volume_muted(self): """Boolean if volume is currently muted.""" return self._mute @property def supported_features(self): """Flag media player features that are supported.""" return SUPPORT_NAD def turn_off(self): """Turn the media player off.""" self._nad_receiver.main_power('=', 'Off') def turn_on(self): """Turn the media player on.""" self._nad_receiver.main_power('=', 'On') def volume_up(self): """Volume up the media player.""" self._nad_receiver.main_volume('+') def volume_down(self): """Volume down the media player.""" self._nad_receiver.main_volume('-') def set_volume_level(self, volume): """Set volume level, range 0..1.""" self._nad_receiver.main_volume('=', self.calc_db(volume)) def mute_volume(self, mute): """Mute (true) or unmute (false) media player.""" if mute: self._nad_receiver.main_mute('=', 'On') else: self._nad_receiver.main_mute('=', 'Off') def select_source(self, source): """Select input source.""" self._nad_receiver.main_source('=', self._reverse_mapping.get(source)) @property def source(self): """Name of the current input source.""" return self._source @property def source_list(self): """List of available input sources.""" return sorted(list(self._reverse_mapping.keys())) def update(self): """Retrieve latest state.""" if self._nad_receiver.main_power('?') == 'Off': self._state = STATE_OFF else: self._state = STATE_ON if self._nad_receiver.main_mute('?') == 'Off': self._mute = False else: self._mute = True self._volume = self.calc_volume(self._nad_receiver.main_volume('?')) self._source = self._source_dict.get( self._nad_receiver.main_source('?')) def calc_volume(self, decibel): """ Calculate the volume given the decibel. Return the volume (0..1). """ return abs(self._min_volume - decibel) / abs( self._min_volume - self._max_volume) def calc_db(self, volume): """ Calculate the decibel given the volume. Return the dB. """ return self._min_volume + round( abs(self._min_volume - self._max_volume) * volume) class NADtcp(MediaPlayerDevice): """Representation of a NAD Digital amplifier.""" def __init__(self, name, nad_device, min_volume, max_volume, volume_step): """Initialize the amplifier.""" self._name = name self._nad_receiver = nad_device self._min_vol = (min_volume + 90) * 2 # from dB to nad vol (0-200) self._max_vol = (max_volume + 90) * 2 # from dB to nad vol (0-200) self._volume_step = volume_step self._state = None self._mute = None self._nad_volume = None self._volume = None self._source = None self._source_list = self._nad_receiver.available_sources() @property def name(self): """Return the name of the device.""" return self._name @property def state(self): """Return the state of the device.""" return self._state @property def volume_level(self): """Volume level of the media player (0..1).""" return self._volume @property def is_volume_muted(self): """Boolean if volume is currently muted.""" return self._mute @property def supported_features(self): """Flag media player features that are supported.""" return SUPPORT_NAD def turn_off(self): """Turn the media player off.""" self._nad_receiver.power_off() def turn_on(self): """Turn the media player on.""" self._nad_receiver.power_on() def volume_up(self): """Step volume up in the configured increments.""" self._nad_receiver.set_volume(self._nad_volume + 2 * self._volume_step) def volume_down(self): """Step volume down in the configured increments.""" self._nad_receiver.set_volume(self._nad_volume - 2 * self._volume_step) def set_volume_level(self, volume): """Set volume level, range 0..1.""" nad_volume_to_set = \ int(round(volume * (self._max_vol - self._min_vol) + self._min_vol)) self._nad_receiver.set_volume(nad_volume_to_set) def mute_volume(self, mute): """Mute (true) or unmute (false) media player.""" if mute: self._nad_receiver.mute() else: self._nad_receiver.unmute() def select_source(self, source): """Select input source.""" self._nad_receiver.select_source(source) @property def source(self): """Name of the current input source.""" return self._source @property def source_list(self): """List of available input sources.""" return self._nad_receiver.available_sources() def update(self): """Get the latest details from the device.""" try: nad_status = self._nad_receiver.status() except OSError: return if nad_status is None: return # Update on/off state if nad_status['power']: self._state = STATE_ON else: self._state = STATE_OFF # Update current volume self._volume = self.nad_vol_to_internal_vol(nad_status['volume']) self._nad_volume = nad_status['volume'] # Update muted state self._mute = nad_status['muted'] # Update current source self._source = nad_status['source'] def nad_vol_to_internal_vol(self, nad_volume): """Convert nad volume range (0-200) to internal volume range. Takes into account configured min and max volume. """ if nad_volume < self._min_vol: volume_internal = 0.0 elif nad_volume > self._max_vol: volume_internal = 1.0 else: volume_internal = (nad_volume - self._min_vol) / \ (self._max_vol - self._min_vol) return volume_internal
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/nad/media_player.py
"""Support for Zigbee devices.""" import logging from binascii import hexlify, unhexlify import voluptuous as vol from homeassistant.const import ( EVENT_HOMEASSISTANT_STOP, CONF_DEVICE, CONF_NAME, CONF_PIN, CONF_ADDRESS) from homeassistant.helpers.entity import Entity from homeassistant.helpers import config_validation as cv from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, dispatcher_send) _LOGGER = logging.getLogger(__name__) DOMAIN = 'zigbee' SIGNAL_ZIGBEE_FRAME_RECEIVED = 'zigbee_frame_received' CONF_BAUD = 'baud' DEFAULT_DEVICE = '/dev/ttyUSB0' DEFAULT_BAUD = 9600 DEFAULT_ADC_MAX_VOLTS = 1.2 # Copied from xbee_helper during setup() GPIO_DIGITAL_OUTPUT_LOW = None GPIO_DIGITAL_OUTPUT_HIGH = None ADC_PERCENTAGE = None DIGITAL_PINS = None ANALOG_PINS = None CONVERT_ADC = None ZIGBEE_EXCEPTION = None ZIGBEE_TX_FAILURE = None ATTR_FRAME = 'frame' DEVICE = None CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Optional(CONF_BAUD, default=DEFAULT_BAUD): cv.string, vol.Optional(CONF_DEVICE, default=DEFAULT_DEVICE): cv.string, }), }, extra=vol.ALLOW_EXTRA) PLATFORM_SCHEMA = vol.Schema({ vol.Required(CONF_NAME): cv.string, vol.Optional(CONF_PIN): cv.positive_int, vol.Optional(CONF_ADDRESS): cv.string, }, extra=vol.ALLOW_EXTRA) def setup(hass, config): """Set up the connection to the Zigbee device.""" global DEVICE global GPIO_DIGITAL_OUTPUT_LOW global GPIO_DIGITAL_OUTPUT_HIGH global ADC_PERCENTAGE global DIGITAL_PINS global ANALOG_PINS global CONVERT_ADC global ZIGBEE_EXCEPTION global ZIGBEE_TX_FAILURE import xbee_helper.const as xb_const from xbee_helper import ZigBee from xbee_helper.device import convert_adc from xbee_helper.exceptions import ZigBeeException, ZigBeeTxFailure from serial import Serial, SerialException GPIO_DIGITAL_OUTPUT_LOW = xb_const.GPIO_DIGITAL_OUTPUT_LOW GPIO_DIGITAL_OUTPUT_HIGH = xb_const.GPIO_DIGITAL_OUTPUT_HIGH ADC_PERCENTAGE = xb_const.ADC_PERCENTAGE DIGITAL_PINS = xb_const.DIGITAL_PINS ANALOG_PINS = xb_const.ANALOG_PINS CONVERT_ADC = convert_adc ZIGBEE_EXCEPTION = ZigBeeException ZIGBEE_TX_FAILURE = ZigBeeTxFailure usb_device = config[DOMAIN].get(CONF_DEVICE, DEFAULT_DEVICE) baud = int(config[DOMAIN].get(CONF_BAUD, DEFAULT_BAUD)) try: ser = Serial(usb_device, baud) except SerialException as exc: _LOGGER.exception("Unable to open serial port for Zigbee: %s", exc) return False DEVICE = ZigBee(ser) hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, close_serial_port) def _frame_received(frame): """Run when a Zigbee frame is received. Pickles the frame, then encodes it into base64 since it contains non JSON serializable binary. """ dispatcher_send(hass, SIGNAL_ZIGBEE_FRAME_RECEIVED, frame) DEVICE.add_frame_rx_handler(_frame_received) return True def close_serial_port(*args): """Close the serial port we're using to communicate with the Zigbee.""" DEVICE.zb.serial.close() def frame_is_relevant(entity, frame): """Test whether the frame is relevant to the entity.""" if frame.get('source_addr_long') != entity.config.address: return False if 'samples' not in frame: return False return True class ZigBeeConfig: """Handle the fetching of configuration from the config file.""" def __init__(self, config): """Initialize the configuration.""" self._config = config self._should_poll = config.get("poll", True) @property def name(self): """Return the name given to the entity.""" return self._config["name"] @property def address(self): """Return the address of the device. If an address has been provided, unhexlify it, otherwise return None as we're talking to our local Zigbee device. """ address = self._config.get("address") if address is not None: address = unhexlify(address) return address @property def should_poll(self): """Return the polling state.""" return self._should_poll class ZigBeePinConfig(ZigBeeConfig): """Handle the fetching of configuration from the configuration file.""" @property def pin(self): """Return the GPIO pin number.""" return self._config["pin"] class ZigBeeDigitalInConfig(ZigBeePinConfig): """A subclass of ZigBeePinConfig.""" def __init__(self, config): """Initialise the Zigbee Digital input config.""" super(ZigBeeDigitalInConfig, self).__init__(config) self._bool2state, self._state2bool = self.boolean_maps @property def boolean_maps(self): """Create mapping dictionaries for potential inversion of booleans. Create dicts to map the pin state (true/false) to potentially inverted values depending on the on_state config value which should be set to "low" or "high". """ if self._config.get("on_state", "").lower() == "low": bool2state = { True: False, False: True } else: bool2state = { True: True, False: False } state2bool = {v: k for k, v in bool2state.items()} return bool2state, state2bool @property def bool2state(self): """Return a dictionary mapping the internal value to the Zigbee value. For the translation of on/off as being pin high or low. """ return self._bool2state @property def state2bool(self): """Return a dictionary mapping the Zigbee value to the internal value. For the translation of pin high/low as being on or off. """ return self._state2bool class ZigBeeDigitalOutConfig(ZigBeePinConfig): """A subclass of ZigBeePinConfig. Set _should_poll to default as False instead of True. The value will still be overridden by the presence of a 'poll' config entry. """ def __init__(self, config): """Initialize the Zigbee Digital out.""" super(ZigBeeDigitalOutConfig, self).__init__(config) self._bool2state, self._state2bool = self.boolean_maps self._should_poll = config.get("poll", False) @property def boolean_maps(self): """Create dicts to map booleans to pin high/low and vice versa. Depends on the config item "on_state" which should be set to "low" or "high". """ if self._config.get("on_state", "").lower() == "low": bool2state = { True: GPIO_DIGITAL_OUTPUT_LOW, False: GPIO_DIGITAL_OUTPUT_HIGH } else: bool2state = { True: GPIO_DIGITAL_OUTPUT_HIGH, False: GPIO_DIGITAL_OUTPUT_LOW } state2bool = {v: k for k, v in bool2state.items()} return bool2state, state2bool @property def bool2state(self): """Return a dictionary mapping booleans to GPIOSetting objects. For the translation of on/off as being pin high or low. """ return self._bool2state @property def state2bool(self): """Return a dictionary mapping GPIOSetting objects to booleans. For the translation of pin high/low as being on or off. """ return self._state2bool class ZigBeeAnalogInConfig(ZigBeePinConfig): """Representation of a Zigbee GPIO pin set to analog in.""" @property def max_voltage(self): """Return the voltage for ADC to report its highest value.""" return float(self._config.get("max_volts", DEFAULT_ADC_MAX_VOLTS)) class ZigBeeDigitalIn(Entity): """Representation of a GPIO pin configured as a digital input.""" def __init__(self, hass, config): """Initialize the device.""" self._config = config self._state = False async def async_added_to_hass(self): """Register callbacks.""" def handle_frame(frame): """Handle an incoming frame. Handle an incoming frame and update our status if it contains information relating to this device. """ if not frame_is_relevant(self, frame): return sample = next(iter(frame['samples'])) pin_name = DIGITAL_PINS[self._config.pin] if pin_name not in sample: # Doesn't contain information about our pin return # Set state to the value of sample, respecting any inversion # logic from the on_state config variable. self._state = self._config.state2bool[ self._config.bool2state[sample[pin_name]]] self.schedule_update_ha_state() async_dispatcher_connect( self.hass, SIGNAL_ZIGBEE_FRAME_RECEIVED, handle_frame) @property def name(self): """Return the name of the input.""" return self._config.name @property def config(self): """Return the entity's configuration.""" return self._config @property def should_poll(self): """Return the state of the polling, if needed.""" return self._config.should_poll @property def is_on(self): """Return True if the Entity is on, else False.""" return self._state def update(self): """Ask the Zigbee device what state its input pin is in.""" try: sample = DEVICE.get_sample(self._config.address) except ZIGBEE_TX_FAILURE: _LOGGER.warning( "Transmission failure when attempting to get sample from " "ZigBee device at address: %s", hexlify(self._config.address)) return except ZIGBEE_EXCEPTION as exc: _LOGGER.exception( "Unable to get sample from Zigbee device: %s", exc) return pin_name = DIGITAL_PINS[self._config.pin] if pin_name not in sample: _LOGGER.warning( "Pin %s (%s) was not in the sample provided by Zigbee device " "%s.", self._config.pin, pin_name, hexlify(self._config.address)) return self._state = self._config.state2bool[sample[pin_name]] class ZigBeeDigitalOut(ZigBeeDigitalIn): """Representation of a GPIO pin configured as a digital input.""" def _set_state(self, state): """Initialize the ZigBee digital out device.""" try: DEVICE.set_gpio_pin( self._config.pin, self._config.bool2state[state], self._config.address) except ZIGBEE_TX_FAILURE: _LOGGER.warning( "Transmission failure when attempting to set output pin on " "ZigBee device at address: %s", hexlify(self._config.address)) return except ZIGBEE_EXCEPTION as exc: _LOGGER.exception( "Unable to set digital pin on ZigBee device: %s", exc) return self._state = state if not self.should_poll: self.schedule_update_ha_state() def turn_on(self, **kwargs): """Set the digital output to its 'on' state.""" self._set_state(True) def turn_off(self, **kwargs): """Set the digital output to its 'off' state.""" self._set_state(False) def update(self): """Ask the ZigBee device what its output is set to.""" try: pin_state = DEVICE.get_gpio_pin( self._config.pin, self._config.address) except ZIGBEE_TX_FAILURE: _LOGGER.warning( "Transmission failure when attempting to get output pin status" " from ZigBee device at address: %s", hexlify(self._config.address)) return except ZIGBEE_EXCEPTION as exc: _LOGGER.exception( "Unable to get output pin status from ZigBee device: %s", exc) return self._state = self._config.state2bool[pin_state] class ZigBeeAnalogIn(Entity): """Representation of a GPIO pin configured as an analog input.""" def __init__(self, hass, config): """Initialize the ZigBee analog in device.""" self._config = config self._value = None async def async_added_to_hass(self): """Register callbacks.""" def handle_frame(frame): """Handle an incoming frame. Handle an incoming frame and update our status if it contains information relating to this device. """ if not frame_is_relevant(self, frame): return sample = frame['samples'].pop() pin_name = ANALOG_PINS[self._config.pin] if pin_name not in sample: # Doesn't contain information about our pin return self._value = CONVERT_ADC( sample[pin_name], ADC_PERCENTAGE, self._config.max_voltage ) self.schedule_update_ha_state() async_dispatcher_connect( self.hass, SIGNAL_ZIGBEE_FRAME_RECEIVED, handle_frame) @property def name(self): """Return the name of the input.""" return self._config.name @property def config(self): """Return the entity's configuration.""" return self._config @property def should_poll(self): """Return the polling state, if needed.""" return self._config.should_poll @property def state(self): """Return the state of the entity.""" return self._value @property def unit_of_measurement(self): """Return the unit this state is expressed in.""" return "%" def update(self): """Get the latest reading from the ADC.""" try: self._value = DEVICE.read_analog_pin( self._config.pin, self._config.max_voltage, self._config.address, ADC_PERCENTAGE) except ZIGBEE_TX_FAILURE: _LOGGER.warning( "Transmission failure when attempting to get sample from " "ZigBee device at address: %s", hexlify(self._config.address)) except ZIGBEE_EXCEPTION as exc: _LOGGER.exception( "Unable to get sample from ZigBee device: %s", exc)
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/zigbee/__init__.py
"""Lockitron lock platform.""" import logging import requests import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.lock import LockDevice, PLATFORM_SCHEMA from homeassistant.const import CONF_ACCESS_TOKEN, CONF_ID _LOGGER = logging.getLogger(__name__) DOMAIN = 'lockitron' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_ACCESS_TOKEN): cv.string, vol.Required(CONF_ID): cv.string }) BASE_URL = 'https://api.lockitron.com' API_STATE_URL = BASE_URL + '/v2/locks/{}?access_token={}' API_ACTION_URL = BASE_URL + '/v2/locks/{}?access_token={}&state={}' def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Lockitron platform.""" access_token = config.get(CONF_ACCESS_TOKEN) device_id = config.get(CONF_ID) response = requests.get( API_STATE_URL.format(device_id, access_token), timeout=5) if response.status_code == 200: add_entities([Lockitron(response.json()['state'], access_token, device_id)]) else: _LOGGER.error( "Error retrieving lock status during init: %s", response.text) class Lockitron(LockDevice): """Representation of a Lockitron lock.""" LOCK_STATE = 'lock' UNLOCK_STATE = 'unlock' def __init__(self, state, access_token, device_id): """Initialize the lock.""" self._state = state self.access_token = access_token self.device_id = device_id @property def name(self): """Return the name of the device.""" return DOMAIN @property def is_locked(self): """Return True if the lock is currently locked, else False.""" return self._state == Lockitron.LOCK_STATE def lock(self, **kwargs): """Lock the device.""" self._state = self.do_change_request(Lockitron.LOCK_STATE) def unlock(self, **kwargs): """Unlock the device.""" self._state = self.do_change_request(Lockitron.UNLOCK_STATE) def update(self): """Update the internal state of the device.""" response = requests.get(API_STATE_URL.format( self.device_id, self.access_token), timeout=5) if response.status_code == 200: self._state = response.json()['state'] else: _LOGGER.error("Error retrieving lock status: %s", response.text) def do_change_request(self, requested_state): """Execute the change request and pull out the new state.""" response = requests.put(API_ACTION_URL.format( self.device_id, self.access_token, requested_state), timeout=5) if response.status_code == 200: return response.json()['state'] _LOGGER.error("Error setting lock state: %s\n%s", requested_state, response.text) return self._state
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/lockitron/lock.py
"""Support for monitoring a Sense energy sensor device.""" import logging from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.core import callback from . import SENSE_DATA, SENSE_DEVICE_UPDATE _LOGGER = logging.getLogger(__name__) BIN_SENSOR_CLASS = 'power' MDI_ICONS = { 'ac': 'air-conditioner', 'aquarium': 'fish', 'car': 'car-electric', 'computer': 'desktop-classic', 'cup': 'coffee', 'dehumidifier': 'water-off', 'dishes': 'dishwasher', 'drill': 'toolbox', 'fan': 'fan', 'freezer': 'fridge-top', 'fridge': 'fridge-bottom', 'game': 'gamepad-variant', 'garage': 'garage', 'grill': 'stove', 'heat': 'fire', 'heater': 'radiatior', 'humidifier': 'water', 'kettle': 'kettle', 'leafblower': 'leaf', 'lightbulb': 'lightbulb', 'media_console': 'set-top-box', 'modem': 'router-wireless', 'outlet': 'power-socket-us', 'papershredder': 'shredder', 'printer': 'printer', 'pump': 'water-pump', 'settings': 'settings', 'skillet': 'pot', 'smartcamera': 'webcam', 'socket': 'power-plug', 'sound': 'speaker', 'stove': 'stove', 'trash': 'trash-can', 'tv': 'television', 'vacuum': 'robot-vacuum', 'washer': 'washing-machine', } async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Sense binary sensor.""" if discovery_info is None: return data = hass.data[SENSE_DATA] sense_devices = await data.get_discovered_device_data() devices = [SenseDevice(data, device) for device in sense_devices if device['tags']['DeviceListAllowed'] == 'true'] async_add_entities(devices) def sense_to_mdi(sense_icon): """Convert sense icon to mdi icon.""" return 'mdi:{}'.format(MDI_ICONS.get(sense_icon, 'power-plug')) class SenseDevice(BinarySensorDevice): """Implementation of a Sense energy device binary sensor.""" def __init__(self, data, device): """Initialize the Sense binary sensor.""" self._name = device['name'] self._id = device['id'] self._icon = sense_to_mdi(device['icon']) self._data = data self._undo_dispatch_subscription = None @property def is_on(self): """Return true if the binary sensor is on.""" return self._name in self._data.active_devices @property def name(self): """Return the name of the binary sensor.""" return self._name @property def unique_id(self): """Return the id of the binary sensor.""" return self._id @property def icon(self): """Return the icon of the binary sensor.""" return self._icon @property def device_class(self): """Return the device class of the binary sensor.""" return BIN_SENSOR_CLASS @property def should_poll(self): """Return the deviceshould not poll for updates.""" return False async def async_added_to_hass(self): """Register callbacks.""" @callback def update(): """Update the state.""" self.async_schedule_update_ha_state(True) self._undo_dispatch_subscription = async_dispatcher_connect( self.hass, SENSE_DEVICE_UPDATE, update) async def async_will_remove_from_hass(self): """Undo subscription.""" if self._undo_dispatch_subscription: self._undo_dispatch_subscription()
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/sense/binary_sensor.py
"""Webhook handlers for mobile_app.""" import logging from aiohttp.web import HTTPBadRequest, Response, Request import voluptuous as vol from homeassistant.components.cloud import (async_remote_ui_url, CloudNotAvailable) from homeassistant.components.frontend import MANIFEST_JSON from homeassistant.components.zone.const import DOMAIN as ZONE_DOMAIN from homeassistant.const import (ATTR_DOMAIN, ATTR_SERVICE, ATTR_SERVICE_DATA, CONF_WEBHOOK_ID, HTTP_BAD_REQUEST, HTTP_CREATED) from homeassistant.core import EventOrigin from homeassistant.exceptions import (HomeAssistantError, ServiceNotFound, TemplateError) from homeassistant.helpers import device_registry as dr from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.template import attach from homeassistant.helpers.typing import HomeAssistantType from .const import (ATTR_DEVICE_ID, ATTR_DEVICE_NAME, ATTR_EVENT_DATA, ATTR_EVENT_TYPE, ATTR_MANUFACTURER, ATTR_MODEL, ATTR_OS_VERSION, ATTR_SENSOR_TYPE, ATTR_SENSOR_UNIQUE_ID, ATTR_SUPPORTS_ENCRYPTION, ATTR_TEMPLATE, ATTR_TEMPLATE_VARIABLES, ATTR_WEBHOOK_DATA, ATTR_WEBHOOK_ENCRYPTED, ATTR_WEBHOOK_ENCRYPTED_DATA, ATTR_WEBHOOK_TYPE, CONF_CLOUDHOOK_URL, CONF_REMOTE_UI_URL, CONF_SECRET, DATA_CONFIG_ENTRIES, DATA_DELETED_IDS, DATA_STORE, DOMAIN, ERR_ENCRYPTION_REQUIRED, ERR_SENSOR_DUPLICATE_UNIQUE_ID, ERR_SENSOR_NOT_REGISTERED, SIGNAL_SENSOR_UPDATE, WEBHOOK_PAYLOAD_SCHEMA, WEBHOOK_SCHEMAS, WEBHOOK_TYPES, WEBHOOK_TYPE_CALL_SERVICE, WEBHOOK_TYPE_FIRE_EVENT, WEBHOOK_TYPE_GET_CONFIG, WEBHOOK_TYPE_GET_ZONES, WEBHOOK_TYPE_REGISTER_SENSOR, WEBHOOK_TYPE_RENDER_TEMPLATE, WEBHOOK_TYPE_UPDATE_LOCATION, WEBHOOK_TYPE_UPDATE_REGISTRATION, WEBHOOK_TYPE_UPDATE_SENSOR_STATES, SIGNAL_LOCATION_UPDATE) from .helpers import (_decrypt_payload, empty_okay_response, error_response, registration_context, safe_registration, savable_state, webhook_response) _LOGGER = logging.getLogger(__name__) async def handle_webhook(hass: HomeAssistantType, webhook_id: str, request: Request) -> Response: """Handle webhook callback.""" if webhook_id in hass.data[DOMAIN][DATA_DELETED_IDS]: return Response(status=410) headers = {} config_entry = hass.data[DOMAIN][DATA_CONFIG_ENTRIES][webhook_id] registration = config_entry.data try: req_data = await request.json() except ValueError: _LOGGER.warning('Received invalid JSON from mobile_app') return empty_okay_response(status=HTTP_BAD_REQUEST) if (ATTR_WEBHOOK_ENCRYPTED not in req_data and registration[ATTR_SUPPORTS_ENCRYPTION]): _LOGGER.warning("Refusing to accept unencrypted webhook from %s", registration[ATTR_DEVICE_NAME]) return error_response(ERR_ENCRYPTION_REQUIRED, "Encryption required") try: req_data = WEBHOOK_PAYLOAD_SCHEMA(req_data) except vol.Invalid as ex: err = vol.humanize.humanize_error(req_data, ex) _LOGGER.error('Received invalid webhook payload: %s', err) return empty_okay_response() webhook_type = req_data[ATTR_WEBHOOK_TYPE] webhook_payload = req_data.get(ATTR_WEBHOOK_DATA, {}) if req_data[ATTR_WEBHOOK_ENCRYPTED]: enc_data = req_data[ATTR_WEBHOOK_ENCRYPTED_DATA] webhook_payload = _decrypt_payload(registration[CONF_SECRET], enc_data) if webhook_type not in WEBHOOK_TYPES: _LOGGER.error('Received invalid webhook type: %s', webhook_type) return empty_okay_response() data = webhook_payload _LOGGER.debug("Received webhook payload for type %s: %s", webhook_type, data) if webhook_type in WEBHOOK_SCHEMAS: try: data = WEBHOOK_SCHEMAS[webhook_type](webhook_payload) except vol.Invalid as ex: err = vol.humanize.humanize_error(webhook_payload, ex) _LOGGER.error('Received invalid webhook payload: %s', err) return empty_okay_response(headers=headers) context = registration_context(registration) if webhook_type == WEBHOOK_TYPE_CALL_SERVICE: try: await hass.services.async_call(data[ATTR_DOMAIN], data[ATTR_SERVICE], data[ATTR_SERVICE_DATA], blocking=True, context=context) # noqa: E722 pylint: disable=broad-except except (vol.Invalid, ServiceNotFound, Exception) as ex: _LOGGER.error("Error when calling service during mobile_app " "webhook (device name: %s): %s", registration[ATTR_DEVICE_NAME], ex) raise HTTPBadRequest() return empty_okay_response(headers=headers) if webhook_type == WEBHOOK_TYPE_FIRE_EVENT: event_type = data[ATTR_EVENT_TYPE] hass.bus.async_fire(event_type, data[ATTR_EVENT_DATA], EventOrigin.remote, context=context) return empty_okay_response(headers=headers) if webhook_type == WEBHOOK_TYPE_RENDER_TEMPLATE: resp = {} for key, item in data.items(): try: tpl = item[ATTR_TEMPLATE] attach(hass, tpl) resp[key] = tpl.async_render(item.get(ATTR_TEMPLATE_VARIABLES)) # noqa: E722 pylint: disable=broad-except except TemplateError as ex: resp[key] = {"error": str(ex)} return webhook_response(resp, registration=registration, headers=headers) if webhook_type == WEBHOOK_TYPE_UPDATE_LOCATION: hass.helpers.dispatcher.async_dispatcher_send( SIGNAL_LOCATION_UPDATE.format(config_entry.entry_id), data ) return empty_okay_response(headers=headers) if webhook_type == WEBHOOK_TYPE_UPDATE_REGISTRATION: new_registration = {**registration, **data} device_registry = await dr.async_get_registry(hass) device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, identifiers={ (ATTR_DEVICE_ID, registration[ATTR_DEVICE_ID]), (CONF_WEBHOOK_ID, registration[CONF_WEBHOOK_ID]) }, manufacturer=new_registration[ATTR_MANUFACTURER], model=new_registration[ATTR_MODEL], name=new_registration[ATTR_DEVICE_NAME], sw_version=new_registration[ATTR_OS_VERSION] ) hass.config_entries.async_update_entry(config_entry, data=new_registration) return webhook_response(safe_registration(new_registration), registration=registration, headers=headers) if webhook_type == WEBHOOK_TYPE_REGISTER_SENSOR: entity_type = data[ATTR_SENSOR_TYPE] unique_id = data[ATTR_SENSOR_UNIQUE_ID] unique_store_key = "{}_{}".format(webhook_id, unique_id) if unique_store_key in hass.data[DOMAIN][entity_type]: _LOGGER.error("Refusing to re-register existing sensor %s!", unique_id) return error_response(ERR_SENSOR_DUPLICATE_UNIQUE_ID, "{} {} already exists!".format(entity_type, unique_id), status=409) data[CONF_WEBHOOK_ID] = webhook_id hass.data[DOMAIN][entity_type][unique_store_key] = data try: await hass.data[DOMAIN][DATA_STORE].async_save(savable_state(hass)) except HomeAssistantError as ex: _LOGGER.error("Error registering sensor: %s", ex) return empty_okay_response() register_signal = '{}_{}_register'.format(DOMAIN, data[ATTR_SENSOR_TYPE]) async_dispatcher_send(hass, register_signal, data) return webhook_response({'success': True}, registration=registration, status=HTTP_CREATED, headers=headers) if webhook_type == WEBHOOK_TYPE_UPDATE_SENSOR_STATES: resp = {} for sensor in data: entity_type = sensor[ATTR_SENSOR_TYPE] unique_id = sensor[ATTR_SENSOR_UNIQUE_ID] unique_store_key = "{}_{}".format(webhook_id, unique_id) if unique_store_key not in hass.data[DOMAIN][entity_type]: _LOGGER.error("Refusing to update non-registered sensor: %s", unique_store_key) err_msg = '{} {} is not registered'.format(entity_type, unique_id) resp[unique_id] = { 'success': False, 'error': { 'code': ERR_SENSOR_NOT_REGISTERED, 'message': err_msg } } continue entry = hass.data[DOMAIN][entity_type][unique_store_key] new_state = {**entry, **sensor} hass.data[DOMAIN][entity_type][unique_store_key] = new_state safe = savable_state(hass) try: await hass.data[DOMAIN][DATA_STORE].async_save(safe) except HomeAssistantError as ex: _LOGGER.error("Error updating mobile_app registration: %s", ex) return empty_okay_response() async_dispatcher_send(hass, SIGNAL_SENSOR_UPDATE, new_state) resp[unique_id] = {'success': True} return webhook_response(resp, registration=registration, headers=headers) if webhook_type == WEBHOOK_TYPE_GET_ZONES: zones = (hass.states.get(entity_id) for entity_id in sorted(hass.states.async_entity_ids(ZONE_DOMAIN))) return webhook_response(list(zones), registration=registration, headers=headers) if webhook_type == WEBHOOK_TYPE_GET_CONFIG: hass_config = hass.config.as_dict() resp = { 'latitude': hass_config['latitude'], 'longitude': hass_config['longitude'], 'elevation': hass_config['elevation'], 'unit_system': hass_config['unit_system'], 'location_name': hass_config['location_name'], 'time_zone': hass_config['time_zone'], 'components': hass_config['components'], 'version': hass_config['version'], 'theme_color': MANIFEST_JSON['theme_color'], } if CONF_CLOUDHOOK_URL in registration: resp[CONF_CLOUDHOOK_URL] = registration[CONF_CLOUDHOOK_URL] try: resp[CONF_REMOTE_UI_URL] = async_remote_ui_url(hass) except CloudNotAvailable: pass return webhook_response(resp, registration=registration, headers=headers)
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/mobile_app/webhook.py
"""Support for Tesla door locks.""" import logging from homeassistant.components.lock import ENTITY_ID_FORMAT, LockDevice from homeassistant.const import STATE_LOCKED, STATE_UNLOCKED from . import DOMAIN as TESLA_DOMAIN, TeslaDevice _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Tesla lock platform.""" devices = [TeslaLock(device, hass.data[TESLA_DOMAIN]['controller']) for device in hass.data[TESLA_DOMAIN]['devices']['lock']] add_entities(devices, True) class TeslaLock(TeslaDevice, LockDevice): """Representation of a Tesla door lock.""" def __init__(self, tesla_device, controller): """Initialise of the lock.""" self._state = None super().__init__(tesla_device, controller) self.entity_id = ENTITY_ID_FORMAT.format(self.tesla_id) def lock(self, **kwargs): """Send the lock command.""" _LOGGER.debug("Locking doors for: %s", self._name) self.tesla_device.lock() def unlock(self, **kwargs): """Send the unlock command.""" _LOGGER.debug("Unlocking doors for: %s", self._name) self.tesla_device.unlock() @property def is_locked(self): """Get whether the lock is in locked state.""" return self._state == STATE_LOCKED def update(self): """Update state of the lock.""" _LOGGER.debug("Updating state for: %s", self._name) self.tesla_device.update() self._state = STATE_LOCKED if self.tesla_device.is_locked() \ else STATE_UNLOCKED
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/tesla/lock.py
"""Support for setting the Deluge BitTorrent client in Pause.""" import logging import voluptuous as vol from homeassistant.components.switch import PLATFORM_SCHEMA from homeassistant.exceptions import PlatformNotReady from homeassistant.const import ( CONF_HOST, CONF_NAME, CONF_PORT, CONF_PASSWORD, CONF_USERNAME, STATE_OFF, STATE_ON) from homeassistant.helpers.entity import ToggleEntity import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = 'Deluge Switch' DEFAULT_PORT = 58846 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Deluge switch.""" from deluge_client import DelugeRPCClient name = config.get(CONF_NAME) host = config.get(CONF_HOST) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) port = config.get(CONF_PORT) deluge_api = DelugeRPCClient(host, port, username, password) try: deluge_api.connect() except ConnectionRefusedError: _LOGGER.error("Connection to Deluge Daemon failed") raise PlatformNotReady add_entities([DelugeSwitch(deluge_api, name)]) class DelugeSwitch(ToggleEntity): """Representation of a Deluge switch.""" def __init__(self, deluge_client, name): """Initialize the Deluge switch.""" self._name = name self.deluge_client = deluge_client self._state = STATE_OFF self._available = False @property def name(self): """Return the name of the switch.""" return self._name @property def state(self): """Return the state of the device.""" return self._state @property def is_on(self): """Return true if device is on.""" return self._state == STATE_ON @property def available(self): """Return true if device is available.""" return self._available def turn_on(self, **kwargs): """Turn the device on.""" torrent_ids = self.deluge_client.call('core.get_session_state') self.deluge_client.call('core.resume_torrent', torrent_ids) def turn_off(self, **kwargs): """Turn the device off.""" torrent_ids = self.deluge_client.call('core.get_session_state') self.deluge_client.call('core.pause_torrent', torrent_ids) def update(self): """Get the latest data from deluge and updates the state.""" from deluge_client import FailedToReconnectException try: torrent_list = self.deluge_client.call('core.get_torrents_status', {}, ['paused']) self._available = True except FailedToReconnectException: _LOGGER.error("Connection to Deluge Daemon Lost") self._available = False return for torrent in torrent_list.values(): item = torrent.popitem() if not item[1]: self._state = STATE_ON return self._state = STATE_OFF
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/deluge/switch.py
"""Support for Lutron switches.""" import logging from homeassistant.components.switch import SwitchDevice from . import LUTRON_CONTROLLER, LUTRON_DEVICES, LutronDevice _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Lutron switches.""" devs = [] for (area_name, device) in hass.data[LUTRON_DEVICES]['switch']: dev = LutronSwitch(area_name, device, hass.data[LUTRON_CONTROLLER]) devs.append(dev) add_entities(devs, True) class LutronSwitch(LutronDevice, SwitchDevice): """Representation of a Lutron Switch.""" def turn_on(self, **kwargs): """Turn the switch on.""" self._lutron_device.level = 100 def turn_off(self, **kwargs): """Turn the switch off.""" self._lutron_device.level = 0 @property def device_state_attributes(self): """Return the state attributes.""" attr = {} attr['lutron_integration_id'] = self._lutron_device.id return attr @property def is_on(self): """Return true if device is on.""" return self._lutron_device.last_level() > 0
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/lutron/switch.py
"""Config flow to configure the Ambient PWS component.""" import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_API_KEY from homeassistant.core import callback from homeassistant.helpers import aiohttp_client from .const import CONF_APP_KEY, DOMAIN @callback def configured_instances(hass): """Return a set of configured Ambient PWS instances.""" return set( entry.data[CONF_APP_KEY] for entry in hass.config_entries.async_entries(DOMAIN)) @config_entries.HANDLERS.register(DOMAIN) class AmbientStationFlowHandler(config_entries.ConfigFlow): """Handle an Ambient PWS config flow.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_PUSH async def _show_form(self, errors=None): """Show the form to the user.""" data_schema = vol.Schema({ vol.Required(CONF_API_KEY): str, vol.Required(CONF_APP_KEY): str, }) return self.async_show_form( step_id='user', data_schema=data_schema, errors=errors if errors else {}, ) async def async_step_import(self, import_config): """Import a config entry from configuration.yaml.""" return await self.async_step_user(import_config) async def async_step_user(self, user_input=None): """Handle the start of the config flow.""" from aioambient import Client from aioambient.errors import AmbientError if not user_input: return await self._show_form() if user_input[CONF_APP_KEY] in configured_instances(self.hass): return await self._show_form({CONF_APP_KEY: 'identifier_exists'}) session = aiohttp_client.async_get_clientsession(self.hass) client = Client( user_input[CONF_API_KEY], user_input[CONF_APP_KEY], session) try: devices = await client.api.get_devices() except AmbientError: return await self._show_form({'base': 'invalid_key'}) if not devices: return await self._show_form({'base': 'no_devices'}) # The Application Key (which identifies each config entry) is too long # to show nicely in the UI, so we take the first 12 characters (similar # to how GitHub does it): return self.async_create_entry( title=user_input[CONF_APP_KEY][:12], data=user_input)
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/ambient_station/config_flow.py
"""Support for OpenWRT (luci) routers.""" import logging import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA, DeviceScanner) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_SSL, CONF_USERNAME) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DEFAULT_SSL = False PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, }) def get_scanner(hass, config): """Validate the configuration and return a Luci scanner.""" scanner = LuciDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None class LuciDeviceScanner(DeviceScanner): """This class scans for devices connected to an OpenWrt router.""" def __init__(self, config): """Initialize the scanner.""" from openwrt_luci_rpc import OpenWrtRpc self.router = OpenWrtRpc( config[CONF_HOST], config[CONF_USERNAME], config[CONF_PASSWORD], config[CONF_SSL]) self.last_results = {} self.success_init = self.router.is_logged_in() def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [device.mac for device in self.last_results] def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" name = next(( result.hostname for result in self.last_results if result.mac == device), None) return name def get_extra_attributes(self, device): """ Get extra attributes of a device. Some known extra attributes that may be returned in the device tuple include MAC address (mac), network device (dev), IP address (ip), reachable status (reachable), associated router (host), hostname if known (hostname) among others. """ device = next(( result for result in self.last_results if result.mac == device), None) return device._asdict() def _update_info(self): """Check the Luci router for devices.""" result = self.router.get_all_connected_devices( only_reachable=True) _LOGGER.debug("Luci get_all_connected_devices returned: %s", result) last_results = [] for device in result: last_results.append(device) self.last_results = last_results
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/luci/device_tracker.py
"""Support for RainMachine devices.""" import asyncio import logging from datetime import timedelta import voluptuous as vol from homeassistant.config_entries import SOURCE_IMPORT from homeassistant.const import ( ATTR_ATTRIBUTION, CONF_BINARY_SENSORS, CONF_IP_ADDRESS, CONF_PASSWORD, CONF_PORT, CONF_SCAN_INTERVAL, CONF_SENSORS, CONF_SSL, CONF_MONITORED_CONDITIONS, CONF_SWITCHES) from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import aiohttp_client, config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_time_interval from homeassistant.helpers.service import verify_domain_control from .config_flow import configured_instances from .const import ( DATA_CLIENT, DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DEFAULT_SSL, DOMAIN, PROVISION_SETTINGS, RESTRICTIONS_CURRENT, RESTRICTIONS_UNIVERSAL) _LOGGER = logging.getLogger(__name__) DATA_LISTENER = 'listener' PROGRAM_UPDATE_TOPIC = '{0}_program_update'.format(DOMAIN) SENSOR_UPDATE_TOPIC = '{0}_data_update'.format(DOMAIN) ZONE_UPDATE_TOPIC = '{0}_zone_update'.format(DOMAIN) CONF_CONTROLLERS = 'controllers' CONF_PROGRAM_ID = 'program_id' CONF_SECONDS = 'seconds' CONF_ZONE_ID = 'zone_id' CONF_ZONE_RUN_TIME = 'zone_run_time' DEFAULT_ATTRIBUTION = 'Data provided by Green Electronics LLC' DEFAULT_ICON = 'mdi:water' DEFAULT_ZONE_RUN = 60 * 10 TYPE_FLOW_SENSOR = 'flow_sensor' TYPE_FLOW_SENSOR_CLICK_M3 = 'flow_sensor_clicks_cubic_meter' TYPE_FLOW_SENSOR_CONSUMED_LITERS = 'flow_sensor_consumed_liters' TYPE_FLOW_SENSOR_START_INDEX = 'flow_sensor_start_index' TYPE_FLOW_SENSOR_WATERING_CLICKS = 'flow_sensor_watering_clicks' TYPE_FREEZE = 'freeze' TYPE_FREEZE_PROTECTION = 'freeze_protection' TYPE_FREEZE_TEMP = 'freeze_protect_temp' TYPE_HOT_DAYS = 'extra_water_on_hot_days' TYPE_HOURLY = 'hourly' TYPE_MONTH = 'month' TYPE_RAINDELAY = 'raindelay' TYPE_RAINSENSOR = 'rainsensor' TYPE_WEEKDAY = 'weekday' BINARY_SENSORS = { TYPE_FLOW_SENSOR: ('Flow Sensor', 'mdi:water-pump'), TYPE_FREEZE: ('Freeze Restrictions', 'mdi:cancel'), TYPE_FREEZE_PROTECTION: ('Freeze Protection', 'mdi:weather-snowy'), TYPE_HOT_DAYS: ('Extra Water on Hot Days', 'mdi:thermometer-lines'), TYPE_HOURLY: ('Hourly Restrictions', 'mdi:cancel'), TYPE_MONTH: ('Month Restrictions', 'mdi:cancel'), TYPE_RAINDELAY: ('Rain Delay Restrictions', 'mdi:cancel'), TYPE_RAINSENSOR: ('Rain Sensor Restrictions', 'mdi:cancel'), TYPE_WEEKDAY: ('Weekday Restrictions', 'mdi:cancel'), } SENSORS = { TYPE_FLOW_SENSOR_CLICK_M3: ( 'Flow Sensor Clicks', 'mdi:water-pump', 'clicks/m^3'), TYPE_FLOW_SENSOR_CONSUMED_LITERS: ( 'Flow Sensor Consumed Liters', 'mdi:water-pump', 'liter'), TYPE_FLOW_SENSOR_START_INDEX: ( 'Flow Sensor Start Index', 'mdi:water-pump', None), TYPE_FLOW_SENSOR_WATERING_CLICKS: ( 'Flow Sensor Clicks', 'mdi:water-pump', 'clicks'), TYPE_FREEZE_TEMP: ('Freeze Protect Temperature', 'mdi:thermometer', '°C'), } BINARY_SENSOR_SCHEMA = vol.Schema({ vol.Optional(CONF_MONITORED_CONDITIONS, default=list(BINARY_SENSORS)): vol.All(cv.ensure_list, [vol.In(BINARY_SENSORS)]) }) SENSOR_SCHEMA = vol.Schema({ vol.Optional(CONF_MONITORED_CONDITIONS, default=list(SENSORS)): vol.All(cv.ensure_list, [vol.In(SENSORS)]) }) SERVICE_ALTER_PROGRAM = vol.Schema({ vol.Required(CONF_PROGRAM_ID): cv.positive_int, }) SERVICE_ALTER_ZONE = vol.Schema({ vol.Required(CONF_ZONE_ID): cv.positive_int, }) SERVICE_PAUSE_WATERING = vol.Schema({ vol.Required(CONF_SECONDS): cv.positive_int, }) SERVICE_START_PROGRAM_SCHEMA = vol.Schema({ vol.Required(CONF_PROGRAM_ID): cv.positive_int, }) SERVICE_START_ZONE_SCHEMA = vol.Schema({ vol.Required(CONF_ZONE_ID): cv.positive_int, vol.Optional(CONF_ZONE_RUN_TIME, default=DEFAULT_ZONE_RUN): cv.positive_int, }) SERVICE_STOP_PROGRAM_SCHEMA = vol.Schema({ vol.Required(CONF_PROGRAM_ID): cv.positive_int, }) SERVICE_STOP_ZONE_SCHEMA = vol.Schema({ vol.Required(CONF_ZONE_ID): cv.positive_int, }) SWITCH_SCHEMA = vol.Schema({vol.Optional(CONF_ZONE_RUN_TIME): cv.positive_int}) CONTROLLER_SCHEMA = vol.Schema({ vol.Required(CONF_IP_ADDRESS): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): cv.time_period, vol.Optional(CONF_BINARY_SENSORS, default={}): BINARY_SENSOR_SCHEMA, vol.Optional(CONF_SENSORS, default={}): SENSOR_SCHEMA, vol.Optional(CONF_SWITCHES, default={}): SWITCH_SCHEMA, }) CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Required(CONF_CONTROLLERS): vol.All(cv.ensure_list, [CONTROLLER_SCHEMA]), }), }, extra=vol.ALLOW_EXTRA) async def async_setup(hass, config): """Set up the RainMachine component.""" hass.data[DOMAIN] = {} hass.data[DOMAIN][DATA_CLIENT] = {} hass.data[DOMAIN][DATA_LISTENER] = {} if DOMAIN not in config: return True conf = config[DOMAIN] for controller in conf[CONF_CONTROLLERS]: if controller[CONF_IP_ADDRESS] in configured_instances(hass): continue hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={'source': SOURCE_IMPORT}, data=controller)) return True async def async_setup_entry(hass, config_entry): """Set up RainMachine as config entry.""" from regenmaschine import login from regenmaschine.errors import RainMachineError _verify_domain_control = verify_domain_control(hass, DOMAIN) websession = aiohttp_client.async_get_clientsession(hass) try: client = await login( config_entry.data[CONF_IP_ADDRESS], config_entry.data[CONF_PASSWORD], websession, port=config_entry.data[CONF_PORT], ssl=config_entry.data[CONF_SSL]) rainmachine = RainMachine( client, config_entry.data.get(CONF_BINARY_SENSORS, {}).get( CONF_MONITORED_CONDITIONS, list(BINARY_SENSORS)), config_entry.data.get(CONF_SENSORS, {}).get( CONF_MONITORED_CONDITIONS, list(SENSORS)), config_entry.data.get(CONF_ZONE_RUN_TIME, DEFAULT_ZONE_RUN)) await rainmachine.async_update() except RainMachineError as err: _LOGGER.error('An error occurred: %s', err) raise ConfigEntryNotReady hass.data[DOMAIN][DATA_CLIENT][config_entry.entry_id] = rainmachine for component in ('binary_sensor', 'sensor', 'switch'): hass.async_create_task( hass.config_entries.async_forward_entry_setup( config_entry, component)) async def refresh(event_time): """Refresh RainMachine sensor data.""" _LOGGER.debug('Updating RainMachine sensor data') await rainmachine.async_update() async_dispatcher_send(hass, SENSOR_UPDATE_TOPIC) hass.data[DOMAIN][DATA_LISTENER][ config_entry.entry_id] = async_track_time_interval( hass, refresh, timedelta(seconds=config_entry.data[CONF_SCAN_INTERVAL])) @_verify_domain_control async def disable_program(call): """Disable a program.""" await rainmachine.client.programs.disable( call.data[CONF_PROGRAM_ID]) async_dispatcher_send(hass, PROGRAM_UPDATE_TOPIC) @_verify_domain_control async def disable_zone(call): """Disable a zone.""" await rainmachine.client.zones.disable(call.data[CONF_ZONE_ID]) async_dispatcher_send(hass, ZONE_UPDATE_TOPIC) @_verify_domain_control async def enable_program(call): """Enable a program.""" await rainmachine.client.programs.enable(call.data[CONF_PROGRAM_ID]) async_dispatcher_send(hass, PROGRAM_UPDATE_TOPIC) @_verify_domain_control async def enable_zone(call): """Enable a zone.""" await rainmachine.client.zones.enable(call.data[CONF_ZONE_ID]) async_dispatcher_send(hass, ZONE_UPDATE_TOPIC) @_verify_domain_control async def pause_watering(call): """Pause watering for a set number of seconds.""" await rainmachine.client.watering.pause_all(call.data[CONF_SECONDS]) async_dispatcher_send(hass, PROGRAM_UPDATE_TOPIC) @_verify_domain_control async def start_program(call): """Start a particular program.""" await rainmachine.client.programs.start(call.data[CONF_PROGRAM_ID]) async_dispatcher_send(hass, PROGRAM_UPDATE_TOPIC) @_verify_domain_control async def start_zone(call): """Start a particular zone for a certain amount of time.""" await rainmachine.client.zones.start( call.data[CONF_ZONE_ID], call.data[CONF_ZONE_RUN_TIME]) async_dispatcher_send(hass, ZONE_UPDATE_TOPIC) @_verify_domain_control async def stop_all(call): """Stop all watering.""" await rainmachine.client.watering.stop_all() async_dispatcher_send(hass, PROGRAM_UPDATE_TOPIC) @_verify_domain_control async def stop_program(call): """Stop a program.""" await rainmachine.client.programs.stop(call.data[CONF_PROGRAM_ID]) async_dispatcher_send(hass, PROGRAM_UPDATE_TOPIC) @_verify_domain_control async def stop_zone(call): """Stop a zone.""" await rainmachine.client.zones.stop(call.data[CONF_ZONE_ID]) async_dispatcher_send(hass, ZONE_UPDATE_TOPIC) @_verify_domain_control async def unpause_watering(call): """Unpause watering.""" await rainmachine.client.watering.unpause_all() async_dispatcher_send(hass, PROGRAM_UPDATE_TOPIC) for service, method, schema in [ ('disable_program', disable_program, SERVICE_ALTER_PROGRAM), ('disable_zone', disable_zone, SERVICE_ALTER_ZONE), ('enable_program', enable_program, SERVICE_ALTER_PROGRAM), ('enable_zone', enable_zone, SERVICE_ALTER_ZONE), ('pause_watering', pause_watering, SERVICE_PAUSE_WATERING), ('start_program', start_program, SERVICE_START_PROGRAM_SCHEMA), ('start_zone', start_zone, SERVICE_START_ZONE_SCHEMA), ('stop_all', stop_all, {}), ('stop_program', stop_program, SERVICE_STOP_PROGRAM_SCHEMA), ('stop_zone', stop_zone, SERVICE_STOP_ZONE_SCHEMA), ('unpause_watering', unpause_watering, {}), ]: hass.services.async_register(DOMAIN, service, method, schema=schema) return True async def async_unload_entry(hass, config_entry): """Unload an OpenUV config entry.""" hass.data[DOMAIN][DATA_CLIENT].pop(config_entry.entry_id) remove_listener = hass.data[DOMAIN][DATA_LISTENER].pop( config_entry.entry_id) remove_listener() for component in ('binary_sensor', 'sensor', 'switch'): await hass.config_entries.async_forward_entry_unload( config_entry, component) return True class RainMachine: """Define a generic RainMachine object.""" def __init__( self, client, binary_sensor_conditions, sensor_conditions, default_zone_runtime): """Initialize.""" self.binary_sensor_conditions = binary_sensor_conditions self.client = client self.data = {} self.default_zone_runtime = default_zone_runtime self.device_mac = self.client.mac self.sensor_conditions = sensor_conditions async def async_update(self): """Update sensor/binary sensor data.""" from regenmaschine.errors import RainMachineError tasks = {} if (TYPE_FLOW_SENSOR in self.binary_sensor_conditions or any(c in self.sensor_conditions for c in (TYPE_FLOW_SENSOR_CLICK_M3, TYPE_FLOW_SENSOR_CONSUMED_LITERS, TYPE_FLOW_SENSOR_START_INDEX, TYPE_FLOW_SENSOR_WATERING_CLICKS))): tasks[PROVISION_SETTINGS] = self.client.provisioning.settings() if any(c in self.binary_sensor_conditions for c in (TYPE_FREEZE, TYPE_HOURLY, TYPE_MONTH, TYPE_RAINDELAY, TYPE_RAINSENSOR, TYPE_WEEKDAY)): tasks[RESTRICTIONS_CURRENT] = self.client.restrictions.current() if (any(c in self.binary_sensor_conditions for c in (TYPE_FREEZE_PROTECTION, TYPE_HOT_DAYS)) or TYPE_FREEZE_TEMP in self.sensor_conditions): tasks[RESTRICTIONS_UNIVERSAL] = ( self.client.restrictions.universal()) results = await asyncio.gather(*tasks.values(), return_exceptions=True) for operation, result in zip(tasks, results): if isinstance(result, RainMachineError): _LOGGER.error( 'There was an error while updating %s: %s', operation, result) continue self.data[operation] = result class RainMachineEntity(Entity): """Define a generic RainMachine entity.""" def __init__(self, rainmachine): """Initialize.""" self._attrs = {ATTR_ATTRIBUTION: DEFAULT_ATTRIBUTION} self._dispatcher_handlers = [] self._name = None self.rainmachine = rainmachine @property def device_info(self): """Return device registry information for this entity.""" return { 'identifiers': { (DOMAIN, self.rainmachine.client.mac) }, 'name': self.rainmachine.client.name, 'manufacturer': 'RainMachine', 'model': 'Version {0} (API: {1})'.format( self.rainmachine.client.hardware_version, self.rainmachine.client.api_version), 'sw_version': self.rainmachine.client.software_version, } @property def device_state_attributes(self) -> dict: """Return the state attributes.""" return self._attrs @property def name(self) -> str: """Return the name of the entity.""" return self._name async def async_will_remove_from_hass(self): """Disconnect dispatcher listener when removed.""" for handler in self._dispatcher_handlers: handler()
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/rainmachine/__init__.py
"""Constants for the UniFi component.""" import logging LOGGER = logging.getLogger(__package__) DOMAIN = 'unifi' CONTROLLER_ID = '{host}-{site}' CONF_CONTROLLER = 'controller' CONF_POE_CONTROL = 'poe_control' CONF_SITE_ID = 'site'
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/unifi/const.py
"""Support for AVM Fritz!Box smarthome temperature sensor only devices.""" import logging import requests from homeassistant.const import TEMP_CELSIUS from homeassistant.helpers.entity import Entity from . import ( ATTR_STATE_DEVICE_LOCKED, ATTR_STATE_LOCKED, DOMAIN as FRITZBOX_DOMAIN) _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Fritzbox smarthome sensor platform.""" _LOGGER.debug("Initializing fritzbox temperature sensors") devices = [] fritz_list = hass.data[FRITZBOX_DOMAIN] for fritz in fritz_list: device_list = fritz.get_devices() for device in device_list: if (device.has_temperature_sensor and not device.has_switch and not device.has_thermostat): devices.append(FritzBoxTempSensor(device, fritz)) add_entities(devices) class FritzBoxTempSensor(Entity): """The entity class for Fritzbox temperature sensors.""" def __init__(self, device, fritz): """Initialize the switch.""" self._device = device self._fritz = fritz @property def name(self): """Return the name of the device.""" return self._device.name @property def state(self): """Return the state of the sensor.""" return self._device.temperature @property def unit_of_measurement(self): """Return the unit of measurement.""" return TEMP_CELSIUS def update(self): """Get latest data and states from the device.""" try: self._device.update() except requests.exceptions.HTTPError as ex: _LOGGER.warning("Fritzhome connection error: %s", ex) self._fritz.login() @property def device_state_attributes(self): """Return the state attributes of the device.""" attrs = { ATTR_STATE_DEVICE_LOCKED: self._device.device_lock, ATTR_STATE_LOCKED: self._device.lock, } return attrs
"""Test Z-Wave config panel.""" import asyncio import json from unittest.mock import MagicMock, patch import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.components.zwave import DATA_NETWORK, const from tests.mock.zwave import MockNode, MockValue, MockEntityValues VIEW_NAME = 'api:config:zwave:device_config' @pytest.fixture def client(loop, hass, hass_client): """Client to communicate with Z-Wave config views.""" with patch.object(config, 'SECTIONS', ['zwave']): loop.run_until_complete(async_setup_component(hass, 'config', {})) return loop.run_until_complete(hass_client()) @asyncio.coroutine def test_get_device_config(client): """Test getting device config.""" def mock_read(path): """Mock reading data.""" return { 'hello.beer': { 'free': 'beer', }, 'other.entity': { 'do': 'something', }, } with patch('homeassistant.components.config._read', mock_read): resp = yield from client.get( '/api/config/zwave/device_config/hello.beer') assert resp.status == 200 result = yield from resp.json() assert result == {'free': 'beer'} @asyncio.coroutine def test_update_device_config(client): """Test updating device config.""" orig_data = { 'hello.beer': { 'ignored': True, }, 'other.entity': { 'polling_intensity': 2, }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch('homeassistant.components.config._read', mock_read), \ patch('homeassistant.components.config._write', mock_write): resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 200 result = yield from resp.json() assert result == {'result': 'ok'} orig_data['hello.beer']['polling_intensity'] = 2 assert written[0] == orig_data @asyncio.coroutine def test_update_device_config_invalid_key(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/invalid_entity', data=json.dumps({ 'polling_intensity': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_data(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data=json.dumps({ 'invalid_option': 2 })) assert resp.status == 400 @asyncio.coroutine def test_update_device_config_invalid_json(client): """Test updating device config.""" resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', data='not json') assert resp.status == 400 @asyncio.coroutine def test_get_values(hass, client): """Test getting values on node.""" node = MockNode(node_id=1) value = MockValue(value_id=123456, node=node, label='Test Label', instance=1, index=2, poll_intensity=4) values = MockEntityValues(primary=value) node2 = MockNode(node_id=2) value2 = MockValue(value_id=234567, node=node2, label='Test Label 2') values2 = MockEntityValues(primary=value2) hass.data[const.DATA_ENTITY_VALUES] = [values, values2] resp = yield from client.get('/api/zwave/values/1') assert resp.status == 200 result = yield from resp.json() assert result == { '123456': { 'label': 'Test Label', 'instance': 1, 'index': 2, 'poll_intensity': 4, } } @asyncio.coroutine def test_get_groups(hass, client): """Test getting groupdata on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) node.groups.associations = 'assoc' node.groups.associations_instances = 'inst' node.groups.label = 'the label' node.groups.max_associations = 'max' node.groups = {1: node.groups} network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == { '1': { 'association_instances': 'inst', 'associations': 'assoc', 'label': 'the label', 'max_associations': 'max' } } @asyncio.coroutine def test_get_groups_nogroups(hass, client): """Test getting groupdata on node with no groups.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_groups_nonode(hass, client): """Test getting groupdata on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/groups/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_config(hass, client): """Test getting config on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) value = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION) value.label = 'label' value.help = 'help' value.type = 'type' value.data = 'data' value.data_items = ['item1', 'item2'] value.max = 'max' value.min = 'min' node.values = {12: value} network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {'12': {'data': 'data', 'data_items': ['item1', 'item2'], 'help': 'help', 'label': 'label', 'max': 'max', 'min': 'min', 'type': 'type'}} @asyncio.coroutine def test_get_config_noconfig_node(hass, client): """Test getting config on node without config.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=2) network.nodes = {2: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/config/2') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_config_nonode(hass, client): """Test getting config on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/config/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes_nonode(hass, client): """Test getting usercodes on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() network.nodes = {1: 1, 5: 5} resp = yield from client.get('/api/zwave/usercodes/2') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'Node not found'} @asyncio.coroutine def test_get_usercodes(hass, client): """Test getting usercodes on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_USER value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {'0': {'code': '1234', 'label': 'label', 'length': 4}} @asyncio.coroutine def test_get_usercode_nousercode_node(hass, client): """Test getting usercodes on node without usercodes.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_get_usercodes_no_genreuser(hass, client): """Test getting usercodes on node missing genre user.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_USER_CODE]) value = MockValue( index=0, command_class=const.COMMAND_CLASS_USER_CODE) value.genre = const.GENRE_SYSTEM value.label = 'label' value.data = '1234' node.values = {0: value} network.nodes = {18: node} node.get_values.return_value = node.values resp = yield from client.get('/api/zwave/usercodes/18') assert resp.status == 200 result = yield from resp.json() assert result == {} @asyncio.coroutine def test_save_config_no_network(hass, client): """Test saving configuration without network data.""" resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 404 result = yield from resp.json() assert result == {'message': 'No Z-Wave network data found'} @asyncio.coroutine def test_save_config(hass, client): """Test saving configuration.""" network = hass.data[DATA_NETWORK] = MagicMock() resp = yield from client.post('/api/zwave/saveconfig') assert resp.status == 200 result = yield from resp.json() assert network.write_config.called assert result == {'message': 'Z-Wave configuration saved to file.'} async def test_get_protection_values(hass, client): """Test getting protection values on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.get_protection_item.return_value = "Unprotected" node.get_protection_items.return_value = value.data_items node.get_protections.return_value = {value.value_id: 'Object'} resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert node.get_protections.called assert node.get_protection_item.called assert node.get_protection_items.called assert result == { 'value_id': '123456', 'selected': 'Unprotected', 'options': ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] } async def test_get_protection_values_nonexisting_node(hass, client): """Test getting protection values on node with wrong nodeid.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 404 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {'message': 'Node not found'} async def test_get_protection_values_without_protectionclass(hass, client): """Test getting protection values on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {18: node} node.value = value resp = await client.get('/api/zwave/protection/18') assert resp.status == 200 result = await resp.json() assert not node.get_protections.called assert not node.get_protection_item.called assert not node.get_protection_items.called assert result == {} async def test_set_protection_value(hass, client): """Test setting protection value on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protection by Sequence'})) assert resp.status == 200 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting succsessfully set'} async def test_set_protection_value_failed(hass, client): """Test setting protection value failed on node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=18, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {18: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 202 result = await resp.json() assert node.set_protection.called assert result == {'message': 'Protection setting did not complete'} async def test_set_protection_value_nonexisting_node(hass, client): """Test setting protection value on nonexisting node.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17, command_classes=[const.COMMAND_CLASS_PROTECTION]) value = MockValue( value_id=123456, index=0, instance=1, command_class=const.COMMAND_CLASS_PROTECTION) value.label = 'Protection Test' value.data_items = ['Unprotected', 'Protection by Sequence', 'No Operation Possible'] value.data = 'Unprotected' network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/18', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'Node not found'} async def test_set_protection_value_missing_class(hass, client): """Test setting protection value on node without protectionclass.""" network = hass.data[DATA_NETWORK] = MagicMock() node = MockNode(node_id=17) value = MockValue( value_id=123456, index=0, instance=1) network.nodes = {17: node} node.value = value node.set_protection.return_value = False resp = await client.post( '/api/zwave/protection/17', data=json.dumps({ 'value_id': '123456', 'selection': 'Protecton by Seuence'})) assert resp.status == 404 result = await resp.json() assert not node.set_protection.called assert result == {'message': 'No protection commandclass on this node'}
aequitas/home-assistant
tests/components/config/test_zwave.py
homeassistant/components/fritzbox/sensor.py
import numpy from mpi4py import MPI import warnings import functools import contextlib import os, sys def is_structured_array(arr): """ Test if the input array is a structured array by testing for `dtype.names` """ if not isinstance(arr, numpy.ndarray) or not hasattr(arr, 'dtype'): return False return arr.dtype.char == 'V' def get_data_bounds(data, comm, selection=None): """ Return the global minimum/maximum of a numpy/dask array along the first axis. This is computed in chunks to avoid memory errors on large data. Parameters ---------- data : numpy.ndarray or dask.array.Array the data to find the bounds of comm : the MPI communicator Returns ------- min, max : the min/max of ``data`` """ import dask.array as da # local min/max on this rank dmin = numpy.ones(data.shape[1:]) * (numpy.inf) dmax = numpy.ones_like(dmin) * (-numpy.inf) # max size Nlocalmax = max(comm.allgather(len(data))) # compute in chunks to avoid memory error chunksize = 1024**2 * 8 for i in range(0, Nlocalmax, chunksize): s = slice(i, i + chunksize) if len(data) != 0: # selection has to be computed many times when data is `large`. if selection is not None: sel = selection[s] if isinstance(selection, da.Array): sel = sel.compute() # be sure to use the source to compute d = data[s] if isinstance(data, da.Array): d = d.compute() # select if selection is not None: d = d[sel] # update min/max on this rank dmin = numpy.min([d.min(axis=0), dmin], axis=0) dmax = numpy.max([d.max(axis=0), dmax], axis=0) # global min/max across all ranks dmin = numpy.asarray(comm.allgather(dmin)).min(axis=0) dmax = numpy.asarray(comm.allgather(dmax)).max(axis=0) return dmin, dmax def split_size_3d(s): """ Split `s` into three integers, a, b, c, such that a * b * c == s and a <= b <= c Parameters ----------- s : int integer to split Returns ------- a, b, c: int integers such that a * b * c == s and a <= b <= c """ a = int(s** 0.3333333) + 1 d = s while a > 1: if s % a == 0: s = s // a break a = a - 1 b = int(s ** 0.5) + 1 while b > 1: if s % b == 0: s = s // b break b = b - 1 c = s return a, b, c def deprecate(name, alternative, alt_name=None): """ This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emmitted when the function is used. """ alt_name = alt_name or alternative.__name__ def wrapper(*args, **kwargs): warnings.warn("%s is deprecated. Use %s instead" % (name, alt_name), FutureWarning, stacklevel=2) return alternative(*args, **kwargs) return wrapper def GatherArray(data, comm, root=0): """ Gather the input data array from all ranks to the specified ``root``. This uses `Gatherv`, which avoids mpi4py pickling, and also avoids the 2 GB mpi4py limit for bytes using a custom datatype Parameters ---------- data : array_like the data on each rank to gather comm : MPI communicator the MPI communicator root : int, or Ellipsis the rank number to gather the data to. If root is Ellipsis, broadcast the result to all ranks. Returns ------- recvbuffer : array_like, None the gathered data on root, and `None` otherwise """ if not isinstance(data, numpy.ndarray): raise ValueError("`data` must by numpy array in GatherArray") # need C-contiguous order if not data.flags['C_CONTIGUOUS']: data = numpy.ascontiguousarray(data) local_length = data.shape[0] # check dtypes and shapes shapes = comm.allgather(data.shape) dtypes = comm.allgather(data.dtype) # check for structured data if dtypes[0].char == 'V': # check for structured data mismatch names = set(dtypes[0].names) if any(set(dt.names) != names for dt in dtypes[1:]): raise ValueError("mismatch between data type fields in structured data") # check for 'O' data types if any(dtypes[0][name] == 'O' for name in dtypes[0].names): raise ValueError("object data types ('O') not allowed in structured data in GatherArray") # compute the new shape for each rank newlength = comm.allreduce(local_length) newshape = list(data.shape) newshape[0] = newlength # the return array if root is Ellipsis or comm.rank == root: recvbuffer = numpy.empty(newshape, dtype=dtypes[0], order='C') else: recvbuffer = None for name in dtypes[0].names: d = GatherArray(data[name], comm, root=root) if root is Ellipsis or comm.rank == root: recvbuffer[name] = d return recvbuffer # check for 'O' data types if dtypes[0] == 'O': raise ValueError("object data types ('O') not allowed in structured data in GatherArray") # check for bad dtypes and bad shapes if root is Ellipsis or comm.rank == root: bad_shape = any(s[1:] != shapes[0][1:] for s in shapes[1:]) bad_dtype = any(dt != dtypes[0] for dt in dtypes[1:]) else: bad_shape = None; bad_dtype = None bad_shape, bad_dtype = comm.bcast((bad_shape, bad_dtype)) if bad_shape: raise ValueError("mismatch between shape[1:] across ranks in GatherArray") if bad_dtype: raise ValueError("mismatch between dtypes across ranks in GatherArray") shape = data.shape dtype = data.dtype # setup the custom dtype duplicity = numpy.product(numpy.array(shape[1:], 'intp')) itemsize = duplicity * dtype.itemsize dt = MPI.BYTE.Create_contiguous(itemsize) dt.Commit() # compute the new shape for each rank newlength = comm.allreduce(local_length) newshape = list(shape) newshape[0] = newlength # the return array if root is Ellipsis or comm.rank == root: recvbuffer = numpy.empty(newshape, dtype=dtype, order='C') else: recvbuffer = None # the recv counts counts = comm.allgather(local_length) counts = numpy.array(counts, order='C') # the recv offsets offsets = numpy.zeros_like(counts, order='C') offsets[1:] = counts.cumsum()[:-1] # gather to root if root is Ellipsis: comm.Allgatherv([data, dt], [recvbuffer, (counts, offsets), dt]) else: comm.Gatherv([data, dt], [recvbuffer, (counts, offsets), dt], root=root) dt.Free() return recvbuffer def ScatterArray(data, comm, root=0, counts=None): """ Scatter the input data array across all ranks, assuming `data` is initially only on `root` (and `None` on other ranks). This uses ``Scatterv``, which avoids mpi4py pickling, and also avoids the 2 GB mpi4py limit for bytes using a custom datatype Parameters ---------- data : array_like or None on `root`, this gives the data to split and scatter comm : MPI communicator the MPI communicator root : int the rank number that initially has the data counts : list of int list of the lengths of data to send to each rank Returns ------- recvbuffer : array_like the chunk of `data` that each rank gets """ import logging if counts is not None: counts = numpy.asarray(counts, order='C') if len(counts) != comm.size: raise ValueError("counts array has wrong length!") # check for bad input if comm.rank == root: bad_input = not isinstance(data, numpy.ndarray) else: bad_input = None bad_input = comm.bcast(bad_input) if bad_input: raise ValueError("`data` must by numpy array on root in ScatterArray") if comm.rank == 0: # need C-contiguous order if not data.flags['C_CONTIGUOUS']: data = numpy.ascontiguousarray(data) shape_and_dtype = (data.shape, data.dtype) else: shape_and_dtype = None # each rank needs shape/dtype of input data shape, dtype = comm.bcast(shape_and_dtype) # object dtype is not supported fail = False if dtype.char == 'V': fail = any(dtype[name] == 'O' for name in dtype.names) else: fail = dtype == 'O' if fail: raise ValueError("'object' data type not supported in ScatterArray; please specify specific data type") # initialize empty data on non-root ranks if comm.rank != root: np_dtype = numpy.dtype((dtype, shape[1:])) data = numpy.empty(0, dtype=np_dtype) # setup the custom dtype duplicity = numpy.product(numpy.array(shape[1:], 'intp')) itemsize = duplicity * dtype.itemsize dt = MPI.BYTE.Create_contiguous(itemsize) dt.Commit() # compute the new shape for each rank newshape = list(shape) if counts is None: newlength = shape[0] // comm.size if comm.rank < shape[0] % comm.size: newlength += 1 newshape[0] = newlength else: if counts.sum() != shape[0]: raise ValueError("the sum of the `counts` array needs to be equal to data length") newshape[0] = counts[comm.rank] # the return array recvbuffer = numpy.empty(newshape, dtype=dtype, order='C') # the send counts, if not provided if counts is None: counts = comm.allgather(newlength) counts = numpy.array(counts, order='C') # the send offsets offsets = numpy.zeros_like(counts, order='C') offsets[1:] = counts.cumsum()[:-1] # do the scatter comm.Barrier() comm.Scatterv([data, (counts, offsets), dt], [recvbuffer, dt]) dt.Free() return recvbuffer def FrontPadArray(array, front, comm): """ Padding an array in the front with items before this rank. """ N = numpy.array(comm.allgather(len(array)), dtype='intp') offsets = numpy.cumsum(numpy.concatenate([[0], N], axis=0)) mystart = offsets[comm.rank] - front torecv = (offsets[:-1] + N) - mystart torecv[torecv < 0] = 0 # before mystart torecv[torecv > front] = 0 # no more than needed torecv[torecv > N] = N[torecv > N] # fully enclosed if comm.allreduce(torecv.sum() != front, MPI.LOR): raise ValueError("cannot work out a plan to padd items. Some front values are too large. %d %d" % (torecv.sum(), front)) tosend = comm.alltoall(torecv) sendbuf = [ array[-items:] if items > 0 else array[0:0] for i, items in enumerate(tosend)] recvbuf = comm.alltoall(sendbuf) return numpy.concatenate(list(recvbuf) + [array], axis=0) def attrs_to_dict(obj, prefix): if not hasattr(obj, 'attrs'): return {} d = {} for key, value in obj.attrs.items(): d[prefix + key] = value return d import json from astropy.units import Quantity, Unit from nbodykit.cosmology import Cosmology class JSONEncoder(json.JSONEncoder): """ A subclass of :class:`json.JSONEncoder` that can also handle numpy arrays, complex values, and :class:`astropy.units.Quantity` objects. """ def default(self, obj): # Cosmology object if isinstance(obj, Cosmology): d = {} d['__cosmo__'] = obj.pars.copy() return d # astropy quantity if isinstance(obj, Quantity): d = {} d['__unit__'] = str(obj.unit) value = obj.value if obj.size > 1: d['__dtype__'] = value.dtype.str if value.dtype.names is None else value.dtype.descr d['__shape__'] = value.shape value = value.tolist() d['__data__'] = value return d # complex values elif isinstance(obj, complex): return {'__complex__': [obj.real, obj.imag ]} # numpy arrays elif isinstance(obj, numpy.ndarray): value = obj dtype = obj.dtype d = { '__dtype__' : dtype.str if dtype.names is None else dtype.descr, '__shape__' : value.shape, '__data__': value.tolist(), } return d # explicity convert numpy data types to python types # see: https://bugs.python.org/issue24313 elif isinstance(obj, numpy.floating): return float(obj) elif isinstance(obj, numpy.integer): return int(obj) return json.JSONEncoder.default(self, obj) class JSONDecoder(json.JSONDecoder): """ A subclass of :class:`json.JSONDecoder` that can also handle numpy arrays, complex values, and :class:`astropy.units.Quantity` objects. """ @staticmethod def hook(value): def fixdtype(dtype): if isinstance(dtype, list): true_dtype = [] for field in dtype: if len(field) == 3: true_dtype.append((str(field[0]), str(field[1]), field[2])) if len(field) == 2: true_dtype.append((str(field[0]), str(field[1]))) return true_dtype return dtype def fixdata(data, N, dtype): if not isinstance(dtype, list): return data # for structured array, # the last dimension shall be a tuple if N > 0: return [fixdata(i, N - 1, dtype) for i in data] else: assert len(data) == len(dtype) return tuple(data) d = None if '__dtype__' in value: dtype = fixdtype(value['__dtype__']) shape = value['__shape__'] a = fixdata(value['__data__'], len(shape), dtype) d = numpy.array(a, dtype=dtype) if '__unit__' in value: if d is None: d = value['__data__'] d = Quantity(d, Unit(value['__unit__'])) if '__cosmo__' in value: d = Cosmology.from_dict(value['__cosmo__']) if d is not None: return d if '__complex__' in value: real, imag = value['__complex__'] return real + 1j * imag return value def __init__(self, *args, **kwargs): kwargs['object_hook'] = JSONDecoder.hook json.JSONDecoder.__init__(self, *args, **kwargs) def timer(start, end): """ Utility function to return a string representing the elapsed time, as computed from the input start and end times Parameters ---------- start : int the start time in seconds end : int the end time in seconds Returns ------- str : the elapsed time as a string, using the format `hours:minutes:seconds` """ hours, rem = divmod(end-start, 3600) minutes, seconds = divmod(rem, 60) return "{:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds) @contextlib.contextmanager def captured_output(comm, root=0): """ Re-direct stdout and stderr to null for every rank but ``root`` """ # keep output on root if root is not None and comm.rank == root: yield sys.stdout, sys.stderr else: from six.moves import StringIO from nbodykit.extern.wurlitzer import sys_pipes # redirect stdout and stderr old_stdout, sys.stdout = sys.stdout, StringIO() old_stderr, sys.stderr = sys.stderr, StringIO() try: with sys_pipes() as (out, err): yield out, err finally: sys.stdout = old_stdout sys.stderr = old_stderr import mpsort class DistributedArray(object): """ Distributed Array Object A distributed array is striped along ranks, along first dimension Attributes ---------- comm : :py:class:`mpi4py.MPI.Comm` the communicator local : array_like the local data """ @staticmethod def _find_dtype(dtype, comm): # guess the dtype dtypes = comm.allgather(dtype) dtypes = set([dtype for dtype in dtypes if dtype is not None]) if len(dtypes) > 1: raise TypeError("Type of local array is inconsistent between ranks; got %s" % dtypes) return next(iter(dtypes)) @staticmethod def _find_cshape(shape, comm): # guess the dtype shapes = comm.allgather(shape) shapes = set(shape[1:] for shape in shapes) if len(shapes) > 1: raise TypeError("Shape of local array is inconsistent between ranks; got %s" % shapes) clen = comm.allreduce(shape[0]) cshape = tuple([clen] + list(shape[1:])) return cshape def __init__(self, local, comm): self.comm = comm shape = numpy.array(local, copy=False).shape dtype = numpy.array(local, copy=False).dtype if len(local) else None self.dtype = DistributedArray._find_dtype(dtype, comm) self.cshape = DistributedArray._find_cshape(shape, comm) # directly use the original local array. self.local = local self.topology = LinearTopology(local, comm) self.coffset = sum(comm.allgather(shape[0])[:comm.rank]) @classmethod def cempty(kls, cshape, dtype, comm): """ Create an empty array collectively """ dtype = DistributedArray._find_dtype(dtype, comm) cshape = tuple(cshape) llen = cshape[0] * (comm.rank + 1) // comm.size - cshape[0] * (comm.rank) // comm.size shape = tuple([llen] + list(cshape[1:])) cshape1 = DistributedArray._find_cshape(shape, comm) if cshape != cshape1: raise ValueError("input cshape is inconsistent %s %s" % (cshape, cshape1)) local = numpy.empty(shape, dtype=dtype) return DistributedArray(local, comm=comm) @classmethod def concat(kls, *args, **kwargs): """ Append several distributed arrays into one. Parameters ---------- localsize : None """ localsize = kwargs.pop('localsize', None) comm = args[0].comm localsize_in = sum([len(arg.local) for arg in args]) if localsize is None: localsize = sum([len(arg.local) for arg in args]) eldtype = numpy.result_type(*[arg.local for arg in args]) dtype = [('index', 'intp'), ('el', eldtype)] inp = numpy.empty(localsize_in, dtype=dtype) out = numpy.empty(localsize, dtype=dtype) go = 0 o = 0 for arg in args: inp['index'][o:o + len(arg.local)] = go + arg.coffset + numpy.arange(len(arg.local), dtype='intp') inp['el'][o:o + len(arg.local)] = arg.local o = o + len(arg.local) go = go + arg.cshape[0] mpsort.sort(inp, orderby='index', out=out, comm=comm) return DistributedArray(out['el'].copy(), comm=comm) def sort(self, orderby=None): """ Sort array globally by key orderby. Due to a limitation of mpsort, self[orderby] must be u8. """ mpsort.sort(self.local, orderby, comm=self.comm) def __getitem__(self, key): return DistributedArray(self.local[key], self.comm) def unique_labels(self): """ Assign unique labels to sorted local. .. warning :: local data must be globally sorted, and of simple type. (numpy.unique) Returns ------- label : :py:class:`DistributedArray` the new labels, starting from 0 """ prev, next = self.topology.prev(), self.topology.next() junk, label = numpy.unique(self.local, return_inverse=True) if len(label) == 0: # work around numpy bug (<=1.13.3) when label is empty it # spits out booleans?? booleans!! # this causes issues when type cast rules in numpy # are tighten up. label = numpy.int64(label) if len(self.local) == 0: Nunique = 0 else: # watch out: this is to make sure after shifting first # labels on the next rank is the same as my last label # when there is a spill-over. if next == self.local[-1]: Nunique = len(junk) - 1 else: Nunique = len(junk) label += numpy.sum(self.comm.allgather(Nunique)[:self.comm.rank], dtype='intp') return DistributedArray(label, self.comm) def bincount(self, weights=None, local=False, shared_edges=True): """ Assign count numbers from sorted local data. .. warning :: local data must be globally sorted, and of integer type. (numpy.bincount) Parameters ---------- weights: array-like if given, count the weight instead of the number of objects. local : boolean if local is True, only count the local array. shared_edges : boolean if True, keep the counts at edges that are shared between ranks on both ranks. if False, keep the counts at shared edges to the rank on the left. Returns ------- N : :py:class:`DistributedArray` distributed counts array. If items of the same value spans other chunks of array, they are added to N as well. Examples -------- if the local array is [ (0, 0), (0, 1)], Then the counts array is [ (3, ), (3, 1)] """ prev = self.topology.prev() if prev is not EmptyRank: offset = prev if len(self.local) > 0: if prev != self.local[0]: offset = self.local[0] else: offset = 0 N = numpy.bincount(self.local - offset, weights) if local: return N heads = self.topology.heads() tails = self.topology.tails() distN = DistributedArray(N, self.comm) headsN, tailsN = distN.topology.heads(), distN.topology.tails() if len(N) > 0: anyshared = False for i in reversed(range(self.comm.rank)): if tails[i] == self.local[0]: N[0] += tailsN[i] anyshared = True for i in range(self.comm.rank + 1, self.comm.size): if heads[i] == self.local[-1]: N[-1] += headsN[i] if not shared_edges: # remove the edge from me, as it s already on the left rank. if anyshared: N = N[1:] return DistributedArray(N, self.comm) def _get_empty_rank(): return EmptyRank class EmptyRankType(object): def __repr__(self): return "EmptyRank" def __reduce__(self): return (_get_empty_rank, ()) EmptyRank = EmptyRankType() class LinearTopology(object): """ Helper object for the topology of a distributed array """ def __init__(self, local, comm): self.local = local self.comm = comm def heads(self): """ The first items on each rank. Returns ------- heads : list a list of first items, EmptyRank is used for empty ranks """ head = EmptyRank if len(self.local) > 0: head = self.local[0] return self.comm.allgather(head) def tails(self): """ The last items on each rank. Returns ------- tails: list a list of last items, EmptyRank is used for empty ranks """ tail = EmptyRank if len(self.local) > 0: tail = self.local[-1] return self.comm.allgather(tail) def prev(self): """ The item before the local data. This method fetches the last item before the local data. If the rank before is empty, the rank before is used. If no item is before this rank, EmptyRank is returned Returns ------- prev : scalar Item before local data, or EmptyRank if all ranks before this rank is empty. """ tails = self.tails() for prev in reversed(tails[:self.comm.rank]): if prev is not EmptyRank: return prev return EmptyRank def next(self): """ The item after the local data. This method the first item after the local data. If the rank after current rank is empty, item after that rank is used. If no item is after local data, EmptyRank is returned. Returns ------- next : scalar Item after local data, or EmptyRank if all ranks after this rank is empty. """ heads = self.heads() for next in heads[self.comm.rank + 1:]: if next is not EmptyRank: return next return EmptyRank
from runtests.mpi import MPITest from nbodykit import setup_logging from nbodykit.binned_statistic import BinnedStatistic import pytest import tempfile import numpy.testing as testing import numpy import os data_dir = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'data') setup_logging("debug") @MPITest([1]) def test_to_json(comm): # load from JSON ds1 = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_1d.json')) # to JSON with tempfile.NamedTemporaryFile(delete=False) as ff: ds1.to_json(ff.name) ds2 = BinnedStatistic.from_json(ff.name) # same data? for name in ds1: testing.assert_almost_equal(ds1[name], ds2[name]) # cleanup os.remove(ff.name) @MPITest([1]) def test_1d_load(comm): # load plaintext format with pytest.warns(FutureWarning): ds1 = BinnedStatistic.from_plaintext(['k'], os.path.join(data_dir, 'dataset_1d_deprecated.dat')) # wrong dimensions with pytest.raises(ValueError): ds1 = BinnedStatistic.from_plaintext(['k', 'mu'], os.path.join(data_dir, 'dataset_1d_deprecated.dat')) # load from JSON ds2 = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_1d.json')) # same data? for name in ds1: testing.assert_almost_equal(ds1[name], ds2[name]) @MPITest([1]) def test_2d_load(comm): # load plaintext format with pytest.warns(FutureWarning): ds1 = BinnedStatistic.from_plaintext(['k', 'mu'], os.path.join(data_dir, 'dataset_2d_deprecated.dat')) # load from JSON ds2 = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # same data? for name in ds1: testing.assert_almost_equal(ds1[name], ds2[name]) @MPITest([1]) def test_str(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # list all variable names s = str(dataset) # now just list total number of variables dataset['test1'] = numpy.ones(dataset.shape) dataset['test2'] = numpy.ones(dataset.shape) s = str(dataset) # this is the same as str r = repr(dataset) @MPITest([1]) def test_getitem(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # invalid key with pytest.raises(KeyError): bad = dataset['error'] # slice columns sliced = dataset[['k', 'mu', 'power']] sliced = dataset[('k', 'mu', 'power')] # invalid slice with pytest.raises(KeyError): bad =dataset[['k', 'mu', 'error']] # too many dims in slice with pytest.raises(IndexError): bad = dataset[0,0,0] # cannot access single element of 2D power with pytest.raises(IndexError): bad = dataset[0,0] @MPITest([1]) def test_array_slice(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # get the first mu column sliced = dataset[:,0] assert sliced.shape[0] == dataset.shape[0] assert len(sliced.shape) == 1 assert sliced.dims == ['k'] # get the first mu column but keep dimension sliced = dataset[:,[0]] assert sliced.shape[0] == dataset.shape[0] assert sliced.shape[1] == 1 assert sliced.dims == ['k', 'mu'] @MPITest([1]) def test_list_array_slice(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # get the first and last mu column sliced = dataset[:,[0, -1]] assert len(sliced.shape) == 2 assert sliced.dims == ['k', 'mu'] # make sure we grabbed the right data for var in dataset: testing.assert_array_equal(dataset[var][:,[0,-1]], sliced[var]) @MPITest([1]) def test_variable_set(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) modes = numpy.ones(dataset.shape) # add new variable dataset['TEST'] = modes assert 'TEST' in dataset # override existing variable dataset['modes'] = modes assert numpy.all(dataset['modes'] == 1.0) # needs right shape with pytest.raises(ValueError): dataset['TEST'] = 10. @MPITest([1]) def test_copy(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) copy = dataset.copy() for var in dataset: testing.assert_array_equal(dataset[var], copy[var]) @MPITest([1]) def test_rename_variable(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) test = numpy.zeros(dataset.shape) dataset['test'] = test dataset.rename_variable('test', 'renamed_test') assert 'renamed_test' in dataset assert 'test' not in dataset @MPITest([1]) def test_sel(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # no exact match fails with pytest.raises(IndexError): sliced = dataset.sel(k=0.1) # this should be squeezed sliced = dataset.sel(k=0.1, method='nearest') assert len(sliced.dims) == 1 # this is not squeezed sliced = dataset.sel(k=[0.1], method='nearest') assert sliced.shape[0] == 1 # this return empty k with arbitary edges. sliced = dataset.sel(k=[], method='nearest') assert sliced.shape[0] == 0 # slice in a specific k-range sliced = dataset.sel(k=slice(0.02, 0.15), mu=[0.5], method='nearest') assert sliced.shape[1] == 1 assert numpy.alltrue((sliced['k'] >= 0.02)&(sliced['k'] <= 0.15)) @MPITest([1]) def test_take(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) sliced = dataset.take(k=[8]) assert sliced.shape[0] == 1 assert len(sliced.dims) == 2 sliced = dataset.take(k=[]) assert sliced.shape[0] == 0 assert len(sliced.dims) == 2 dataset.take(k=dataset.coords['k'] < 0.3) assert len(sliced.dims) == 2 dataset.take(dataset['modes'] > 0) assert len(sliced.dims) == 2 dataset.take(dataset['k'] < 0.3) assert len(sliced.dims) == 2 @MPITest([1]) def test_squeeze(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # need to specify which dimension to squeeze with pytest.raises(ValueError): squeezed = dataset.squeeze() with pytest.raises(ValueError): squeezed = dataset[[0],[0]].squeeze() sliced = dataset[:,[2]] with pytest.raises(ValueError): squeezed = sliced.squeeze('k') squeezed = sliced.squeeze('mu') assert len(squeezed.dims) == 1 assert squeezed.shape[0] == sliced.shape[0] @MPITest([1]) def test_average(comm): import warnings dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # unweighted with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) avg = dataset.average('mu') for var in dataset.variables: if var in dataset._fields_to_sum: x = numpy.nansum(dataset[var], axis=-1) else: x = numpy.nanmean(dataset[var], axis=-1) testing.assert_allclose(x, avg[var]) # weighted weights = numpy.random.random(dataset.shape) dataset['weights'] = weights avg = dataset.average('mu', weights='weights') for var in dataset: if var in dataset._fields_to_sum: x = numpy.nansum(dataset[var], axis=-1) else: x = numpy.nansum(dataset[var]*dataset['weights'], axis=-1) x /= dataset['weights'].sum(axis=-1) testing.assert_allclose(x, avg[var]) @MPITest([1]) def test_reindex(comm): import warnings dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) with pytest.raises(ValueError): new, spacing = dataset.reindex('k', 0.005, force=True, return_spacing=True) with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) weights = numpy.random.random(dataset.shape) dataset['weights'] = weights new, spacing = dataset.reindex('k', 0.02, weights='weights', force=True, return_spacing=True) diff = numpy.diff(new.coords['k']) assert numpy.alltrue(diff > numpy.diff(dataset.coords['k'])[0]) with pytest.raises(ValueError): new = dataset.reindex('mu', 0.4, force=False) new = dataset.reindex('mu', 0.4, force=True) @MPITest([1]) def test_subclass_copy_sel(comm): # this test asserts the sel returns instance of subclass. # and the copy method can change the class. class A(BinnedStatistic): def mymethod(self): return self.copy(cls=BinnedStatistic) # load from JSON dataset = A.from_json(os.path.join(data_dir, 'dataset_2d.json')) dataset.mymethod() # no exact match fails with pytest.raises(IndexError): sliced = dataset.sel(k=0.1) # this should be squeezed sliced = dataset.sel(k=0.1, method='nearest') assert len(sliced.dims) == 1 assert isinstance(sliced, A) assert isinstance(sliced.mymethod(), BinnedStatistic)
nickhand/nbodykit
nbodykit/tests/test_binned_stat.py
nbodykit/utils.py
from nbodykit.base.catalog import CatalogSource from nbodykit.utils import is_structured_array from nbodykit import CurrentMPIComm from astropy.table import Table import numpy class ArrayCatalog(CatalogSource): """ A CatalogSource initialized from an in-memory :obj:`dict`, structured :class:`numpy.ndarray`, or :class:`astropy.table.Table`. Parameters ---------- data : obj:`dict`, :class:`numpy.ndarray`, :class:`astropy.table.Table` a dictionary, structured ndarray, or astropy Table; items are interpreted as the columns of the catalog; the length of any item is used as the size of the catalog. comm : MPI Communicator, optional the MPI communicator instance; default (``None``) sets to the current communicator **kwargs : additional keywords to store as meta-data in :attr:`attrs` """ @CurrentMPIComm.enable def __init__(self, data, comm=None, **kwargs): # convert astropy Tables to structured numpy arrays if isinstance(data, Table): data = data.as_array() # check for structured data if not isinstance(data, dict): if not is_structured_array(data): raise ValueError(("input data to ArrayCatalog must have a " "structured data type with fields")) self.comm = comm self._source = data # compute the data type if hasattr(data, 'dtype'): keys = sorted(data.dtype.names) else: keys = sorted(data.keys()) dtype = numpy.dtype([(key, (data[key].dtype, data[key].shape[1:])) for key in keys]) self._dtype = dtype # verify data types are the same dtypes = self.comm.gather(dtype, root=0) if self.comm.rank == 0: if any(dt != dtypes[0] for dt in dtypes): raise ValueError("mismatch between dtypes across ranks in Array") # the local size self._size = len(self._source[keys[0]]) for key in keys: if len(self._source[key]) != self._size: raise ValueError("column `%s` and column `%s` has different size" % (keys[0], key)) # update the meta-data self.attrs.update(kwargs) CatalogSource.__init__(self, comm=comm) @property def hardcolumns(self): """ The union of the columns in the file and any transformed columns. """ defaults = CatalogSource.hardcolumns.fget(self) return list(self._dtype.names) + defaults def get_hardcolumn(self, col): """ Return a column from the underlying data array/dict. Columns are returned as dask arrays. """ if col in self._dtype.names: return self.make_column(self._source[col]) else: return CatalogSource.get_hardcolumn(self, col)
from runtests.mpi import MPITest from nbodykit import setup_logging from nbodykit.binned_statistic import BinnedStatistic import pytest import tempfile import numpy.testing as testing import numpy import os data_dir = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'data') setup_logging("debug") @MPITest([1]) def test_to_json(comm): # load from JSON ds1 = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_1d.json')) # to JSON with tempfile.NamedTemporaryFile(delete=False) as ff: ds1.to_json(ff.name) ds2 = BinnedStatistic.from_json(ff.name) # same data? for name in ds1: testing.assert_almost_equal(ds1[name], ds2[name]) # cleanup os.remove(ff.name) @MPITest([1]) def test_1d_load(comm): # load plaintext format with pytest.warns(FutureWarning): ds1 = BinnedStatistic.from_plaintext(['k'], os.path.join(data_dir, 'dataset_1d_deprecated.dat')) # wrong dimensions with pytest.raises(ValueError): ds1 = BinnedStatistic.from_plaintext(['k', 'mu'], os.path.join(data_dir, 'dataset_1d_deprecated.dat')) # load from JSON ds2 = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_1d.json')) # same data? for name in ds1: testing.assert_almost_equal(ds1[name], ds2[name]) @MPITest([1]) def test_2d_load(comm): # load plaintext format with pytest.warns(FutureWarning): ds1 = BinnedStatistic.from_plaintext(['k', 'mu'], os.path.join(data_dir, 'dataset_2d_deprecated.dat')) # load from JSON ds2 = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # same data? for name in ds1: testing.assert_almost_equal(ds1[name], ds2[name]) @MPITest([1]) def test_str(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # list all variable names s = str(dataset) # now just list total number of variables dataset['test1'] = numpy.ones(dataset.shape) dataset['test2'] = numpy.ones(dataset.shape) s = str(dataset) # this is the same as str r = repr(dataset) @MPITest([1]) def test_getitem(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # invalid key with pytest.raises(KeyError): bad = dataset['error'] # slice columns sliced = dataset[['k', 'mu', 'power']] sliced = dataset[('k', 'mu', 'power')] # invalid slice with pytest.raises(KeyError): bad =dataset[['k', 'mu', 'error']] # too many dims in slice with pytest.raises(IndexError): bad = dataset[0,0,0] # cannot access single element of 2D power with pytest.raises(IndexError): bad = dataset[0,0] @MPITest([1]) def test_array_slice(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # get the first mu column sliced = dataset[:,0] assert sliced.shape[0] == dataset.shape[0] assert len(sliced.shape) == 1 assert sliced.dims == ['k'] # get the first mu column but keep dimension sliced = dataset[:,[0]] assert sliced.shape[0] == dataset.shape[0] assert sliced.shape[1] == 1 assert sliced.dims == ['k', 'mu'] @MPITest([1]) def test_list_array_slice(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # get the first and last mu column sliced = dataset[:,[0, -1]] assert len(sliced.shape) == 2 assert sliced.dims == ['k', 'mu'] # make sure we grabbed the right data for var in dataset: testing.assert_array_equal(dataset[var][:,[0,-1]], sliced[var]) @MPITest([1]) def test_variable_set(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) modes = numpy.ones(dataset.shape) # add new variable dataset['TEST'] = modes assert 'TEST' in dataset # override existing variable dataset['modes'] = modes assert numpy.all(dataset['modes'] == 1.0) # needs right shape with pytest.raises(ValueError): dataset['TEST'] = 10. @MPITest([1]) def test_copy(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) copy = dataset.copy() for var in dataset: testing.assert_array_equal(dataset[var], copy[var]) @MPITest([1]) def test_rename_variable(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) test = numpy.zeros(dataset.shape) dataset['test'] = test dataset.rename_variable('test', 'renamed_test') assert 'renamed_test' in dataset assert 'test' not in dataset @MPITest([1]) def test_sel(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # no exact match fails with pytest.raises(IndexError): sliced = dataset.sel(k=0.1) # this should be squeezed sliced = dataset.sel(k=0.1, method='nearest') assert len(sliced.dims) == 1 # this is not squeezed sliced = dataset.sel(k=[0.1], method='nearest') assert sliced.shape[0] == 1 # this return empty k with arbitary edges. sliced = dataset.sel(k=[], method='nearest') assert sliced.shape[0] == 0 # slice in a specific k-range sliced = dataset.sel(k=slice(0.02, 0.15), mu=[0.5], method='nearest') assert sliced.shape[1] == 1 assert numpy.alltrue((sliced['k'] >= 0.02)&(sliced['k'] <= 0.15)) @MPITest([1]) def test_take(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) sliced = dataset.take(k=[8]) assert sliced.shape[0] == 1 assert len(sliced.dims) == 2 sliced = dataset.take(k=[]) assert sliced.shape[0] == 0 assert len(sliced.dims) == 2 dataset.take(k=dataset.coords['k'] < 0.3) assert len(sliced.dims) == 2 dataset.take(dataset['modes'] > 0) assert len(sliced.dims) == 2 dataset.take(dataset['k'] < 0.3) assert len(sliced.dims) == 2 @MPITest([1]) def test_squeeze(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # need to specify which dimension to squeeze with pytest.raises(ValueError): squeezed = dataset.squeeze() with pytest.raises(ValueError): squeezed = dataset[[0],[0]].squeeze() sliced = dataset[:,[2]] with pytest.raises(ValueError): squeezed = sliced.squeeze('k') squeezed = sliced.squeeze('mu') assert len(squeezed.dims) == 1 assert squeezed.shape[0] == sliced.shape[0] @MPITest([1]) def test_average(comm): import warnings dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # unweighted with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) avg = dataset.average('mu') for var in dataset.variables: if var in dataset._fields_to_sum: x = numpy.nansum(dataset[var], axis=-1) else: x = numpy.nanmean(dataset[var], axis=-1) testing.assert_allclose(x, avg[var]) # weighted weights = numpy.random.random(dataset.shape) dataset['weights'] = weights avg = dataset.average('mu', weights='weights') for var in dataset: if var in dataset._fields_to_sum: x = numpy.nansum(dataset[var], axis=-1) else: x = numpy.nansum(dataset[var]*dataset['weights'], axis=-1) x /= dataset['weights'].sum(axis=-1) testing.assert_allclose(x, avg[var]) @MPITest([1]) def test_reindex(comm): import warnings dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) with pytest.raises(ValueError): new, spacing = dataset.reindex('k', 0.005, force=True, return_spacing=True) with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) weights = numpy.random.random(dataset.shape) dataset['weights'] = weights new, spacing = dataset.reindex('k', 0.02, weights='weights', force=True, return_spacing=True) diff = numpy.diff(new.coords['k']) assert numpy.alltrue(diff > numpy.diff(dataset.coords['k'])[0]) with pytest.raises(ValueError): new = dataset.reindex('mu', 0.4, force=False) new = dataset.reindex('mu', 0.4, force=True) @MPITest([1]) def test_subclass_copy_sel(comm): # this test asserts the sel returns instance of subclass. # and the copy method can change the class. class A(BinnedStatistic): def mymethod(self): return self.copy(cls=BinnedStatistic) # load from JSON dataset = A.from_json(os.path.join(data_dir, 'dataset_2d.json')) dataset.mymethod() # no exact match fails with pytest.raises(IndexError): sliced = dataset.sel(k=0.1) # this should be squeezed sliced = dataset.sel(k=0.1, method='nearest') assert len(sliced.dims) == 1 assert isinstance(sliced, A) assert isinstance(sliced.mymethod(), BinnedStatistic)
nickhand/nbodykit
nbodykit/tests/test_binned_stat.py
nbodykit/source/catalog/array.py
from runtests.mpi import MPITest from nbodykit.lab import * from nbodykit import setup_logging from numpy.testing import assert_allclose setup_logging() @MPITest([1,4]) def test_paint(comm): cosmo = cosmology.Planck15 # linear grid Plin = cosmology.LinearPower(cosmo, redshift=0.55, transfer='EisensteinHu') source = LinearMesh(Plin, Nmesh=64, BoxSize=512, seed=42, comm=comm) # compute P(k) from linear grid r = FFTPower(source, mode='1d', Nmesh=64, dk=0.01, kmin=0.005) # run and get the result valid = r.power['modes'] > 0 # variance of each point is 2*P^2/N_modes theory = Plin(r.power['k'][valid]) errs = (2*theory**2/r.power['modes'][valid])**0.5 # compute reduced chi-squared of measurement to theory chisq = ((r.power['power'][valid].real - theory)/errs)**2 N = valid.sum() red_chisq = chisq.sum() / (N-1) # make sure it is less than 1.5 (should be ~1) assert red_chisq < 1.5, "reduced chi sq of linear grid measurement = %.3f" %red_chisq
from runtests.mpi import MPITest from nbodykit import setup_logging from nbodykit.binned_statistic import BinnedStatistic import pytest import tempfile import numpy.testing as testing import numpy import os data_dir = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'data') setup_logging("debug") @MPITest([1]) def test_to_json(comm): # load from JSON ds1 = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_1d.json')) # to JSON with tempfile.NamedTemporaryFile(delete=False) as ff: ds1.to_json(ff.name) ds2 = BinnedStatistic.from_json(ff.name) # same data? for name in ds1: testing.assert_almost_equal(ds1[name], ds2[name]) # cleanup os.remove(ff.name) @MPITest([1]) def test_1d_load(comm): # load plaintext format with pytest.warns(FutureWarning): ds1 = BinnedStatistic.from_plaintext(['k'], os.path.join(data_dir, 'dataset_1d_deprecated.dat')) # wrong dimensions with pytest.raises(ValueError): ds1 = BinnedStatistic.from_plaintext(['k', 'mu'], os.path.join(data_dir, 'dataset_1d_deprecated.dat')) # load from JSON ds2 = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_1d.json')) # same data? for name in ds1: testing.assert_almost_equal(ds1[name], ds2[name]) @MPITest([1]) def test_2d_load(comm): # load plaintext format with pytest.warns(FutureWarning): ds1 = BinnedStatistic.from_plaintext(['k', 'mu'], os.path.join(data_dir, 'dataset_2d_deprecated.dat')) # load from JSON ds2 = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # same data? for name in ds1: testing.assert_almost_equal(ds1[name], ds2[name]) @MPITest([1]) def test_str(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # list all variable names s = str(dataset) # now just list total number of variables dataset['test1'] = numpy.ones(dataset.shape) dataset['test2'] = numpy.ones(dataset.shape) s = str(dataset) # this is the same as str r = repr(dataset) @MPITest([1]) def test_getitem(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # invalid key with pytest.raises(KeyError): bad = dataset['error'] # slice columns sliced = dataset[['k', 'mu', 'power']] sliced = dataset[('k', 'mu', 'power')] # invalid slice with pytest.raises(KeyError): bad =dataset[['k', 'mu', 'error']] # too many dims in slice with pytest.raises(IndexError): bad = dataset[0,0,0] # cannot access single element of 2D power with pytest.raises(IndexError): bad = dataset[0,0] @MPITest([1]) def test_array_slice(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # get the first mu column sliced = dataset[:,0] assert sliced.shape[0] == dataset.shape[0] assert len(sliced.shape) == 1 assert sliced.dims == ['k'] # get the first mu column but keep dimension sliced = dataset[:,[0]] assert sliced.shape[0] == dataset.shape[0] assert sliced.shape[1] == 1 assert sliced.dims == ['k', 'mu'] @MPITest([1]) def test_list_array_slice(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # get the first and last mu column sliced = dataset[:,[0, -1]] assert len(sliced.shape) == 2 assert sliced.dims == ['k', 'mu'] # make sure we grabbed the right data for var in dataset: testing.assert_array_equal(dataset[var][:,[0,-1]], sliced[var]) @MPITest([1]) def test_variable_set(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) modes = numpy.ones(dataset.shape) # add new variable dataset['TEST'] = modes assert 'TEST' in dataset # override existing variable dataset['modes'] = modes assert numpy.all(dataset['modes'] == 1.0) # needs right shape with pytest.raises(ValueError): dataset['TEST'] = 10. @MPITest([1]) def test_copy(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) copy = dataset.copy() for var in dataset: testing.assert_array_equal(dataset[var], copy[var]) @MPITest([1]) def test_rename_variable(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) test = numpy.zeros(dataset.shape) dataset['test'] = test dataset.rename_variable('test', 'renamed_test') assert 'renamed_test' in dataset assert 'test' not in dataset @MPITest([1]) def test_sel(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # no exact match fails with pytest.raises(IndexError): sliced = dataset.sel(k=0.1) # this should be squeezed sliced = dataset.sel(k=0.1, method='nearest') assert len(sliced.dims) == 1 # this is not squeezed sliced = dataset.sel(k=[0.1], method='nearest') assert sliced.shape[0] == 1 # this return empty k with arbitary edges. sliced = dataset.sel(k=[], method='nearest') assert sliced.shape[0] == 0 # slice in a specific k-range sliced = dataset.sel(k=slice(0.02, 0.15), mu=[0.5], method='nearest') assert sliced.shape[1] == 1 assert numpy.alltrue((sliced['k'] >= 0.02)&(sliced['k'] <= 0.15)) @MPITest([1]) def test_take(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) sliced = dataset.take(k=[8]) assert sliced.shape[0] == 1 assert len(sliced.dims) == 2 sliced = dataset.take(k=[]) assert sliced.shape[0] == 0 assert len(sliced.dims) == 2 dataset.take(k=dataset.coords['k'] < 0.3) assert len(sliced.dims) == 2 dataset.take(dataset['modes'] > 0) assert len(sliced.dims) == 2 dataset.take(dataset['k'] < 0.3) assert len(sliced.dims) == 2 @MPITest([1]) def test_squeeze(comm): dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # need to specify which dimension to squeeze with pytest.raises(ValueError): squeezed = dataset.squeeze() with pytest.raises(ValueError): squeezed = dataset[[0],[0]].squeeze() sliced = dataset[:,[2]] with pytest.raises(ValueError): squeezed = sliced.squeeze('k') squeezed = sliced.squeeze('mu') assert len(squeezed.dims) == 1 assert squeezed.shape[0] == sliced.shape[0] @MPITest([1]) def test_average(comm): import warnings dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) # unweighted with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) avg = dataset.average('mu') for var in dataset.variables: if var in dataset._fields_to_sum: x = numpy.nansum(dataset[var], axis=-1) else: x = numpy.nanmean(dataset[var], axis=-1) testing.assert_allclose(x, avg[var]) # weighted weights = numpy.random.random(dataset.shape) dataset['weights'] = weights avg = dataset.average('mu', weights='weights') for var in dataset: if var in dataset._fields_to_sum: x = numpy.nansum(dataset[var], axis=-1) else: x = numpy.nansum(dataset[var]*dataset['weights'], axis=-1) x /= dataset['weights'].sum(axis=-1) testing.assert_allclose(x, avg[var]) @MPITest([1]) def test_reindex(comm): import warnings dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json')) with pytest.raises(ValueError): new, spacing = dataset.reindex('k', 0.005, force=True, return_spacing=True) with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) weights = numpy.random.random(dataset.shape) dataset['weights'] = weights new, spacing = dataset.reindex('k', 0.02, weights='weights', force=True, return_spacing=True) diff = numpy.diff(new.coords['k']) assert numpy.alltrue(diff > numpy.diff(dataset.coords['k'])[0]) with pytest.raises(ValueError): new = dataset.reindex('mu', 0.4, force=False) new = dataset.reindex('mu', 0.4, force=True) @MPITest([1]) def test_subclass_copy_sel(comm): # this test asserts the sel returns instance of subclass. # and the copy method can change the class. class A(BinnedStatistic): def mymethod(self): return self.copy(cls=BinnedStatistic) # load from JSON dataset = A.from_json(os.path.join(data_dir, 'dataset_2d.json')) dataset.mymethod() # no exact match fails with pytest.raises(IndexError): sliced = dataset.sel(k=0.1) # this should be squeezed sliced = dataset.sel(k=0.1, method='nearest') assert len(sliced.dims) == 1 assert isinstance(sliced, A) assert isinstance(sliced.mymethod(), BinnedStatistic)
nickhand/nbodykit
nbodykit/tests/test_binned_stat.py
nbodykit/source/mesh/tests/test_linear.py
""" Scheduler for periodic tasks """ import traceback from logging import getLogger import schedule import time from concurrent.futures import ThreadPoolExecutor class Task: """ Base class of tasks Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger connection_provider : minette.ConnectionProvider Connection provider to use database in each tasks """ def __init__(self, config=None, timezone=None, logger=None, connection_provider=None, **kwargs): """ Parameters ---------- config : minette.Config, default None Configuration timezone : pytz.timezone, default None Timezone logger : logging.Logger, default None Logger connection_provider : minette.ConnectionProvider Connection provider to use database in each tasks """ self.config = config self.timezone = timezone self.logger = logger or getLogger(__name__) self.connection_provider = connection_provider def do(self, **kwargs): """ Implement your periodic task """ self.logger.error("Task is not implemented") class Scheduler: """ Task scheduler for periodic tasks Examples -------- To start doing scheduled tasks, just create `Scheduler` instance and register task(s), then call `start()` >>> my_scheduler = MyScheduler() >>> my_scheduler.every_minutes(MyTask) >>> my_scheduler.start() To register tasks, this class provides shortcut methods. Each tasks run at worker threads. >>> my_scheduler.every_minutes(MyTask) >>> my_scheduler.every_seconds(MyTask, seconds=5) >>> my_scheduler.every_seconds(MyTask, seconds=5, arg1="val1", arg2="val2") You can also use internal `schedule` to register tasks then the tasks run at main thread. >>> my_scheduler.schedule.every().minute.do(self.create_task(MyTask)) >>> my_scheduler.schedule.every().hour.do(self.create_task(YourTask)) Notes ----- How to execute jobs in parallel? https://schedule.readthedocs.io/en/stable/faq.html#how-to-execute-jobs-in-parallel Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger threads : int Number of worker threads to process tasks connection_provider : minette.ConnectionProvider Connection provider to use database in each tasks schedule : schedule schedule module executor : concurrent.futures.ThreadPoolExecutor Executor to run tasks at worker threads """ def __init__(self, config=None, timezone=None, logger=None, threads=None, connection_provider=None, **kwargs): """ Parameters ---------- config : minette.Config, default None Configuration timezone : pytz.timezone, default None Timezone logger : logging.Logger, default None Logger threads : int, default None Number of worker threads to process tasks connection_provider : ConnectionProvider, default None Connection provider to use database in each tasks """ self.config = config self.timezone = timezone self.logger = logger or getLogger(__name__) self.threads = threads self.connection_provider = connection_provider self.schedule = schedule self.executor = ThreadPoolExecutor( max_workers=self.threads, thread_name_prefix="SchedulerThread") self._is_running = False @property def is_running(self): return self._is_running def create_task(self, task_class, **kwargs): """ Create and return callable function of task Parameters ---------- task_class : type Class of task Returns ------- task_method : callable Callable interface of task """ if isinstance(task_class, type): if issubclass(task_class, Task): return task_class( config=self.config, timezone=self.timezone, logger=self.logger, connection_provider=self.connection_provider, **kwargs).do else: raise TypeError( "task_class should be a subclass of minette.Task " + "or callable, not {}".format(task_class.__name__)) elif callable(task_class): return task_class else: raise TypeError( "task_class should be a subclass of minette.Task " + "or callable, not the instance of {}".format( task_class.__class__.__name__)) def every_seconds(self, task, seconds=1, *args, **kwargs): self.schedule.every(seconds).seconds.do( self.executor.submit, self.create_task(task), *args, **kwargs) def every_minutes(self, task, minutes=1, *args, **kwargs): self.schedule.every(minutes).minutes.do( self.executor.submit, self.create_task(task), *args, **kwargs) def every_hours(self, task, hours=1, *args, **kwargs): self.schedule.every(hours).hours.do( self.executor.submit, self.create_task(task), *args, **kwargs) def every_days(self, task, days=1, *args, **kwargs): self.schedule.every(days).days.do( self.executor.submit, self.create_task(task), *args, **kwargs) def start(self): """ Start scheduler """ self.logger.info("Task scheduler started") self._is_running = True while self._is_running: self.schedule.run_pending() time.sleep(1) self.logger.info("Task scheduler stopped") def stop(self): """ Stop scheduler """ self._is_running = False
import sys import os sys.path.append(os.pardir) import pytest from pytz import timezone from logging import Logger, FileHandler, getLogger from datetime import datetime from types import GeneratorType from minette import ( Minette, DialogService, SQLiteConnectionProvider, SQLiteContextStore, SQLiteUserStore, SQLiteMessageLogStore, Tagger, Config, DialogRouter, StoreSet, Message, User, Group, DependencyContainer, Payload ) from minette.utils import date_to_unixtime from minette.tagger.janometagger import JanomeTagger now = datetime.now() user_id = "user_id" + str(date_to_unixtime(now)) print("user_id: {}".format(user_id)) class CustomTagger(Tagger): pass class CustomConnectionProvider(SQLiteConnectionProvider): pass class CustomContextStore(SQLiteContextStore): pass class CustomUserStore(SQLiteUserStore): pass class CustomMessageLogStore(SQLiteMessageLogStore): pass class CustomDataStores(StoreSet): connection_provider = CustomConnectionProvider context_store = CustomContextStore user_store = CustomUserStore messagelog_store = CustomMessageLogStore class MyDialog(DialogService): def compose_response(self, request, context, connection): return "res:" + request.text class ErrorDialog(DialogService): def compose_response(self, request, context, connection): 1 / 0 return "res:" + request.text class MyDialogRouter(DialogRouter): def __init__(self, custom_router_arg=None, **kwargs): super().__init__(**kwargs) self.custom_attr = custom_router_arg class TaggerDialog(DialogService): def compose_response(self, request, context, connection): return request.to_reply( text=request.text, payloads=[Payload(content_type="data", content=request.words)]) class TaggerManuallyParseDialog(DialogService): def compose_response(self, request, context, connection): assert request.words == [] request.words = self.dependencies.tagger.parse(request.text, max_length=10) return request.to_reply( text=request.text, payloads=[Payload(content_type="data", content=request.words)]) class TaggerManuallyParseGeneratorDialog(DialogService): def compose_response(self, request, context, connection): assert request.words == [] request.words = self.dependencies.tagger.parse_as_generator(request.text, max_length=10) return request.to_reply( text=request.text, payloads=[Payload(content_type="data", content=request.words)]) def test_init(): # without config bot = Minette() assert bot.config.get("timezone") == "UTC" assert bot.timezone == timezone("UTC") assert isinstance(bot.logger, Logger) assert bot.logger.name == "minette" assert isinstance(bot.connection_provider, SQLiteConnectionProvider) assert isinstance(bot.context_store, SQLiteContextStore) assert isinstance(bot.user_store, SQLiteUserStore) assert isinstance(bot.messagelog_store, SQLiteMessageLogStore) assert bot.default_dialog_service is None assert isinstance(bot.tagger, Tagger) def test_init_config(): bot = Minette(config_file="./config/test_config.ini") assert bot.timezone == timezone("Asia/Tokyo") for handler in bot.logger.handlers: if isinstance(handler, FileHandler): assert handler.baseFilename == \ os.path.join(os.path.dirname(os.path.abspath(__file__)), bot.config.get("log_file")) assert bot.connection_provider.connection_str != "" assert bot.connection_provider.connection_str == \ bot.config.get("connection_str") assert bot.context_store.timeout == bot.config.get("context_timeout") assert bot.context_store.table_name == bot.config.get("context_table") assert bot.user_store.table_name == bot.config.get("user_table") assert bot.messagelog_store.table_name == \ bot.config.get("messagelog_table") def test_init_args(): # initialize arguments config = Config("") config.confg_parser.add_section("test_section") config.confg_parser.set("test_section", "test_key", "test_value") tz = timezone("Asia/Tokyo") logger = getLogger("test_core_logger") print(logger.name) connection_provider = CustomConnectionProvider context_store = CustomContextStore user_store = CustomUserStore messagelog_store = CustomMessageLogStore data_stores = CustomDataStores default_dialog_service = MyDialog dialog_router = MyDialogRouter tagger = CustomTagger custom_router_arg = "router_value" # create bot bot = Minette( config=config, timezone=tz, logger=logger, connection_provider=connection_provider, context_store=context_store, user_store=user_store, messagelog_store=messagelog_store, default_dialog_service=default_dialog_service, dialog_router=dialog_router, custom_router_arg=custom_router_arg, tagger=tagger, prepare_table=True ) assert bot.config.get("test_key", section="test_section") == "test_value" assert bot.timezone == timezone("Asia/Tokyo") assert bot.logger.name == "test_core_logger" assert isinstance(bot.connection_provider, CustomConnectionProvider) assert isinstance(bot.context_store, CustomContextStore) assert isinstance(bot.user_store, CustomUserStore) assert isinstance(bot.messagelog_store, CustomMessageLogStore) assert bot.default_dialog_service is MyDialog assert isinstance(bot.dialog_router, MyDialogRouter) assert bot.dialog_router.custom_attr == "router_value" assert isinstance(bot.tagger, CustomTagger) # create bot with data_stores bot = Minette( config=config, timezone=tz, logger=logger, data_stores=data_stores, default_dialog_service=default_dialog_service, dialog_router=dialog_router, custom_router_arg=custom_router_arg, tagger=tagger, prepare_table=True ) assert bot.config.get("test_key", section="test_section") == "test_value" assert bot.timezone == timezone("Asia/Tokyo") assert bot.logger.name == "test_core_logger" assert isinstance(bot.connection_provider, CustomConnectionProvider) assert isinstance(bot.context_store, CustomContextStore) assert isinstance(bot.user_store, CustomUserStore) assert isinstance(bot.messagelog_store, CustomMessageLogStore) assert bot.default_dialog_service is MyDialog assert isinstance(bot.dialog_router, MyDialogRouter) assert bot.dialog_router.custom_attr == "router_value" assert isinstance(bot.tagger, CustomTagger) def test_get_user(): bot = Minette(prepare_table=True) with bot.connection_provider.get_connection() as connection: # register user for test u = bot.user_store.get( channel="get_user_test", channel_user_id=user_id, connection=connection) u.name = "user channel" bot.user_store.save(u, connection) u_detail = bot.user_store.get( channel="get_user_test_detail", channel_user_id=user_id, connection=connection) u_detail.name = "user detail" bot.user_store.save(u_detail, connection) # without detail request = Message( text="hello", channel="get_user_test", channel_user_id=user_id) user = bot._get_user(request, connection) assert user.channel == "get_user_test" assert user.channel_user_id == user_id assert user.name == "user channel" # with detail bot.config.confg_parser.set("minette", "user_scope", "channel_detail") request = Message( text="hello", channel="get_user_test", channel_detail="detail", channel_user_id=user_id) user = bot._get_user(request, connection) assert user.channel == "get_user_test_detail" assert user.channel_user_id == user_id assert user.name == "user detail" def test_save_user(): bot = Minette(prepare_table=True) with bot.connection_provider.get_connection() as connection: # register user for test u = bot.user_store.get( channel="save_user_test", channel_user_id=user_id, connection=connection) u.name = "Tomori Nao" # save bot._save_user(u, connection) # check request = Message( text="hello", channel="save_user_test", channel_user_id=user_id) user = bot._get_user(request, connection) assert user.channel == "save_user_test" assert user.channel_user_id == user_id assert user.name == "Tomori Nao" def test_get_context(): bot = Minette(prepare_table=True) with bot.connection_provider.get_connection() as connection: # register context for test ctx = bot.context_store.get( channel="get_context_test", channel_user_id=user_id, connection=connection) ctx.data["unixtime"] = date_to_unixtime(now) bot.context_store.save(ctx, connection) ctx_group = bot.context_store.get( channel="get_context_test", channel_user_id="group_" + user_id, connection=connection) ctx_group.data["unixtime"] = date_to_unixtime(now) bot.context_store.save(ctx_group, connection) ctx_detail = bot.context_store.get( channel="get_context_test_detail", channel_user_id=user_id, connection=connection) ctx_detail.data["unixtime"] = date_to_unixtime(now) bot.context_store.save(ctx_detail, connection) # without detail request = Message( text="hello", channel="get_context_test", channel_user_id=user_id) context = bot._get_context(request, connection) assert context.channel == "get_context_test" assert context.channel_user_id == user_id assert context.data["unixtime"] == date_to_unixtime(now) # group without group request = Message( text="hello", channel="get_context_test", channel_user_id=user_id) request.group = Group(id="group_" + user_id) context = bot._get_context(request, connection) assert context.channel == "get_context_test" assert context.channel_user_id == "group_" + user_id assert context.data["unixtime"] == date_to_unixtime(now) # with detail bot.config.confg_parser.set( "minette", "context_scope", "channel_detail") request = Message( text="hello", channel="get_context_test", channel_detail="detail", channel_user_id=user_id) context = bot._get_context(request, connection) assert context.channel == "get_context_test_detail" assert context.channel_user_id == user_id assert context.data["unixtime"] == date_to_unixtime(now) def test_save_context(): bot = Minette(prepare_table=True) with bot.connection_provider.get_connection() as connection: # register context for test ctx = bot.context_store.get( channel="save_context_test", channel_user_id=user_id, connection=connection) ctx.data["unixtime"] = date_to_unixtime(now) # save ctx.topic.keep_on = True bot._save_context(ctx, connection) # check request = Message( text="hello", channel="save_context_test", channel_user_id=user_id) context = bot._get_context(request, connection) assert context.channel == "save_context_test" assert context.channel_user_id == user_id assert context.data["unixtime"] == date_to_unixtime(now) def test_chat(): bot = Minette(default_dialog_service=MyDialog) res = bot.chat("hello") assert res.messages[0].text == "res:hello" def test_chat_error(): bot = Minette(default_dialog_service=MyDialog) bot.connection_provider = None res = bot.chat("hello") assert res.messages == [] def test_chat_messagelog_error(): bot = Minette(default_dialog_service=MyDialog) bot.messagelog_store = None res = bot.chat("hello") assert res.messages[0].text == "res:hello" def test_chat_dialog_error(): bot = Minette(default_dialog_service=ErrorDialog) res = bot.chat("hello") assert res.messages[0].text == "?" def test_chat_timezone(): bot = Minette(default_dialog_service=MyDialog, timezone=timezone("Asia/Tokyo")) res = bot.chat("hello") # bot.timezone itself is +9:19 assert res.messages[0].timestamp.tzinfo == datetime.now(tz=bot.timezone).tzinfo def test_chat_with_tagger(): bot = Minette( default_dialog_service=TaggerDialog, tagger=JanomeTagger) res = bot.chat("今日はいい天気です。") assert res.messages[0].text == "今日はいい天気です。" words = res.messages[0].payloads[0].content assert words[0].surface == "今日" assert words[1].surface == "は" assert words[2].surface == "いい" assert words[3].surface == "天気" assert words[4].surface == "です" def test_chat_with_tagger_no_parse(): bot = Minette( default_dialog_service=TaggerDialog, tagger=JanomeTagger, tagger_max_length=0) assert bot.tagger.max_length == 0 res = bot.chat("今日はいい天気です。") assert res.messages[0].text == "今日はいい天気です。" words = res.messages[0].payloads[0].content assert words == [] def test_chat_parse_morph_manually(): bot = Minette( default_dialog_service=TaggerManuallyParseDialog, tagger=JanomeTagger, tagger_max_length=0) bot.dialog_uses(tagger=bot.tagger) res = bot.chat("今日はいい天気です。") assert res.messages[0].text == "今日はいい天気です。" words = res.messages[0].payloads[0].content assert words[0].surface == "今日" assert words[1].surface == "は" assert words[2].surface == "いい" assert words[3].surface == "天気" assert words[4].surface == "です" def test_chat_parse_morph_manually_generator(): bot = Minette( default_dialog_service=TaggerManuallyParseGeneratorDialog, tagger=JanomeTagger, tagger_max_length=0) bot.dialog_uses(tagger=bot.tagger) res = bot.chat("今日はいい天気です。") assert res.messages[0].text == "今日はいい天気です。" assert isinstance(res.messages[0].payloads[0].content, GeneratorType) words = [w for w in res.messages[0].payloads[0].content] assert words[0].surface == "今日" assert words[1].surface == "は" assert words[2].surface == "いい" assert words[3].surface == "天気" assert words[4].surface == "です" def test_dialog_uses(): class HighCostToCreate: pass class OnlyForFooDS: pass class FooFialog(DialogService): pass # run once when create bot hctc = HighCostToCreate() offds = OnlyForFooDS() # create bot bot = Minette() # set dependencies to dialogs bot.dialog_uses( { FooFialog: {"api": offds} }, highcost=hctc ) assert bot.dialog_router.dependencies.highcost == hctc assert hasattr(bot.dialog_router.dependencies, "api") is False assert bot.dialog_router.dependency_rules[FooFialog]["api"] == offds # create bot and not set dialog dependencies bot_no_dd = Minette() assert bot_no_dd.dialog_router.dependencies is None bot_no_dd.dialog_uses() assert isinstance(bot_no_dd.dialog_router.dependencies, DependencyContainer)
uezo/minette-python
tests/test_core.py
minette/scheduler/base.py
"""Switches on Zigbee Home Automation networks.""" from __future__ import annotations import functools from typing import Any from zigpy.zcl.clusters.general import OnOff from zigpy.zcl.foundation import Status from homeassistant.components.switch import DOMAIN, SwitchEntity from homeassistant.const import STATE_ON, STATE_UNAVAILABLE from homeassistant.core import State, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .core import discovery from .core.const import ( CHANNEL_ON_OFF, DATA_ZHA, DATA_ZHA_DISPATCHERS, SIGNAL_ADD_ENTITIES, SIGNAL_ATTR_UPDATED, ) from .core.registries import ZHA_ENTITIES from .entity import ZhaEntity, ZhaGroupEntity STRICT_MATCH = functools.partial(ZHA_ENTITIES.strict_match, DOMAIN) GROUP_MATCH = functools.partial(ZHA_ENTITIES.group_match, DOMAIN) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Zigbee Home Automation switch from config entry.""" entities_to_create = hass.data[DATA_ZHA][DOMAIN] unsub = async_dispatcher_connect( hass, SIGNAL_ADD_ENTITIES, functools.partial( discovery.async_add_entities, async_add_entities, entities_to_create ), ) hass.data[DATA_ZHA][DATA_ZHA_DISPATCHERS].append(unsub) class BaseSwitch(SwitchEntity): """Common base class for zha switches.""" def __init__(self, *args, **kwargs): """Initialize the ZHA switch.""" self._on_off_channel = None self._state = None super().__init__(*args, **kwargs) @property def is_on(self) -> bool: """Return if the switch is on based on the statemachine.""" if self._state is None: return False return self._state async def async_turn_on(self, **kwargs) -> None: """Turn the entity on.""" result = await self._on_off_channel.on() if not isinstance(result, list) or result[1] is not Status.SUCCESS: return self._state = True self.async_write_ha_state() async def async_turn_off(self, **kwargs) -> None: """Turn the entity off.""" result = await self._on_off_channel.off() if not isinstance(result, list) or result[1] is not Status.SUCCESS: return self._state = False self.async_write_ha_state() @STRICT_MATCH(channel_names=CHANNEL_ON_OFF) class Switch(BaseSwitch, ZhaEntity): """ZHA switch.""" def __init__(self, unique_id, zha_device, channels, **kwargs): """Initialize the ZHA switch.""" super().__init__(unique_id, zha_device, channels, **kwargs) self._on_off_channel = self.cluster_channels.get(CHANNEL_ON_OFF) @callback def async_set_state(self, attr_id: int, attr_name: str, value: Any): """Handle state update from channel.""" self._state = bool(value) self.async_write_ha_state() async def async_added_to_hass(self) -> None: """Run when about to be added to hass.""" await super().async_added_to_hass() self.async_accept_signal( self._on_off_channel, SIGNAL_ATTR_UPDATED, self.async_set_state ) @callback def async_restore_last_state(self, last_state) -> None: """Restore previous state.""" self._state = last_state.state == STATE_ON async def async_update(self) -> None: """Attempt to retrieve on off state from the switch.""" await super().async_update() if self._on_off_channel: state = await self._on_off_channel.get_attribute_value("on_off") if state is not None: self._state = state @GROUP_MATCH() class SwitchGroup(BaseSwitch, ZhaGroupEntity): """Representation of a switch group.""" def __init__( self, entity_ids: list[str], unique_id: str, group_id: int, zha_device, **kwargs ) -> None: """Initialize a switch group.""" super().__init__(entity_ids, unique_id, group_id, zha_device, **kwargs) self._available: bool = False group = self.zha_device.gateway.get_group(self._group_id) self._on_off_channel = group.endpoint[OnOff.cluster_id] async def async_update(self) -> None: """Query all members and determine the light group state.""" all_states = [self.hass.states.get(x) for x in self._entity_ids] states: list[State] = list(filter(None, all_states)) on_states = [state for state in states if state.state == STATE_ON] self._state = len(on_states) > 0 self._available = any(state.state != STATE_UNAVAILABLE for state in states)
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/zha/switch.py
"""Helpers for listening to events.""" from __future__ import annotations import asyncio import copy from dataclasses import dataclass from datetime import datetime, timedelta import functools as ft import logging import time from typing import Any, Awaitable, Callable, Iterable, List import attr from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_NOW, EVENT_CORE_CONFIG_UPDATE, EVENT_STATE_CHANGED, EVENT_TIME_CHANGED, MATCH_ALL, SUN_EVENT_SUNRISE, SUN_EVENT_SUNSET, ) from homeassistant.core import ( CALLBACK_TYPE, Event, HassJob, HomeAssistant, State, callback, split_entity_id, ) from homeassistant.exceptions import TemplateError from homeassistant.helpers.entity_registry import EVENT_ENTITY_REGISTRY_UPDATED from homeassistant.helpers.ratelimit import KeyedRateLimit from homeassistant.helpers.sun import get_astral_event_next from homeassistant.helpers.template import RenderInfo, Template, result_as_boolean from homeassistant.helpers.typing import TemplateVarsType from homeassistant.loader import bind_hass from homeassistant.util import dt as dt_util from homeassistant.util.async_ import run_callback_threadsafe TRACK_STATE_CHANGE_CALLBACKS = "track_state_change_callbacks" TRACK_STATE_CHANGE_LISTENER = "track_state_change_listener" TRACK_STATE_ADDED_DOMAIN_CALLBACKS = "track_state_added_domain_callbacks" TRACK_STATE_ADDED_DOMAIN_LISTENER = "track_state_added_domain_listener" TRACK_STATE_REMOVED_DOMAIN_CALLBACKS = "track_state_removed_domain_callbacks" TRACK_STATE_REMOVED_DOMAIN_LISTENER = "track_state_removed_domain_listener" TRACK_ENTITY_REGISTRY_UPDATED_CALLBACKS = "track_entity_registry_updated_callbacks" TRACK_ENTITY_REGISTRY_UPDATED_LISTENER = "track_entity_registry_updated_listener" _ALL_LISTENER = "all" _DOMAINS_LISTENER = "domains" _ENTITIES_LISTENER = "entities" _LOGGER = logging.getLogger(__name__) @dataclass class TrackStates: """Class for keeping track of states being tracked. all_states: All states on the system are being tracked entities: Entities to track domains: Domains to track """ all_states: bool entities: set domains: set @dataclass class TrackTemplate: """Class for keeping track of a template with variables. The template is template to calculate. The variables are variables to pass to the template. The rate_limit is a rate limit on how often the template is re-rendered. """ template: Template variables: TemplateVarsType rate_limit: timedelta | None = None @dataclass class TrackTemplateResult: """Class for result of template tracking. template The template that has changed. last_result The output from the template on the last successful run, or None if no previous successful run. result Result from the template run. This will be a string or an TemplateError if the template resulted in an error. """ template: Template last_result: Any result: Any def threaded_listener_factory( async_factory: Callable[..., Any] ) -> Callable[..., CALLBACK_TYPE]: """Convert an async event helper to a threaded one.""" @ft.wraps(async_factory) def factory(*args: Any, **kwargs: Any) -> CALLBACK_TYPE: """Call async event helper safely.""" hass = args[0] if not isinstance(hass, HomeAssistant): raise TypeError("First parameter needs to be a hass instance") async_remove = run_callback_threadsafe( hass.loop, ft.partial(async_factory, *args, **kwargs) ).result() def remove() -> None: """Threadsafe removal.""" run_callback_threadsafe(hass.loop, async_remove).result() return remove return factory @callback @bind_hass def async_track_state_change( hass: HomeAssistant, entity_ids: str | Iterable[str], action: Callable[[str, State, State], None], from_state: None | str | Iterable[str] = None, to_state: None | str | Iterable[str] = None, ) -> CALLBACK_TYPE: """Track specific state changes. entity_ids, from_state and to_state can be string or list. Use list to match multiple. Returns a function that can be called to remove the listener. If entity_ids are not MATCH_ALL along with from_state and to_state being None, async_track_state_change_event should be used instead as it is slightly faster. Must be run within the event loop. """ if from_state is not None: match_from_state = process_state_match(from_state) if to_state is not None: match_to_state = process_state_match(to_state) # Ensure it is a lowercase list with entity ids we want to match on if entity_ids == MATCH_ALL: pass elif isinstance(entity_ids, str): entity_ids = (entity_ids.lower(),) else: entity_ids = tuple(entity_id.lower() for entity_id in entity_ids) job = HassJob(action) @callback def state_change_filter(event: Event) -> bool: """Handle specific state changes.""" if from_state is not None: old_state = event.data.get("old_state") if old_state is not None: old_state = old_state.state if not match_from_state(old_state): return False if to_state is not None: new_state = event.data.get("new_state") if new_state is not None: new_state = new_state.state if not match_to_state(new_state): return False return True @callback def state_change_dispatcher(event: Event) -> None: """Handle specific state changes.""" hass.async_run_hass_job( job, event.data.get("entity_id"), event.data.get("old_state"), event.data.get("new_state"), ) @callback def state_change_listener(event: Event) -> None: """Handle specific state changes.""" if not state_change_filter(event): return state_change_dispatcher(event) if entity_ids != MATCH_ALL: # If we have a list of entity ids we use # async_track_state_change_event to route # by entity_id to avoid iterating though state change # events and creating a jobs where the most # common outcome is to return right away because # the entity_id does not match since usually # only one or two listeners want that specific # entity_id. return async_track_state_change_event(hass, entity_ids, state_change_listener) return hass.bus.async_listen( EVENT_STATE_CHANGED, state_change_dispatcher, event_filter=state_change_filter ) track_state_change = threaded_listener_factory(async_track_state_change) @bind_hass def async_track_state_change_event( hass: HomeAssistant, entity_ids: str | Iterable[str], action: Callable[[Event], Any], ) -> Callable[[], None]: """Track specific state change events indexed by entity_id. Unlike async_track_state_change, async_track_state_change_event passes the full event to the callback. In order to avoid having to iterate a long list of EVENT_STATE_CHANGED and fire and create a job for each one, we keep a dict of entity ids that care about the state change events so we can do a fast dict lookup to route events. """ entity_ids = _async_string_to_lower_list(entity_ids) if not entity_ids: return _remove_empty_listener entity_callbacks = hass.data.setdefault(TRACK_STATE_CHANGE_CALLBACKS, {}) if TRACK_STATE_CHANGE_LISTENER not in hass.data: @callback def _async_state_change_filter(event: Event) -> bool: """Filter state changes by entity_id.""" return event.data.get("entity_id") in entity_callbacks @callback def _async_state_change_dispatcher(event: Event) -> None: """Dispatch state changes by entity_id.""" entity_id = event.data.get("entity_id") if entity_id not in entity_callbacks: return for job in entity_callbacks[entity_id][:]: try: hass.async_run_hass_job(job, event) except Exception: # pylint: disable=broad-except _LOGGER.exception( "Error while processing state change for %s", entity_id ) hass.data[TRACK_STATE_CHANGE_LISTENER] = hass.bus.async_listen( EVENT_STATE_CHANGED, _async_state_change_dispatcher, event_filter=_async_state_change_filter, ) job = HassJob(action) for entity_id in entity_ids: entity_callbacks.setdefault(entity_id, []).append(job) @callback def remove_listener() -> None: """Remove state change listener.""" _async_remove_indexed_listeners( hass, TRACK_STATE_CHANGE_CALLBACKS, TRACK_STATE_CHANGE_LISTENER, entity_ids, job, ) return remove_listener @callback def _remove_empty_listener() -> None: """Remove a listener that does nothing.""" @callback def _async_remove_indexed_listeners( hass: HomeAssistant, data_key: str, listener_key: str, storage_keys: Iterable[str], job: HassJob, ) -> None: """Remove a listener.""" callbacks = hass.data[data_key] for storage_key in storage_keys: callbacks[storage_key].remove(job) if len(callbacks[storage_key]) == 0: del callbacks[storage_key] if not callbacks: hass.data[listener_key]() del hass.data[listener_key] @bind_hass def async_track_entity_registry_updated_event( hass: HomeAssistant, entity_ids: str | Iterable[str], action: Callable[[Event], Any], ) -> Callable[[], None]: """Track specific entity registry updated events indexed by entity_id. Similar to async_track_state_change_event. """ entity_ids = _async_string_to_lower_list(entity_ids) if not entity_ids: return _remove_empty_listener entity_callbacks = hass.data.setdefault(TRACK_ENTITY_REGISTRY_UPDATED_CALLBACKS, {}) if TRACK_ENTITY_REGISTRY_UPDATED_LISTENER not in hass.data: @callback def _async_entity_registry_updated_filter(event: Event) -> bool: """Filter entity registry updates by entity_id.""" entity_id = event.data.get("old_entity_id", event.data["entity_id"]) return entity_id in entity_callbacks @callback def _async_entity_registry_updated_dispatcher(event: Event) -> None: """Dispatch entity registry updates by entity_id.""" entity_id = event.data.get("old_entity_id", event.data["entity_id"]) if entity_id not in entity_callbacks: return for job in entity_callbacks[entity_id][:]: try: hass.async_run_hass_job(job, event) except Exception: # pylint: disable=broad-except _LOGGER.exception( "Error while processing entity registry update for %s", entity_id, ) hass.data[TRACK_ENTITY_REGISTRY_UPDATED_LISTENER] = hass.bus.async_listen( EVENT_ENTITY_REGISTRY_UPDATED, _async_entity_registry_updated_dispatcher, event_filter=_async_entity_registry_updated_filter, ) job = HassJob(action) for entity_id in entity_ids: entity_callbacks.setdefault(entity_id, []).append(job) @callback def remove_listener() -> None: """Remove state change listener.""" _async_remove_indexed_listeners( hass, TRACK_ENTITY_REGISTRY_UPDATED_CALLBACKS, TRACK_ENTITY_REGISTRY_UPDATED_LISTENER, entity_ids, job, ) return remove_listener @callback def _async_dispatch_domain_event( hass: HomeAssistant, event: Event, callbacks: dict[str, list] ) -> None: domain = split_entity_id(event.data["entity_id"])[0] if domain not in callbacks and MATCH_ALL not in callbacks: return listeners = callbacks.get(domain, []) + callbacks.get(MATCH_ALL, []) for job in listeners: try: hass.async_run_hass_job(job, event) except Exception: # pylint: disable=broad-except _LOGGER.exception( "Error while processing event %s for domain %s", event, domain ) @bind_hass def async_track_state_added_domain( hass: HomeAssistant, domains: str | Iterable[str], action: Callable[[Event], Any], ) -> Callable[[], None]: """Track state change events when an entity is added to domains.""" domains = _async_string_to_lower_list(domains) if not domains: return _remove_empty_listener domain_callbacks = hass.data.setdefault(TRACK_STATE_ADDED_DOMAIN_CALLBACKS, {}) if TRACK_STATE_ADDED_DOMAIN_LISTENER not in hass.data: @callback def _async_state_change_filter(event: Event) -> bool: """Filter state changes by entity_id.""" return event.data.get("old_state") is None @callback def _async_state_change_dispatcher(event: Event) -> None: """Dispatch state changes by entity_id.""" if event.data.get("old_state") is not None: return _async_dispatch_domain_event(hass, event, domain_callbacks) hass.data[TRACK_STATE_ADDED_DOMAIN_LISTENER] = hass.bus.async_listen( EVENT_STATE_CHANGED, _async_state_change_dispatcher, event_filter=_async_state_change_filter, ) job = HassJob(action) for domain in domains: domain_callbacks.setdefault(domain, []).append(job) @callback def remove_listener() -> None: """Remove state change listener.""" _async_remove_indexed_listeners( hass, TRACK_STATE_ADDED_DOMAIN_CALLBACKS, TRACK_STATE_ADDED_DOMAIN_LISTENER, domains, job, ) return remove_listener @bind_hass def async_track_state_removed_domain( hass: HomeAssistant, domains: str | Iterable[str], action: Callable[[Event], Any], ) -> Callable[[], None]: """Track state change events when an entity is removed from domains.""" domains = _async_string_to_lower_list(domains) if not domains: return _remove_empty_listener domain_callbacks = hass.data.setdefault(TRACK_STATE_REMOVED_DOMAIN_CALLBACKS, {}) if TRACK_STATE_REMOVED_DOMAIN_LISTENER not in hass.data: @callback def _async_state_change_filter(event: Event) -> bool: """Filter state changes by entity_id.""" return event.data.get("new_state") is None @callback def _async_state_change_dispatcher(event: Event) -> None: """Dispatch state changes by entity_id.""" if event.data.get("new_state") is not None: return _async_dispatch_domain_event(hass, event, domain_callbacks) hass.data[TRACK_STATE_REMOVED_DOMAIN_LISTENER] = hass.bus.async_listen( EVENT_STATE_CHANGED, _async_state_change_dispatcher, event_filter=_async_state_change_filter, ) job = HassJob(action) for domain in domains: domain_callbacks.setdefault(domain, []).append(job) @callback def remove_listener() -> None: """Remove state change listener.""" _async_remove_indexed_listeners( hass, TRACK_STATE_REMOVED_DOMAIN_CALLBACKS, TRACK_STATE_REMOVED_DOMAIN_LISTENER, domains, job, ) return remove_listener @callback def _async_string_to_lower_list(instr: str | Iterable[str]) -> list[str]: if isinstance(instr, str): return [instr.lower()] return [mstr.lower() for mstr in instr] class _TrackStateChangeFiltered: """Handle removal / refresh of tracker.""" def __init__( self, hass: HomeAssistant, track_states: TrackStates, action: Callable[[Event], Any], ): """Handle removal / refresh of tracker init.""" self.hass = hass self._action = action self._listeners: dict[str, Callable] = {} self._last_track_states: TrackStates = track_states @callback def async_setup(self) -> None: """Create listeners to track states.""" track_states = self._last_track_states if ( not track_states.all_states and not track_states.domains and not track_states.entities ): return if track_states.all_states: self._setup_all_listener() return self._setup_domains_listener(track_states.domains) self._setup_entities_listener(track_states.domains, track_states.entities) @property def listeners(self) -> dict: """State changes that will cause a re-render.""" track_states = self._last_track_states return { _ALL_LISTENER: track_states.all_states, _ENTITIES_LISTENER: track_states.entities, _DOMAINS_LISTENER: track_states.domains, } @callback def async_update_listeners(self, new_track_states: TrackStates) -> None: """Update the listeners based on the new TrackStates.""" last_track_states = self._last_track_states self._last_track_states = new_track_states had_all_listener = last_track_states.all_states if new_track_states.all_states: if had_all_listener: return self._cancel_listener(_DOMAINS_LISTENER) self._cancel_listener(_ENTITIES_LISTENER) self._setup_all_listener() return if had_all_listener: self._cancel_listener(_ALL_LISTENER) domains_changed = new_track_states.domains != last_track_states.domains if had_all_listener or domains_changed: domains_changed = True self._cancel_listener(_DOMAINS_LISTENER) self._setup_domains_listener(new_track_states.domains) if ( had_all_listener or domains_changed or new_track_states.entities != last_track_states.entities ): self._cancel_listener(_ENTITIES_LISTENER) self._setup_entities_listener( new_track_states.domains, new_track_states.entities ) @callback def async_remove(self) -> None: """Cancel the listeners.""" for key in list(self._listeners): self._listeners.pop(key)() @callback def _cancel_listener(self, listener_name: str) -> None: if listener_name not in self._listeners: return self._listeners.pop(listener_name)() @callback def _setup_entities_listener(self, domains: set, entities: set) -> None: if domains: entities = entities.copy() entities.update(self.hass.states.async_entity_ids(domains)) # Entities has changed to none if not entities: return self._listeners[_ENTITIES_LISTENER] = async_track_state_change_event( self.hass, entities, self._action ) @callback def _setup_domains_listener(self, domains: set) -> None: if not domains: return self._listeners[_DOMAINS_LISTENER] = async_track_state_added_domain( self.hass, domains, self._action ) @callback def _setup_all_listener(self) -> None: self._listeners[_ALL_LISTENER] = self.hass.bus.async_listen( EVENT_STATE_CHANGED, self._action ) @callback @bind_hass def async_track_state_change_filtered( hass: HomeAssistant, track_states: TrackStates, action: Callable[[Event], Any], ) -> _TrackStateChangeFiltered: """Track state changes with a TrackStates filter that can be updated. Parameters ---------- hass Home assistant object. track_states A TrackStates data class. action Callable to call with results. Returns ------- Object used to update the listeners (async_update_listeners) with a new TrackStates or cancel the tracking (async_remove). """ tracker = _TrackStateChangeFiltered(hass, track_states, action) tracker.async_setup() return tracker @callback @bind_hass def async_track_template( hass: HomeAssistant, template: Template, action: Callable[[str, State | None, State | None], None], variables: TemplateVarsType | None = None, ) -> Callable[[], None]: """Add a listener that fires when a a template evaluates to 'true'. Listen for the result of the template becoming true, or a true-like string result, such as 'On', 'Open', or 'Yes'. If the template results in an error state when the value changes, this will be logged and not passed through. If the initial check of the template is invalid and results in an exception, the listener will still be registered but will only fire if the template result becomes true without an exception. Action arguments ---------------- entity_id ID of the entity that triggered the state change. old_state The old state of the entity that changed. new_state New state of the entity that changed. Parameters ---------- hass Home assistant object. template The template to calculate. action Callable to call with results. See above for arguments. variables Variables to pass to the template. Returns ------- Callable to unregister the listener. """ job = HassJob(action) @callback def _template_changed_listener( event: Event, updates: list[TrackTemplateResult] ) -> None: """Check if condition is correct and run action.""" track_result = updates.pop() template = track_result.template last_result = track_result.last_result result = track_result.result if isinstance(result, TemplateError): _LOGGER.error( "Error while processing template: %s", template.template, exc_info=result, ) return if ( not isinstance(last_result, TemplateError) and result_as_boolean(last_result) or not result_as_boolean(result) ): return hass.async_run_hass_job( job, event and event.data.get("entity_id"), event and event.data.get("old_state"), event and event.data.get("new_state"), ) info = async_track_template_result( hass, [TrackTemplate(template, variables)], _template_changed_listener ) return info.async_remove track_template = threaded_listener_factory(async_track_template) class _TrackTemplateResultInfo: """Handle removal / refresh of tracker.""" def __init__( self, hass: HomeAssistant, track_templates: Iterable[TrackTemplate], action: Callable, ): """Handle removal / refresh of tracker init.""" self.hass = hass self._job = HassJob(action) for track_template_ in track_templates: track_template_.template.hass = hass self._track_templates = track_templates self._last_result: dict[Template, str | TemplateError] = {} self._rate_limit = KeyedRateLimit(hass) self._info: dict[Template, RenderInfo] = {} self._track_state_changes: _TrackStateChangeFiltered | None = None self._time_listeners: dict[Template, Callable] = {} def async_setup(self, raise_on_template_error: bool) -> None: """Activation of template tracking.""" for track_template_ in self._track_templates: template = track_template_.template variables = track_template_.variables self._info[template] = info = template.async_render_to_info(variables) if info.exception: if raise_on_template_error: raise info.exception _LOGGER.error( "Error while processing template: %s", track_template_.template, exc_info=info.exception, ) self._track_state_changes = async_track_state_change_filtered( self.hass, _render_infos_to_track_states(self._info.values()), self._refresh ) self._update_time_listeners() _LOGGER.debug( "Template group %s listens for %s", self._track_templates, self.listeners, ) @property def listeners(self) -> dict: """State changes that will cause a re-render.""" assert self._track_state_changes return { **self._track_state_changes.listeners, "time": bool(self._time_listeners), } @callback def _setup_time_listener(self, template: Template, has_time: bool) -> None: if not has_time: if template in self._time_listeners: # now() or utcnow() has left the scope of the template self._time_listeners.pop(template)() return if template in self._time_listeners: return track_templates = [ track_template_ for track_template_ in self._track_templates if track_template_.template == template ] @callback def _refresh_from_time(now: datetime) -> None: self._refresh(None, track_templates=track_templates) self._time_listeners[template] = async_track_utc_time_change( self.hass, _refresh_from_time, second=0 ) @callback def _update_time_listeners(self) -> None: for template, info in self._info.items(): self._setup_time_listener(template, info.has_time) @callback def async_remove(self) -> None: """Cancel the listener.""" assert self._track_state_changes self._track_state_changes.async_remove() self._rate_limit.async_remove() for template in list(self._time_listeners): self._time_listeners.pop(template)() @callback def async_refresh(self) -> None: """Force recalculate the template.""" self._refresh(None) def _render_template_if_ready( self, track_template_: TrackTemplate, now: datetime, event: Event | None, ) -> bool | TrackTemplateResult: """Re-render the template if conditions match. Returns False if the template was not be re-rendered Returns True if the template re-rendered and did not change. Returns TrackTemplateResult if the template re-render generates a new result. """ template = track_template_.template if event: info = self._info[template] if not _event_triggers_rerender(event, info): return False had_timer = self._rate_limit.async_has_timer(template) if self._rate_limit.async_schedule_action( template, _rate_limit_for_event(event, info, track_template_), now, self._refresh, event, (track_template_,), True, ): return not had_timer _LOGGER.debug( "Template update %s triggered by event: %s", template.template, event, ) self._rate_limit.async_triggered(template, now) self._info[template] = info = template.async_render_to_info( track_template_.variables ) try: result: str | TemplateError = info.result() except TemplateError as ex: result = ex last_result = self._last_result.get(template) # Check to see if the result has changed if result == last_result: return True if isinstance(result, TemplateError) and isinstance(last_result, TemplateError): return True return TrackTemplateResult(template, last_result, result) @callback def _refresh( self, event: Event | None, track_templates: Iterable[TrackTemplate] | None = None, replayed: bool | None = False, ) -> None: """Refresh the template. The event is the state_changed event that caused the refresh to be considered. track_templates is an optional list of TrackTemplate objects to refresh. If not provided, all tracked templates will be considered. replayed is True if the event is being replayed because the rate limit was hit. """ updates = [] info_changed = False now = event.time_fired if not replayed and event else dt_util.utcnow() for track_template_ in track_templates or self._track_templates: update = self._render_template_if_ready(track_template_, now, event) if not update: continue template = track_template_.template self._setup_time_listener(template, self._info[template].has_time) info_changed = True if isinstance(update, TrackTemplateResult): updates.append(update) if info_changed: assert self._track_state_changes self._track_state_changes.async_update_listeners( _render_infos_to_track_states( [ _suppress_domain_all_in_render_info(self._info[template]) if self._rate_limit.async_has_timer(template) else self._info[template] for template in self._info ] ) ) _LOGGER.debug( "Template group %s listens for %s", self._track_templates, self.listeners, ) if not updates: return for track_result in updates: self._last_result[track_result.template] = track_result.result self.hass.async_run_hass_job(self._job, event, updates) TrackTemplateResultListener = Callable[ [ Event, List[TrackTemplateResult], ], None, ] """Type for the listener for template results. Action arguments ---------------- event Event that caused the template to change output. None if not triggered by an event. updates A list of TrackTemplateResult """ @callback @bind_hass def async_track_template_result( hass: HomeAssistant, track_templates: Iterable[TrackTemplate], action: TrackTemplateResultListener, raise_on_template_error: bool = False, ) -> _TrackTemplateResultInfo: """Add a listener that fires when the result of a template changes. The action will fire with the initial result from the template, and then whenever the output from the template changes. The template will be reevaluated if any states referenced in the last run of the template change, or if manually triggered. If the result of the evaluation is different from the previous run, the listener is passed the result. If the template results in an TemplateError, this will be returned to the listener the first time this happens but not for subsequent errors. Once the template returns to a non-error condition the result is sent to the action as usual. Parameters ---------- hass Home assistant object. track_templates An iterable of TrackTemplate. action Callable to call with results. raise_on_template_error When set to True, if there is an exception processing the template during setup, the system will raise the exception instead of setting up tracking. Returns ------- Info object used to unregister the listener, and refresh the template. """ tracker = _TrackTemplateResultInfo(hass, track_templates, action) tracker.async_setup(raise_on_template_error) return tracker @callback @bind_hass def async_track_same_state( hass: HomeAssistant, period: timedelta, action: Callable[..., None], async_check_same_func: Callable[[str, State | None, State | None], bool], entity_ids: str | Iterable[str] = MATCH_ALL, ) -> CALLBACK_TYPE: """Track the state of entities for a period and run an action. If async_check_func is None it use the state of orig_value. Without entity_ids we track all state changes. """ async_remove_state_for_cancel: CALLBACK_TYPE | None = None async_remove_state_for_listener: CALLBACK_TYPE | None = None job = HassJob(action) @callback def clear_listener() -> None: """Clear all unsub listener.""" nonlocal async_remove_state_for_cancel, async_remove_state_for_listener if async_remove_state_for_listener is not None: async_remove_state_for_listener() async_remove_state_for_listener = None if async_remove_state_for_cancel is not None: async_remove_state_for_cancel() async_remove_state_for_cancel = None @callback def state_for_listener(now: Any) -> None: """Fire on state changes after a delay and calls action.""" nonlocal async_remove_state_for_listener async_remove_state_for_listener = None clear_listener() hass.async_run_hass_job(job) @callback def state_for_cancel_listener(event: Event) -> None: """Fire on changes and cancel for listener if changed.""" entity: str = event.data["entity_id"] from_state: State | None = event.data.get("old_state") to_state: State | None = event.data.get("new_state") if not async_check_same_func(entity, from_state, to_state): clear_listener() async_remove_state_for_listener = async_track_point_in_utc_time( hass, state_for_listener, dt_util.utcnow() + period ) if entity_ids == MATCH_ALL: async_remove_state_for_cancel = hass.bus.async_listen( EVENT_STATE_CHANGED, state_for_cancel_listener ) else: async_remove_state_for_cancel = async_track_state_change_event( hass, [entity_ids] if isinstance(entity_ids, str) else entity_ids, state_for_cancel_listener, ) return clear_listener track_same_state = threaded_listener_factory(async_track_same_state) @callback @bind_hass def async_track_point_in_time( hass: HomeAssistant, action: HassJob | Callable[..., None], point_in_time: datetime, ) -> CALLBACK_TYPE: """Add a listener that fires once after a specific point in time.""" job = action if isinstance(action, HassJob) else HassJob(action) @callback def utc_converter(utc_now: datetime) -> None: """Convert passed in UTC now to local now.""" hass.async_run_hass_job(job, dt_util.as_local(utc_now)) return async_track_point_in_utc_time(hass, utc_converter, point_in_time) track_point_in_time = threaded_listener_factory(async_track_point_in_time) @callback @bind_hass def async_track_point_in_utc_time( hass: HomeAssistant, action: HassJob | Callable[..., None], point_in_time: datetime, ) -> CALLBACK_TYPE: """Add a listener that fires once after a specific point in UTC time.""" # Ensure point_in_time is UTC utc_point_in_time = dt_util.as_utc(point_in_time) # Since this is called once, we accept a HassJob so we can avoid # having to figure out how to call the action every time its called. job = action if isinstance(action, HassJob) else HassJob(action) cancel_callback: asyncio.TimerHandle | None = None @callback def run_action() -> None: """Call the action.""" nonlocal cancel_callback now = time_tracker_utcnow() # Depending on the available clock support (including timer hardware # and the OS kernel) it can happen that we fire a little bit too early # as measured by utcnow(). That is bad when callbacks have assumptions # about the current time. Thus, we rearm the timer for the remaining # time. delta = (utc_point_in_time - now).total_seconds() if delta > 0: _LOGGER.debug("Called %f seconds too early, rearming", delta) cancel_callback = hass.loop.call_later(delta, run_action) return hass.async_run_hass_job(job, utc_point_in_time) delta = utc_point_in_time.timestamp() - time.time() cancel_callback = hass.loop.call_later(delta, run_action) @callback def unsub_point_in_time_listener() -> None: """Cancel the call_later.""" assert cancel_callback is not None cancel_callback.cancel() return unsub_point_in_time_listener track_point_in_utc_time = threaded_listener_factory(async_track_point_in_utc_time) @callback @bind_hass def async_call_later( hass: HomeAssistant, delay: float, action: HassJob | Callable[..., None] ) -> CALLBACK_TYPE: """Add a listener that is called in <delay>.""" return async_track_point_in_utc_time( hass, action, dt_util.utcnow() + timedelta(seconds=delay) ) call_later = threaded_listener_factory(async_call_later) @callback @bind_hass def async_track_time_interval( hass: HomeAssistant, action: Callable[..., None | Awaitable], interval: timedelta, ) -> CALLBACK_TYPE: """Add a listener that fires repetitively at every timedelta interval.""" remove = None interval_listener_job = None job = HassJob(action) def next_interval() -> datetime: """Return the next interval.""" return dt_util.utcnow() + interval @callback def interval_listener(now: datetime) -> None: """Handle elapsed intervals.""" nonlocal remove nonlocal interval_listener_job remove = async_track_point_in_utc_time( hass, interval_listener_job, next_interval() # type: ignore ) hass.async_run_hass_job(job, now) interval_listener_job = HassJob(interval_listener) remove = async_track_point_in_utc_time(hass, interval_listener_job, next_interval()) def remove_listener() -> None: """Remove interval listener.""" remove() # type: ignore return remove_listener track_time_interval = threaded_listener_factory(async_track_time_interval) @attr.s class SunListener: """Helper class to help listen to sun events.""" hass: HomeAssistant = attr.ib() job: HassJob = attr.ib() event: str = attr.ib() offset: timedelta | None = attr.ib() _unsub_sun: CALLBACK_TYPE | None = attr.ib(default=None) _unsub_config: CALLBACK_TYPE | None = attr.ib(default=None) @callback def async_attach(self) -> None: """Attach a sun listener.""" assert self._unsub_config is None self._unsub_config = self.hass.bus.async_listen( EVENT_CORE_CONFIG_UPDATE, self._handle_config_event ) self._listen_next_sun_event() @callback def async_detach(self) -> None: """Detach the sun listener.""" assert self._unsub_sun is not None assert self._unsub_config is not None self._unsub_sun() self._unsub_sun = None self._unsub_config() self._unsub_config = None @callback def _listen_next_sun_event(self) -> None: """Set up the sun event listener.""" assert self._unsub_sun is None self._unsub_sun = async_track_point_in_utc_time( self.hass, self._handle_sun_event, get_astral_event_next(self.hass, self.event, offset=self.offset), ) @callback def _handle_sun_event(self, _now: Any) -> None: """Handle solar event.""" self._unsub_sun = None self._listen_next_sun_event() self.hass.async_run_hass_job(self.job) @callback def _handle_config_event(self, _event: Any) -> None: """Handle core config update.""" assert self._unsub_sun is not None self._unsub_sun() self._unsub_sun = None self._listen_next_sun_event() @callback @bind_hass def async_track_sunrise( hass: HomeAssistant, action: Callable[..., None], offset: timedelta | None = None ) -> CALLBACK_TYPE: """Add a listener that will fire a specified offset from sunrise daily.""" listener = SunListener(hass, HassJob(action), SUN_EVENT_SUNRISE, offset) listener.async_attach() return listener.async_detach track_sunrise = threaded_listener_factory(async_track_sunrise) @callback @bind_hass def async_track_sunset( hass: HomeAssistant, action: Callable[..., None], offset: timedelta | None = None ) -> CALLBACK_TYPE: """Add a listener that will fire a specified offset from sunset daily.""" listener = SunListener(hass, HassJob(action), SUN_EVENT_SUNSET, offset) listener.async_attach() return listener.async_detach track_sunset = threaded_listener_factory(async_track_sunset) # For targeted patching in tests time_tracker_utcnow = dt_util.utcnow @callback @bind_hass def async_track_utc_time_change( hass: HomeAssistant, action: Callable[..., None], hour: Any | None = None, minute: Any | None = None, second: Any | None = None, local: bool = False, ) -> CALLBACK_TYPE: """Add a listener that will fire if time matches a pattern.""" job = HassJob(action) # We do not have to wrap the function with time pattern matching logic # if no pattern given if all(val is None for val in (hour, minute, second)): @callback def time_change_listener(event: Event) -> None: """Fire every time event that comes in.""" hass.async_run_hass_job(job, event.data[ATTR_NOW]) return hass.bus.async_listen(EVENT_TIME_CHANGED, time_change_listener) matching_seconds = dt_util.parse_time_expression(second, 0, 59) matching_minutes = dt_util.parse_time_expression(minute, 0, 59) matching_hours = dt_util.parse_time_expression(hour, 0, 23) def calculate_next(now: datetime) -> datetime: """Calculate and set the next time the trigger should fire.""" localized_now = dt_util.as_local(now) if local else now return dt_util.find_next_time_expression_time( localized_now, matching_seconds, matching_minutes, matching_hours ) time_listener: CALLBACK_TYPE | None = None @callback def pattern_time_change_listener(_: datetime) -> None: """Listen for matching time_changed events.""" nonlocal time_listener now = time_tracker_utcnow() hass.async_run_hass_job(job, dt_util.as_local(now) if local else now) time_listener = async_track_point_in_utc_time( hass, pattern_time_change_listener, calculate_next(now + timedelta(seconds=1)), ) time_listener = async_track_point_in_utc_time( hass, pattern_time_change_listener, calculate_next(dt_util.utcnow()) ) @callback def unsub_pattern_time_change_listener() -> None: """Cancel the time listener.""" assert time_listener is not None time_listener() return unsub_pattern_time_change_listener track_utc_time_change = threaded_listener_factory(async_track_utc_time_change) @callback @bind_hass def async_track_time_change( hass: HomeAssistant, action: Callable[..., None], hour: Any | None = None, minute: Any | None = None, second: Any | None = None, ) -> CALLBACK_TYPE: """Add a listener that will fire if UTC time matches a pattern.""" return async_track_utc_time_change(hass, action, hour, minute, second, local=True) track_time_change = threaded_listener_factory(async_track_time_change) def process_state_match(parameter: None | str | Iterable[str]) -> Callable[[str], bool]: """Convert parameter to function that matches input against parameter.""" if parameter is None or parameter == MATCH_ALL: return lambda _: True if isinstance(parameter, str) or not hasattr(parameter, "__iter__"): return lambda state: state == parameter parameter_set = set(parameter) return lambda state: state in parameter_set @callback def _entities_domains_from_render_infos( render_infos: Iterable[RenderInfo], ) -> tuple[set, set]: """Combine from multiple RenderInfo.""" entities = set() domains = set() for render_info in render_infos: if render_info.entities: entities.update(render_info.entities) if render_info.domains: domains.update(render_info.domains) if render_info.domains_lifecycle: domains.update(render_info.domains_lifecycle) return entities, domains @callback def _render_infos_needs_all_listener(render_infos: Iterable[RenderInfo]) -> bool: """Determine if an all listener is needed from RenderInfo.""" for render_info in render_infos: # Tracking all states if render_info.all_states or render_info.all_states_lifecycle: return True # Previous call had an exception # so we do not know which states # to track if render_info.exception: return True return False @callback def _render_infos_to_track_states(render_infos: Iterable[RenderInfo]) -> TrackStates: """Create a TrackStates dataclass from the latest RenderInfo.""" if _render_infos_needs_all_listener(render_infos): return TrackStates(True, set(), set()) return TrackStates(False, *_entities_domains_from_render_infos(render_infos)) @callback def _event_triggers_rerender(event: Event, info: RenderInfo) -> bool: """Determine if a template should be re-rendered from an event.""" entity_id = event.data.get(ATTR_ENTITY_ID) if info.filter(entity_id): return True if ( event.data.get("new_state") is not None and event.data.get("old_state") is not None ): return False return bool(info.filter_lifecycle(entity_id)) @callback def _rate_limit_for_event( event: Event, info: RenderInfo, track_template_: TrackTemplate ) -> timedelta | None: """Determine the rate limit for an event.""" entity_id = event.data.get(ATTR_ENTITY_ID) # Specifically referenced entities are excluded # from the rate limit if entity_id in info.entities: return None if track_template_.rate_limit is not None: return track_template_.rate_limit rate_limit: timedelta | None = info.rate_limit return rate_limit def _suppress_domain_all_in_render_info(render_info: RenderInfo) -> RenderInfo: """Remove the domains and all_states from render info during a ratelimit.""" rate_limited_render_info = copy.copy(render_info) rate_limited_render_info.all_states = False rate_limited_render_info.all_states_lifecycle = False rate_limited_render_info.domains = set() rate_limited_render_info.domains_lifecycle = set() return rate_limited_render_info
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/helpers/event.py
"""Support for Frontier Silicon Devices (Medion, Hama, Auna,...).""" import logging from afsapi import AFSAPI import requests import voluptuous as vol from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerEntity from homeassistant.components.media_player.const import ( MEDIA_TYPE_MUSIC, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_SEEK, SUPPORT_SELECT_SOURCE, SUPPORT_STOP, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_VOLUME_STEP, ) from homeassistant.const import ( CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_PORT, STATE_IDLE, STATE_OFF, STATE_PAUSED, STATE_PLAYING, STATE_UNKNOWN, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) SUPPORT_FRONTIER_SILICON = ( SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | SUPPORT_VOLUME_STEP | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK | SUPPORT_SEEK | SUPPORT_PLAY_MEDIA | SUPPORT_PLAY | SUPPORT_STOP | SUPPORT_TURN_ON | SUPPORT_TURN_OFF | SUPPORT_SELECT_SOURCE ) DEFAULT_PORT = 80 DEFAULT_PASSWORD = "1234" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_PASSWORD, default=DEFAULT_PASSWORD): cv.string, vol.Optional(CONF_NAME): cv.string, } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Frontier Silicon platform.""" if discovery_info is not None: async_add_entities( [AFSAPIDevice(discovery_info["ssdp_description"], DEFAULT_PASSWORD, None)], True, ) return True host = config.get(CONF_HOST) port = config.get(CONF_PORT) password = config.get(CONF_PASSWORD) name = config.get(CONF_NAME) try: async_add_entities( [AFSAPIDevice(f"http://{host}:{port}/device", password, name)], True ) _LOGGER.debug("FSAPI device %s:%s -> %s", host, port, password) return True except requests.exceptions.RequestException: _LOGGER.error( "Could not add the FSAPI device at %s:%s -> %s", host, port, password ) return False class AFSAPIDevice(MediaPlayerEntity): """Representation of a Frontier Silicon device on the network.""" def __init__(self, device_url, password, name): """Initialize the Frontier Silicon API device.""" self._device_url = device_url self._password = password self._state = None self._name = name self._title = None self._artist = None self._album_name = None self._mute = None self._source = None self._source_list = None self._media_image_url = None self._max_volume = None self._volume_level = None # Properties @property def fs_device(self): """ Create a fresh fsapi session. A new session is created for each request in case someone else connected to the device in between the updates and invalidated the existing session (i.e UNDOK). """ return AFSAPI(self._device_url, self._password) @property def name(self): """Return the device name.""" return self._name @property def media_title(self): """Title of current playing media.""" return self._title @property def media_artist(self): """Artist of current playing media, music track only.""" return self._artist @property def media_album_name(self): """Album name of current playing media, music track only.""" return self._album_name @property def media_content_type(self): """Content type of current playing media.""" return MEDIA_TYPE_MUSIC @property def supported_features(self): """Flag of media commands that are supported.""" return SUPPORT_FRONTIER_SILICON @property def state(self): """Return the state of the player.""" return self._state # source @property def source_list(self): """List of available input sources.""" return self._source_list @property def source(self): """Name of the current input source.""" return self._source @property def media_image_url(self): """Image url of current playing media.""" return self._media_image_url @property def volume_level(self): """Volume level of the media player (0..1).""" return self._volume_level async def async_update(self): """Get the latest date and update device state.""" fs_device = self.fs_device if not self._name: self._name = await fs_device.get_friendly_name() if not self._source_list: self._source_list = await fs_device.get_mode_list() # The API seems to include 'zero' in the number of steps (e.g. if the range is # 0-40 then get_volume_steps returns 41) subtract one to get the max volume. # If call to get_volume fails set to 0 and try again next time. if not self._max_volume: self._max_volume = int(await fs_device.get_volume_steps() or 1) - 1 if await fs_device.get_power(): status = await fs_device.get_play_status() self._state = { "playing": STATE_PLAYING, "paused": STATE_PAUSED, "stopped": STATE_IDLE, "unknown": STATE_UNKNOWN, None: STATE_IDLE, }.get(status, STATE_UNKNOWN) else: self._state = STATE_OFF if self._state != STATE_OFF: info_name = await fs_device.get_play_name() info_text = await fs_device.get_play_text() self._title = " - ".join(filter(None, [info_name, info_text])) self._artist = await fs_device.get_play_artist() self._album_name = await fs_device.get_play_album() self._source = await fs_device.get_mode() self._mute = await fs_device.get_mute() self._media_image_url = await fs_device.get_play_graphic() volume = await self.fs_device.get_volume() # Prevent division by zero if max_volume not known yet self._volume_level = float(volume or 0) / (self._max_volume or 1) else: self._title = None self._artist = None self._album_name = None self._source = None self._mute = None self._media_image_url = None self._volume_level = None # Management actions # power control async def async_turn_on(self): """Turn on the device.""" await self.fs_device.set_power(True) async def async_turn_off(self): """Turn off the device.""" await self.fs_device.set_power(False) async def async_media_play(self): """Send play command.""" await self.fs_device.play() async def async_media_pause(self): """Send pause command.""" await self.fs_device.pause() async def async_media_play_pause(self): """Send play/pause command.""" if "playing" in self._state: await self.fs_device.pause() else: await self.fs_device.play() async def async_media_stop(self): """Send play/pause command.""" await self.fs_device.pause() async def async_media_previous_track(self): """Send previous track command (results in rewind).""" await self.fs_device.rewind() async def async_media_next_track(self): """Send next track command (results in fast-forward).""" await self.fs_device.forward() # mute @property def is_volume_muted(self): """Boolean if volume is currently muted.""" return self._mute async def async_mute_volume(self, mute): """Send mute command.""" await self.fs_device.set_mute(mute) # volume async def async_volume_up(self): """Send volume up command.""" volume = await self.fs_device.get_volume() volume = int(volume or 0) + 1 await self.fs_device.set_volume(min(volume, self._max_volume)) async def async_volume_down(self): """Send volume down command.""" volume = await self.fs_device.get_volume() volume = int(volume or 0) - 1 await self.fs_device.set_volume(max(volume, 0)) async def async_set_volume_level(self, volume): """Set volume command.""" if self._max_volume: # Can't do anything sensible if not set volume = int(volume * self._max_volume) await self.fs_device.set_volume(volume) async def async_select_source(self, source): """Select input source.""" await self.fs_device.set_mode(source)
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/frontier_silicon/media_player.py
"""Support for AquaLogic devices.""" from datetime import timedelta import logging import threading import time from aqualogic.core import AquaLogic import voluptuous as vol from homeassistant.const import ( CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP, ) from homeassistant.helpers import config_validation as cv _LOGGER = logging.getLogger(__name__) DOMAIN = "aqualogic" UPDATE_TOPIC = f"{DOMAIN}_update" CONF_UNIT = "unit" RECONNECT_INTERVAL = timedelta(seconds=10) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( {vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PORT): cv.port} ) }, extra=vol.ALLOW_EXTRA, ) def setup(hass, config): """Set up AquaLogic platform.""" host = config[DOMAIN][CONF_HOST] port = config[DOMAIN][CONF_PORT] processor = AquaLogicProcessor(hass, host, port) hass.data[DOMAIN] = processor hass.bus.listen_once(EVENT_HOMEASSISTANT_START, processor.start_listen) hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, processor.shutdown) _LOGGER.debug("AquaLogicProcessor %s:%i initialized", host, port) return True class AquaLogicProcessor(threading.Thread): """AquaLogic event processor thread.""" def __init__(self, hass, host, port): """Initialize the data object.""" super().__init__(daemon=True) self._hass = hass self._host = host self._port = port self._shutdown = False self._panel = None def start_listen(self, event): """Start event-processing thread.""" _LOGGER.debug("Event processing thread started") self.start() def shutdown(self, event): """Signal shutdown of processing event.""" _LOGGER.debug("Event processing signaled exit") self._shutdown = True def data_changed(self, panel): """Aqualogic data changed callback.""" self._hass.helpers.dispatcher.dispatcher_send(UPDATE_TOPIC) def run(self): """Event thread.""" while True: self._panel = AquaLogic() self._panel.connect(self._host, self._port) self._panel.process(self.data_changed) if self._shutdown: return _LOGGER.error("Connection to %s:%d lost", self._host, self._port) time.sleep(RECONNECT_INTERVAL.seconds) @property def panel(self): """Retrieve the AquaLogic object.""" return self._panel
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/aqualogic/__init__.py
"""Support for Azure DevOps.""" from __future__ import annotations import logging from typing import Any from aioazuredevops.client import DevOpsClient import aiohttp from homeassistant.components.azure_devops.const import ( CONF_ORG, CONF_PAT, CONF_PROJECT, DATA_AZURE_DEVOPS_CLIENT, DOMAIN, ) from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntry from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.entity import Entity from homeassistant.helpers.typing import ConfigType, HomeAssistantType _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Set up Azure DevOps from a config entry.""" client = DevOpsClient() try: if entry.data[CONF_PAT] is not None: await client.authorize(entry.data[CONF_PAT], entry.data[CONF_ORG]) if not client.authorized: _LOGGER.warning( "Could not authorize with Azure DevOps. You may need to update your token" ) hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_REAUTH}, data=entry.data, ) ) return False await client.get_project(entry.data[CONF_ORG], entry.data[CONF_PROJECT]) except aiohttp.ClientError as exception: _LOGGER.warning(exception) raise ConfigEntryNotReady from exception instance_key = f"{DOMAIN}_{entry.data[CONF_ORG]}_{entry.data[CONF_PROJECT]}" hass.data.setdefault(instance_key, {})[DATA_AZURE_DEVOPS_CLIENT] = client # Setup components hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "sensor") ) return True async def async_unload_entry(hass: HomeAssistantType, entry: ConfigType) -> bool: """Unload Azure DevOps config entry.""" del hass.data[f"{DOMAIN}_{entry.data[CONF_ORG]}_{entry.data[CONF_PROJECT]}"] return await hass.config_entries.async_forward_entry_unload(entry, "sensor") class AzureDevOpsEntity(Entity): """Defines a base Azure DevOps entity.""" def __init__(self, organization: str, project: str, name: str, icon: str) -> None: """Initialize the Azure DevOps entity.""" self._name = name self._icon = icon self._available = True self.organization = organization self.project = project @property def name(self) -> str: """Return the name of the entity.""" return self._name @property def icon(self) -> str: """Return the mdi icon of the entity.""" return self._icon @property def available(self) -> bool: """Return True if entity is available.""" return self._available async def async_update(self) -> None: """Update Azure DevOps entity.""" if await self._azure_devops_update(): self._available = True else: if self._available: _LOGGER.debug( "An error occurred while updating Azure DevOps sensor", exc_info=True, ) self._available = False async def _azure_devops_update(self) -> None: """Update Azure DevOps entity.""" raise NotImplementedError() class AzureDevOpsDeviceEntity(AzureDevOpsEntity): """Defines a Azure DevOps device entity.""" @property def device_info(self) -> dict[str, Any]: """Return device information about this Azure DevOps instance.""" return { "identifiers": { ( DOMAIN, self.organization, self.project, ) }, "manufacturer": self.organization, "name": self.project, "entry_type": "service", }
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/azure_devops/__init__.py
"""Blueprint models.""" from __future__ import annotations import asyncio import logging import pathlib import shutil from typing import Any from awesomeversion import AwesomeVersion import voluptuous as vol from voluptuous.humanize import humanize_error from homeassistant import loader from homeassistant.const import ( CONF_DEFAULT, CONF_DOMAIN, CONF_NAME, CONF_PATH, __version__, ) from homeassistant.core import DOMAIN as HA_DOMAIN, HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.util import yaml from .const import ( BLUEPRINT_FOLDER, CONF_BLUEPRINT, CONF_HOMEASSISTANT, CONF_INPUT, CONF_MIN_VERSION, CONF_SOURCE_URL, CONF_USE_BLUEPRINT, DOMAIN, ) from .errors import ( BlueprintException, FailedToLoad, FileAlreadyExists, InvalidBlueprint, InvalidBlueprintInputs, MissingInput, ) from .schemas import BLUEPRINT_INSTANCE_FIELDS, BLUEPRINT_SCHEMA class Blueprint: """Blueprint of a configuration structure.""" def __init__( self, data: dict, *, path: str | None = None, expected_domain: str | None = None, ) -> None: """Initialize a blueprint.""" try: data = self.data = BLUEPRINT_SCHEMA(data) except vol.Invalid as err: raise InvalidBlueprint(expected_domain, path, data, err) from err # In future, we will treat this as "incorrect" and allow to recover from this data_domain = data[CONF_BLUEPRINT][CONF_DOMAIN] if expected_domain is not None and data_domain != expected_domain: raise InvalidBlueprint( expected_domain, path or self.name, data, f"Found incorrect blueprint type {data_domain}, expected {expected_domain}", ) self.domain = data_domain missing = yaml.extract_inputs(data) - set(data[CONF_BLUEPRINT][CONF_INPUT]) if missing: raise InvalidBlueprint( data_domain, path or self.name, data, f"Missing input definition for {', '.join(missing)}", ) @property def name(self) -> str: """Return blueprint name.""" return self.data[CONF_BLUEPRINT][CONF_NAME] @property def inputs(self) -> dict: """Return blueprint inputs.""" return self.data[CONF_BLUEPRINT][CONF_INPUT] @property def metadata(self) -> dict: """Return blueprint metadata.""" return self.data[CONF_BLUEPRINT] def update_metadata(self, *, source_url: str | None = None) -> None: """Update metadata.""" if source_url is not None: self.data[CONF_BLUEPRINT][CONF_SOURCE_URL] = source_url def yaml(self) -> str: """Dump blueprint as YAML.""" return yaml.dump(self.data) @callback def validate(self) -> list[str] | None: """Test if the Home Assistant installation supports this blueprint. Return list of errors if not valid. """ errors = [] metadata = self.metadata min_version = metadata.get(CONF_HOMEASSISTANT, {}).get(CONF_MIN_VERSION) if min_version is not None and AwesomeVersion(__version__) < AwesomeVersion( min_version ): errors.append(f"Requires at least Home Assistant {min_version}") return errors or None class BlueprintInputs: """Inputs for a blueprint.""" def __init__( self, blueprint: Blueprint, config_with_inputs: dict[str, Any] ) -> None: """Instantiate a blueprint inputs object.""" self.blueprint = blueprint self.config_with_inputs = config_with_inputs @property def inputs(self): """Return the inputs.""" return self.config_with_inputs[CONF_USE_BLUEPRINT][CONF_INPUT] @property def inputs_with_default(self): """Return the inputs and fallback to defaults.""" no_input = set(self.blueprint.inputs) - set(self.inputs) inputs_with_default = dict(self.inputs) for inp in no_input: blueprint_input = self.blueprint.inputs[inp] if isinstance(blueprint_input, dict) and CONF_DEFAULT in blueprint_input: inputs_with_default[inp] = blueprint_input[CONF_DEFAULT] return inputs_with_default def validate(self) -> None: """Validate the inputs.""" missing = set(self.blueprint.inputs) - set(self.inputs_with_default) if missing: raise MissingInput(self.blueprint.domain, self.blueprint.name, missing) # In future we can see if entities are correct domain, areas exist etc # using the new selector helper. @callback def async_substitute(self) -> dict: """Get the blueprint value with the inputs substituted.""" processed = yaml.substitute(self.blueprint.data, self.inputs_with_default) combined = {**processed, **self.config_with_inputs} # From config_with_inputs combined.pop(CONF_USE_BLUEPRINT) # From blueprint combined.pop(CONF_BLUEPRINT) return combined class DomainBlueprints: """Blueprints for a specific domain.""" def __init__( self, hass: HomeAssistant, domain: str, logger: logging.Logger, ) -> None: """Initialize a domain blueprints instance.""" self.hass = hass self.domain = domain self.logger = logger self._blueprints = {} self._load_lock = asyncio.Lock() hass.data.setdefault(DOMAIN, {})[domain] = self @property def blueprint_folder(self) -> pathlib.Path: """Return the blueprint folder.""" return pathlib.Path(self.hass.config.path(BLUEPRINT_FOLDER, self.domain)) @callback def async_reset_cache(self) -> None: """Reset the blueprint cache.""" self._blueprints = {} def _load_blueprint(self, blueprint_path) -> Blueprint: """Load a blueprint.""" try: blueprint_data = yaml.load_yaml(self.blueprint_folder / blueprint_path) except FileNotFoundError as err: raise FailedToLoad( self.domain, blueprint_path, FileNotFoundError(f"Unable to find {blueprint_path}"), ) from err except HomeAssistantError as err: raise FailedToLoad(self.domain, blueprint_path, err) from err return Blueprint( blueprint_data, expected_domain=self.domain, path=blueprint_path ) def _load_blueprints(self) -> dict[str, Blueprint | BlueprintException]: """Load all the blueprints.""" blueprint_folder = pathlib.Path( self.hass.config.path(BLUEPRINT_FOLDER, self.domain) ) results = {} for blueprint_path in blueprint_folder.glob("**/*.yaml"): blueprint_path = str(blueprint_path.relative_to(blueprint_folder)) if self._blueprints.get(blueprint_path) is None: try: self._blueprints[blueprint_path] = self._load_blueprint( blueprint_path ) except BlueprintException as err: self._blueprints[blueprint_path] = None results[blueprint_path] = err continue results[blueprint_path] = self._blueprints[blueprint_path] return results async def async_get_blueprints( self, ) -> dict[str, Blueprint | BlueprintException]: """Get all the blueprints.""" async with self._load_lock: return await self.hass.async_add_executor_job(self._load_blueprints) async def async_get_blueprint(self, blueprint_path: str) -> Blueprint: """Get a blueprint.""" def load_from_cache(): """Load blueprint from cache.""" blueprint = self._blueprints[blueprint_path] if blueprint is None: raise FailedToLoad( self.domain, blueprint_path, FileNotFoundError(f"Unable to find {blueprint_path}"), ) return blueprint if blueprint_path in self._blueprints: return load_from_cache() async with self._load_lock: # Check it again if blueprint_path in self._blueprints: return load_from_cache() try: blueprint = await self.hass.async_add_executor_job( self._load_blueprint, blueprint_path ) except Exception: self._blueprints[blueprint_path] = None raise self._blueprints[blueprint_path] = blueprint return blueprint async def async_inputs_from_config( self, config_with_blueprint: dict ) -> BlueprintInputs: """Process a blueprint config.""" try: config_with_blueprint = BLUEPRINT_INSTANCE_FIELDS(config_with_blueprint) except vol.Invalid as err: raise InvalidBlueprintInputs( self.domain, humanize_error(config_with_blueprint, err) ) from err bp_conf = config_with_blueprint[CONF_USE_BLUEPRINT] blueprint = await self.async_get_blueprint(bp_conf[CONF_PATH]) inputs = BlueprintInputs(blueprint, config_with_blueprint) inputs.validate() return inputs async def async_remove_blueprint(self, blueprint_path: str) -> None: """Remove a blueprint file.""" path = self.blueprint_folder / blueprint_path await self.hass.async_add_executor_job(path.unlink) self._blueprints[blueprint_path] = None def _create_file(self, blueprint: Blueprint, blueprint_path: str) -> None: """Create blueprint file.""" path = pathlib.Path( self.hass.config.path(BLUEPRINT_FOLDER, self.domain, blueprint_path) ) if path.exists(): raise FileAlreadyExists(self.domain, blueprint_path) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(blueprint.yaml()) async def async_add_blueprint( self, blueprint: Blueprint, blueprint_path: str ) -> None: """Add a blueprint.""" if not blueprint_path.endswith(".yaml"): blueprint_path = f"{blueprint_path}.yaml" await self.hass.async_add_executor_job( self._create_file, blueprint, blueprint_path ) self._blueprints[blueprint_path] = blueprint async def async_populate(self) -> None: """Create folder if it doesn't exist and populate with examples.""" integration = await loader.async_get_integration(self.hass, self.domain) def populate(): if self.blueprint_folder.exists(): return shutil.copytree( integration.file_path / BLUEPRINT_FOLDER, self.blueprint_folder / HA_DOMAIN, ) await self.hass.async_add_executor_job(populate)
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/blueprint/models.py
"""Support for Genius Hub switch/outlet devices.""" from datetime import timedelta import voluptuous as vol from homeassistant.components.switch import DEVICE_CLASS_OUTLET, SwitchEntity from homeassistant.const import ATTR_ENTITY_ID from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.typing import ConfigType, HomeAssistantType from . import ATTR_DURATION, DOMAIN, GeniusZone GH_ON_OFF_ZONE = "on / off" SVC_SET_SWITCH_OVERRIDE = "set_switch_override" SET_SWITCH_OVERRIDE_SCHEMA = vol.Schema( { vol.Required(ATTR_ENTITY_ID): cv.entity_id, vol.Optional(ATTR_DURATION): vol.All( cv.time_period, vol.Range(min=timedelta(minutes=5), max=timedelta(days=1)), ), } ) async def async_setup_platform( hass: HomeAssistantType, config: ConfigType, async_add_entities, discovery_info=None ) -> None: """Set up the Genius Hub switch entities.""" if discovery_info is None: return broker = hass.data[DOMAIN]["broker"] async_add_entities( [ GeniusSwitch(broker, z) for z in broker.client.zone_objs if z.data["type"] == GH_ON_OFF_ZONE ] ) # Register custom services platform = entity_platform.current_platform.get() platform.async_register_entity_service( SVC_SET_SWITCH_OVERRIDE, SET_SWITCH_OVERRIDE_SCHEMA, "async_turn_on", ) class GeniusSwitch(GeniusZone, SwitchEntity): """Representation of a Genius Hub switch.""" @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" return DEVICE_CLASS_OUTLET @property def is_on(self) -> bool: """Return the current state of the on/off zone. The zone is considered 'on' if & only if it is override/on (e.g. timer/on is 'off'). """ return self._zone.data["mode"] == "override" and self._zone.data["setpoint"] async def async_turn_off(self, **kwargs) -> None: """Send the zone to Timer mode. The zone is deemed 'off' in this mode, although the plugs may actually be on. """ await self._zone.set_mode("timer") async def async_turn_on(self, **kwargs) -> None: """Set the zone to override/on ({'setpoint': true}) for x seconds.""" await self._zone.set_override(1, kwargs.get(ATTR_DURATION, 3600))
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/geniushub/switch.py
"""Support for exposing Home Assistant via Zeroconf.""" from __future__ import annotations from contextlib import suppress import fnmatch from functools import partial import ipaddress import logging import socket from typing import Any, TypedDict import voluptuous as vol from zeroconf import ( Error as ZeroconfError, InterfaceChoice, IPVersion, NonUniqueNameException, ServiceInfo, ServiceStateChange, Zeroconf, ) from homeassistant import util from homeassistant.const import ( EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STARTED, EVENT_HOMEASSISTANT_STOP, __version__, ) from homeassistant.core import Event, HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.network import NoURLAvailableError, get_url from homeassistant.helpers.singleton import singleton from homeassistant.loader import async_get_homekit, async_get_zeroconf from .models import HaServiceBrowser, HaZeroconf from .usage import install_multiple_zeroconf_catcher _LOGGER = logging.getLogger(__name__) DOMAIN = "zeroconf" ZEROCONF_TYPE = "_home-assistant._tcp.local." HOMEKIT_TYPES = [ "_hap._tcp.local.", # Thread based devices "_hap._udp.local.", ] CONF_DEFAULT_INTERFACE = "default_interface" CONF_IPV6 = "ipv6" DEFAULT_DEFAULT_INTERFACE = True DEFAULT_IPV6 = True HOMEKIT_PAIRED_STATUS_FLAG = "sf" HOMEKIT_MODEL = "md" # Property key=value has a max length of 255 # so we use 230 to leave space for key= MAX_PROPERTY_VALUE_LEN = 230 # Dns label max length MAX_NAME_LEN = 63 CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Optional( CONF_DEFAULT_INTERFACE, default=DEFAULT_DEFAULT_INTERFACE ): cv.boolean, vol.Optional(CONF_IPV6, default=DEFAULT_IPV6): cv.boolean, } ) }, extra=vol.ALLOW_EXTRA, ) class HaServiceInfo(TypedDict): """Prepared info from mDNS entries.""" host: str port: int | None hostname: str type: str name: str properties: dict[str, Any] @singleton(DOMAIN) async def async_get_instance(hass: HomeAssistant) -> HaZeroconf: """Zeroconf instance to be shared with other integrations that use it.""" return await _async_get_instance(hass) async def _async_get_instance(hass: HomeAssistant, **zcargs: Any) -> HaZeroconf: logging.getLogger("zeroconf").setLevel(logging.NOTSET) zeroconf = await hass.async_add_executor_job(partial(HaZeroconf, **zcargs)) install_multiple_zeroconf_catcher(zeroconf) def _stop_zeroconf(_event: Event) -> None: """Stop Zeroconf.""" zeroconf.ha_close() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _stop_zeroconf) return zeroconf async def async_setup(hass: HomeAssistant, config: dict) -> bool: """Set up Zeroconf and make Home Assistant discoverable.""" zc_config = config.get(DOMAIN, {}) zc_args: dict = {} if zc_config.get(CONF_DEFAULT_INTERFACE, DEFAULT_DEFAULT_INTERFACE): zc_args["interfaces"] = InterfaceChoice.Default if not zc_config.get(CONF_IPV6, DEFAULT_IPV6): zc_args["ip_version"] = IPVersion.V4Only zeroconf = hass.data[DOMAIN] = await _async_get_instance(hass, **zc_args) async def _async_zeroconf_hass_start(_event: Event) -> None: """Expose Home Assistant on zeroconf when it starts. Wait till started or otherwise HTTP is not up and running. """ uuid = await hass.helpers.instance_id.async_get() await hass.async_add_executor_job( _register_hass_zc_service, hass, zeroconf, uuid ) async def _async_zeroconf_hass_started(_event: Event) -> None: """Start the service browser.""" await _async_start_zeroconf_browser(hass, zeroconf) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, _async_zeroconf_hass_start) hass.bus.async_listen_once( EVENT_HOMEASSISTANT_STARTED, _async_zeroconf_hass_started ) return True def _register_hass_zc_service( hass: HomeAssistant, zeroconf: HaZeroconf, uuid: str ) -> None: # Get instance UUID valid_location_name = _truncate_location_name_to_valid(hass.config.location_name) params = { "location_name": valid_location_name, "uuid": uuid, "version": __version__, "external_url": "", "internal_url": "", # Old base URL, for backward compatibility "base_url": "", # Always needs authentication "requires_api_password": True, } # Get instance URL's with suppress(NoURLAvailableError): params["external_url"] = get_url(hass, allow_internal=False) with suppress(NoURLAvailableError): params["internal_url"] = get_url(hass, allow_external=False) # Set old base URL based on external or internal params["base_url"] = params["external_url"] or params["internal_url"] host_ip = util.get_local_ip() try: host_ip_pton = socket.inet_pton(socket.AF_INET, host_ip) except OSError: host_ip_pton = socket.inet_pton(socket.AF_INET6, host_ip) _suppress_invalid_properties(params) info = ServiceInfo( ZEROCONF_TYPE, name=f"{valid_location_name}.{ZEROCONF_TYPE}", server=f"{uuid}.local.", addresses=[host_ip_pton], port=hass.http.server_port, properties=params, ) _LOGGER.info("Starting Zeroconf broadcast") try: zeroconf.register_service(info) except NonUniqueNameException: _LOGGER.error( "Home Assistant instance with identical name present in the local network" ) async def _async_start_zeroconf_browser( hass: HomeAssistant, zeroconf: HaZeroconf ) -> None: """Start the zeroconf browser.""" zeroconf_types = await async_get_zeroconf(hass) homekit_models = await async_get_homekit(hass) types = list(zeroconf_types) for hk_type in HOMEKIT_TYPES: if hk_type not in zeroconf_types: types.append(hk_type) def service_update( zeroconf: Zeroconf, service_type: str, name: str, state_change: ServiceStateChange, ) -> None: """Service state changed.""" nonlocal zeroconf_types nonlocal homekit_models if state_change == ServiceStateChange.Removed: return try: service_info = zeroconf.get_service_info(service_type, name) except ZeroconfError: _LOGGER.exception("Failed to get info for device %s", name) return if not service_info: # Prevent the browser thread from collapsing as # service_info can be None _LOGGER.debug("Failed to get info for device %s", name) return info = info_from_service(service_info) if not info: # Prevent the browser thread from collapsing _LOGGER.debug("Failed to get addresses for device %s", name) return _LOGGER.debug("Discovered new device %s %s", name, info) # If we can handle it as a HomeKit discovery, we do that here. if service_type in HOMEKIT_TYPES: discovery_was_forwarded = handle_homekit(hass, homekit_models, info) # Continue on here as homekit_controller # still needs to get updates on devices # so it can see when the 'c#' field is updated. # # We only send updates to homekit_controller # if the device is already paired in order to avoid # offering a second discovery for the same device if ( discovery_was_forwarded and HOMEKIT_PAIRED_STATUS_FLAG in info["properties"] ): try: # 0 means paired and not discoverable by iOS clients) if int(info["properties"][HOMEKIT_PAIRED_STATUS_FLAG]): return except ValueError: # HomeKit pairing status unknown # likely bad homekit data return if "name" in info: lowercase_name: str | None = info["name"].lower() else: lowercase_name = None if "macaddress" in info["properties"]: uppercase_mac: str | None = info["properties"]["macaddress"].upper() else: uppercase_mac = None # Not all homekit types are currently used for discovery # so not all service type exist in zeroconf_types for entry in zeroconf_types.get(service_type, []): if len(entry) > 1: if ( uppercase_mac is not None and "macaddress" in entry and not fnmatch.fnmatch(uppercase_mac, entry["macaddress"]) ): continue if ( lowercase_name is not None and "name" in entry and not fnmatch.fnmatch(lowercase_name, entry["name"]) ): continue hass.add_job( hass.config_entries.flow.async_init( entry["domain"], context={"source": DOMAIN}, data=info ) # type: ignore ) _LOGGER.debug("Starting Zeroconf browser") HaServiceBrowser(zeroconf, types, handlers=[service_update]) def handle_homekit( hass: HomeAssistant, homekit_models: dict[str, str], info: HaServiceInfo ) -> bool: """Handle a HomeKit discovery. Return if discovery was forwarded. """ model = None props = info["properties"] for key in props: if key.lower() == HOMEKIT_MODEL: model = props[key] break if model is None: return False for test_model in homekit_models: if ( model != test_model and not model.startswith(f"{test_model} ") and not model.startswith(f"{test_model}-") ): continue hass.add_job( hass.config_entries.flow.async_init( homekit_models[test_model], context={"source": "homekit"}, data=info ) # type: ignore ) return True return False def info_from_service(service: ServiceInfo) -> HaServiceInfo | None: """Return prepared info from mDNS entries.""" properties: dict[str, Any] = {"_raw": {}} for key, value in service.properties.items(): # See https://ietf.org/rfc/rfc6763.html#section-6.4 and # https://ietf.org/rfc/rfc6763.html#section-6.5 for expected encodings # for property keys and values try: key = key.decode("ascii") except UnicodeDecodeError: _LOGGER.debug( "Ignoring invalid key provided by [%s]: %s", service.name, key ) continue properties["_raw"][key] = value with suppress(UnicodeDecodeError): if isinstance(value, bytes): properties[key] = value.decode("utf-8") if not service.addresses: return None address = service.addresses[0] return { "host": str(ipaddress.ip_address(address)), "port": service.port, "hostname": service.server, "type": service.type, "name": service.name, "properties": properties, } def _suppress_invalid_properties(properties: dict) -> None: """Suppress any properties that will cause zeroconf to fail to startup.""" for prop, prop_value in properties.items(): if not isinstance(prop_value, str): continue if len(prop_value.encode("utf-8")) > MAX_PROPERTY_VALUE_LEN: _LOGGER.error( "The property '%s' was suppressed because it is longer than the maximum length of %d bytes: %s", prop, MAX_PROPERTY_VALUE_LEN, prop_value, ) properties[prop] = "" def _truncate_location_name_to_valid(location_name: str) -> str: """Truncate or return the location name usable for zeroconf.""" if len(location_name.encode("utf-8")) < MAX_NAME_LEN: return location_name _LOGGER.warning( "The location name was truncated because it is longer than the maximum length of %d bytes: %s", MAX_NAME_LEN, location_name, ) return location_name.encode("utf-8")[:MAX_NAME_LEN].decode("utf-8", "ignore")
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/zeroconf/__init__.py
"""Support for Nest devices.""" import asyncio import logging from google_nest_sdm.event import EventMessage from google_nest_sdm.exceptions import ( AuthException, ConfigurationException, GoogleNestException, ) from google_nest_sdm.google_nest_subscriber import GoogleNestSubscriber import voluptuous as vol from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntry from homeassistant.const import ( CONF_BINARY_SENSORS, CONF_CLIENT_ID, CONF_CLIENT_SECRET, CONF_MONITORED_CONDITIONS, CONF_SENSORS, CONF_STRUCTURE, ) from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import ( aiohttp_client, config_entry_oauth2_flow, config_validation as cv, ) from . import api, config_flow from .const import DATA_SDM, DATA_SUBSCRIBER, DOMAIN, OAUTH2_AUTHORIZE, OAUTH2_TOKEN from .events import EVENT_NAME_MAP, NEST_EVENT from .legacy import async_setup_legacy, async_setup_legacy_entry _CONFIGURING = {} _LOGGER = logging.getLogger(__name__) CONF_PROJECT_ID = "project_id" CONF_SUBSCRIBER_ID = "subscriber_id" DATA_NEST_CONFIG = "nest_config" DATA_NEST_UNAVAILABLE = "nest_unavailable" NEST_SETUP_NOTIFICATION = "nest_setup" SENSOR_SCHEMA = vol.Schema( {vol.Optional(CONF_MONITORED_CONDITIONS): vol.All(cv.ensure_list)} ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Required(CONF_CLIENT_ID): cv.string, vol.Required(CONF_CLIENT_SECRET): cv.string, # Required to use the new API (optional for compatibility) vol.Optional(CONF_PROJECT_ID): cv.string, vol.Optional(CONF_SUBSCRIBER_ID): cv.string, # Config that only currently works on the old API vol.Optional(CONF_STRUCTURE): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_SENSORS): SENSOR_SCHEMA, vol.Optional(CONF_BINARY_SENSORS): SENSOR_SCHEMA, } ) }, extra=vol.ALLOW_EXTRA, ) # Platforms for SDM API PLATFORMS = ["sensor", "camera", "climate"] async def async_setup(hass: HomeAssistant, config: dict): """Set up Nest components with dispatch between old/new flows.""" hass.data[DOMAIN] = {} if DOMAIN not in config: return True if CONF_PROJECT_ID not in config[DOMAIN]: return await async_setup_legacy(hass, config) if CONF_SUBSCRIBER_ID not in config[DOMAIN]: _LOGGER.error("Configuration option '{CONF_SUBSCRIBER_ID}' required") return False # For setup of ConfigEntry below hass.data[DOMAIN][DATA_NEST_CONFIG] = config[DOMAIN] project_id = config[DOMAIN][CONF_PROJECT_ID] config_flow.NestFlowHandler.register_sdm_api(hass) config_flow.NestFlowHandler.async_register_implementation( hass, config_entry_oauth2_flow.LocalOAuth2Implementation( hass, DOMAIN, config[DOMAIN][CONF_CLIENT_ID], config[DOMAIN][CONF_CLIENT_SECRET], OAUTH2_AUTHORIZE.format(project_id=project_id), OAUTH2_TOKEN, ), ) return True class SignalUpdateCallback: """An EventCallback invoked when new events arrive from subscriber.""" def __init__(self, hass: HomeAssistant): """Initialize EventCallback.""" self._hass = hass async def async_handle_event(self, event_message: EventMessage): """Process an incoming EventMessage.""" if not event_message.resource_update_name: return device_id = event_message.resource_update_name events = event_message.resource_update_events if not events: return _LOGGER.debug("Event Update %s", events.keys()) device_registry = await self._hass.helpers.device_registry.async_get_registry() device_entry = device_registry.async_get_device({(DOMAIN, device_id)}) if not device_entry: return for event in events: event_type = EVENT_NAME_MAP.get(event) if not event_type: continue message = { "device_id": device_entry.id, "type": event_type, "timestamp": event_message.timestamp, } self._hass.bus.async_fire(NEST_EVENT, message) async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up Nest from a config entry with dispatch between old/new flows.""" if DATA_SDM not in entry.data: return await async_setup_legacy_entry(hass, entry) implementation = ( await config_entry_oauth2_flow.async_get_config_entry_implementation( hass, entry ) ) config = hass.data[DOMAIN][DATA_NEST_CONFIG] session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation) auth = api.AsyncConfigEntryAuth( aiohttp_client.async_get_clientsession(hass), session, config[CONF_CLIENT_ID], config[CONF_CLIENT_SECRET], ) subscriber = GoogleNestSubscriber( auth, config[CONF_PROJECT_ID], config[CONF_SUBSCRIBER_ID] ) callback = SignalUpdateCallback(hass) subscriber.set_update_callback(callback.async_handle_event) try: await subscriber.start_async() except AuthException as err: _LOGGER.debug("Subscriber authentication error: %s", err) hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_REAUTH}, data=entry.data, ) ) return False except ConfigurationException as err: _LOGGER.error("Configuration error: %s", err) subscriber.stop_async() return False except GoogleNestException as err: if DATA_NEST_UNAVAILABLE not in hass.data[DOMAIN]: _LOGGER.error("Subscriber error: %s", err) hass.data[DOMAIN][DATA_NEST_UNAVAILABLE] = True subscriber.stop_async() raise ConfigEntryNotReady from err try: await subscriber.async_get_device_manager() except GoogleNestException as err: if DATA_NEST_UNAVAILABLE not in hass.data[DOMAIN]: _LOGGER.error("Device manager error: %s", err) hass.data[DOMAIN][DATA_NEST_UNAVAILABLE] = True subscriber.stop_async() raise ConfigEntryNotReady from err hass.data[DOMAIN].pop(DATA_NEST_UNAVAILABLE, None) hass.data[DOMAIN][DATA_SUBSCRIBER] = subscriber for platform in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, platform) ) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry): """Unload a config entry.""" if DATA_SDM not in entry.data: # Legacy API return True _LOGGER.debug("Stopping nest subscriber") subscriber = hass.data[DOMAIN][DATA_SUBSCRIBER] subscriber.stop_async() unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, platform) for platform in PLATFORMS ] ) ) if unload_ok: hass.data[DOMAIN].pop(DATA_SUBSCRIBER) hass.data[DOMAIN].pop(DATA_NEST_UNAVAILABLE, None) return unload_ok
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/nest/__init__.py
"""Provides a binary sensor which gets its values from a TCP socket.""" from homeassistant.components.binary_sensor import BinarySensorEntity from .sensor import CONF_VALUE_ON, PLATFORM_SCHEMA, TcpSensor PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({}) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the TCP binary sensor.""" add_entities([TcpBinarySensor(hass, config)]) class TcpBinarySensor(BinarySensorEntity, TcpSensor): """A binary sensor which is on when its state == CONF_VALUE_ON.""" required = (CONF_VALUE_ON,) @property def is_on(self): """Return true if the binary sensor is on.""" return self._state == self._config[CONF_VALUE_ON]
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/tcp/binary_sensor.py
"""Register an iFrame front end panel.""" import voluptuous as vol from homeassistant.const import CONF_ICON, CONF_URL import homeassistant.helpers.config_validation as cv DOMAIN = "panel_iframe" CONF_TITLE = "title" CONF_RELATIVE_URL_ERROR_MSG = "Invalid relative URL. Absolute path required." CONF_RELATIVE_URL_REGEX = r"\A/" CONF_REQUIRE_ADMIN = "require_admin" CONFIG_SCHEMA = vol.Schema( { DOMAIN: cv.schema_with_slug_keys( vol.Schema( { # pylint: disable=no-value-for-parameter vol.Optional(CONF_TITLE): cv.string, vol.Optional(CONF_ICON): cv.icon, vol.Optional(CONF_REQUIRE_ADMIN, default=False): cv.boolean, vol.Required(CONF_URL): vol.Any( vol.Match( CONF_RELATIVE_URL_REGEX, msg=CONF_RELATIVE_URL_ERROR_MSG ), vol.Url(), ), } ) ) }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, config): """Set up the iFrame frontend panels.""" for url_path, info in config[DOMAIN].items(): hass.components.frontend.async_register_built_in_panel( "iframe", info.get(CONF_TITLE), info.get(CONF_ICON), url_path, {"url": info[CONF_URL]}, require_admin=info[CONF_REQUIRE_ADMIN], ) return True
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/panel_iframe/__init__.py
"""Support for lights through the SmartThings cloud API.""" from __future__ import annotations import asyncio from typing import Sequence from pysmartthings import Capability from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, ATTR_TRANSITION, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_TRANSITION, LightEntity, ) import homeassistant.util.color as color_util from . import SmartThingsEntity from .const import DATA_BROKERS, DOMAIN async def async_setup_entry(hass, config_entry, async_add_entities): """Add lights for a config entry.""" broker = hass.data[DOMAIN][DATA_BROKERS][config_entry.entry_id] async_add_entities( [ SmartThingsLight(device) for device in broker.devices.values() if broker.any_assigned(device.device_id, "light") ], True, ) def get_capabilities(capabilities: Sequence[str]) -> Sequence[str] | None: """Return all capabilities supported if minimum required are present.""" supported = [ Capability.switch, Capability.switch_level, Capability.color_control, Capability.color_temperature, ] # Must be able to be turned on/off. if Capability.switch not in capabilities: return None # Must have one of these light_capabilities = [ Capability.color_control, Capability.color_temperature, Capability.switch_level, ] if any(capability in capabilities for capability in light_capabilities): return supported return None def convert_scale(value, value_scale, target_scale, round_digits=4): """Convert a value to a different scale.""" return round(value * target_scale / value_scale, round_digits) class SmartThingsLight(SmartThingsEntity, LightEntity): """Define a SmartThings Light.""" def __init__(self, device): """Initialize a SmartThingsLight.""" super().__init__(device) self._brightness = None self._color_temp = None self._hs_color = None self._supported_features = self._determine_features() def _determine_features(self): """Get features supported by the device.""" features = 0 # Brightness and transition if Capability.switch_level in self._device.capabilities: features |= SUPPORT_BRIGHTNESS | SUPPORT_TRANSITION # Color Temperature if Capability.color_temperature in self._device.capabilities: features |= SUPPORT_COLOR_TEMP # Color if Capability.color_control in self._device.capabilities: features |= SUPPORT_COLOR return features async def async_turn_on(self, **kwargs) -> None: """Turn the light on.""" tasks = [] # Color temperature if self._supported_features & SUPPORT_COLOR_TEMP and ATTR_COLOR_TEMP in kwargs: tasks.append(self.async_set_color_temp(kwargs[ATTR_COLOR_TEMP])) # Color if self._supported_features & SUPPORT_COLOR and ATTR_HS_COLOR in kwargs: tasks.append(self.async_set_color(kwargs[ATTR_HS_COLOR])) if tasks: # Set temp/color first await asyncio.gather(*tasks) # Switch/brightness/transition if self._supported_features & SUPPORT_BRIGHTNESS and ATTR_BRIGHTNESS in kwargs: await self.async_set_level( kwargs[ATTR_BRIGHTNESS], kwargs.get(ATTR_TRANSITION, 0) ) else: await self._device.switch_on(set_status=True) # State is set optimistically in the commands above, therefore update # the entity state ahead of receiving the confirming push updates self.async_schedule_update_ha_state(True) async def async_turn_off(self, **kwargs) -> None: """Turn the light off.""" # Switch/transition if self._supported_features & SUPPORT_TRANSITION and ATTR_TRANSITION in kwargs: await self.async_set_level(0, int(kwargs[ATTR_TRANSITION])) else: await self._device.switch_off(set_status=True) # State is set optimistically in the commands above, therefore update # the entity state ahead of receiving the confirming push updates self.async_schedule_update_ha_state(True) async def async_update(self): """Update entity attributes when the device status has changed.""" # Brightness and transition if self._supported_features & SUPPORT_BRIGHTNESS: self._brightness = int( convert_scale(self._device.status.level, 100, 255, 0) ) # Color Temperature if self._supported_features & SUPPORT_COLOR_TEMP: self._color_temp = color_util.color_temperature_kelvin_to_mired( self._device.status.color_temperature ) # Color if self._supported_features & SUPPORT_COLOR: self._hs_color = ( convert_scale(self._device.status.hue, 100, 360), self._device.status.saturation, ) async def async_set_color(self, hs_color): """Set the color of the device.""" hue = convert_scale(float(hs_color[0]), 360, 100) hue = max(min(hue, 100.0), 0.0) saturation = max(min(float(hs_color[1]), 100.0), 0.0) await self._device.set_color(hue, saturation, set_status=True) async def async_set_color_temp(self, value: float): """Set the color temperature of the device.""" kelvin = color_util.color_temperature_mired_to_kelvin(value) kelvin = max(min(kelvin, 30000.0), 1.0) await self._device.set_color_temperature(kelvin, set_status=True) async def async_set_level(self, brightness: int, transition: int): """Set the brightness of the light over transition.""" level = int(convert_scale(brightness, 255, 100, 0)) # Due to rounding, set level to 1 (one) so we don't inadvertently # turn off the light when a low brightness is set. level = 1 if level == 0 and brightness > 0 else level level = max(min(level, 100), 0) duration = int(transition) await self._device.set_level(level, duration, set_status=True) @property def brightness(self): """Return the brightness of this light between 0..255.""" return self._brightness @property def color_temp(self): """Return the CT color value in mireds.""" return self._color_temp @property def hs_color(self): """Return the hue and saturation color value [float, float].""" return self._hs_color @property def is_on(self) -> bool: """Return true if light is on.""" return self._device.status.switch @property def max_mireds(self): """Return the warmest color_temp that this light supports.""" # SmartThings does not expose this attribute, instead it's # implemented within each device-type handler. This value is the # lowest kelvin found supported across 20+ handlers. return 500 # 2000K @property def min_mireds(self): """Return the coldest color_temp that this light supports.""" # SmartThings does not expose this attribute, instead it's # implemented within each device-type handler. This value is the # highest kelvin found supported across 20+ handlers. return 111 # 9000K @property def supported_features(self) -> int: """Flag supported features.""" return self._supported_features
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/smartthings/light.py
"""Support for LimitlessLED bulbs.""" import logging from limitlessled import Color from limitlessled.bridge import Bridge from limitlessled.group.dimmer import DimmerGroup from limitlessled.group.rgbw import RgbwGroup from limitlessled.group.rgbww import RgbwwGroup from limitlessled.group.white import WhiteGroup from limitlessled.pipeline import Pipeline from limitlessled.presets import COLORLOOP import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_FLASH, ATTR_HS_COLOR, ATTR_TRANSITION, EFFECT_COLORLOOP, EFFECT_WHITE, FLASH_LONG, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_FLASH, SUPPORT_TRANSITION, LightEntity, ) from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT, CONF_TYPE, STATE_ON import homeassistant.helpers.config_validation as cv from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.util.color import color_hs_to_RGB, color_temperature_mired_to_kelvin _LOGGER = logging.getLogger(__name__) CONF_BRIDGES = "bridges" CONF_GROUPS = "groups" CONF_NUMBER = "number" CONF_VERSION = "version" CONF_FADE = "fade" DEFAULT_LED_TYPE = "rgbw" DEFAULT_PORT = 5987 DEFAULT_TRANSITION = 0 DEFAULT_VERSION = 6 DEFAULT_FADE = False LED_TYPE = ["rgbw", "rgbww", "white", "bridge-led", "dimmer"] EFFECT_NIGHT = "night" MIN_SATURATION = 10 WHITE = [0, 0] SUPPORT_LIMITLESSLED_WHITE = ( SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP | SUPPORT_EFFECT | SUPPORT_TRANSITION ) SUPPORT_LIMITLESSLED_DIMMER = SUPPORT_BRIGHTNESS | SUPPORT_TRANSITION SUPPORT_LIMITLESSLED_RGB = ( SUPPORT_BRIGHTNESS | SUPPORT_EFFECT | SUPPORT_FLASH | SUPPORT_COLOR | SUPPORT_TRANSITION ) SUPPORT_LIMITLESSLED_RGBWW = ( SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP | SUPPORT_EFFECT | SUPPORT_FLASH | SUPPORT_COLOR | SUPPORT_TRANSITION ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_BRIDGES): vol.All( cv.ensure_list, [ { vol.Required(CONF_HOST): cv.string, vol.Optional( CONF_VERSION, default=DEFAULT_VERSION ): cv.positive_int, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Required(CONF_GROUPS): vol.All( cv.ensure_list, [ { vol.Required(CONF_NAME): cv.string, vol.Optional( CONF_TYPE, default=DEFAULT_LED_TYPE ): vol.In(LED_TYPE), vol.Required(CONF_NUMBER): cv.positive_int, vol.Optional( CONF_FADE, default=DEFAULT_FADE ): cv.boolean, } ], ), } ], ) } ) def rewrite_legacy(config): """Rewrite legacy configuration to new format.""" bridges = config.get(CONF_BRIDGES, [config]) new_bridges = [] for bridge_conf in bridges: groups = [] if "groups" in bridge_conf: groups = bridge_conf["groups"] else: _LOGGER.warning("Legacy configuration format detected") for i in range(1, 5): name_key = "group_%d_name" % i if name_key in bridge_conf: groups.append( { "number": i, "type": bridge_conf.get( "group_%d_type" % i, DEFAULT_LED_TYPE ), "name": bridge_conf.get(name_key), } ) new_bridges.append( { "host": bridge_conf.get(CONF_HOST), "version": bridge_conf.get(CONF_VERSION), "port": bridge_conf.get(CONF_PORT), "groups": groups, } ) return {"bridges": new_bridges} def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the LimitlessLED lights.""" # Two legacy configuration formats are supported to maintain backwards # compatibility. config = rewrite_legacy(config) # Use the expanded configuration format. lights = [] for bridge_conf in config.get(CONF_BRIDGES): bridge = Bridge( bridge_conf.get(CONF_HOST), port=bridge_conf.get(CONF_PORT, DEFAULT_PORT), version=bridge_conf.get(CONF_VERSION, DEFAULT_VERSION), ) for group_conf in bridge_conf.get(CONF_GROUPS): group = bridge.add_group( group_conf.get(CONF_NUMBER), group_conf.get(CONF_NAME), group_conf.get(CONF_TYPE, DEFAULT_LED_TYPE), ) lights.append(LimitlessLEDGroup(group, {"fade": group_conf[CONF_FADE]})) add_entities(lights) def state(new_state): """State decorator. Specify True (turn on) or False (turn off). """ def decorator(function): """Set up the decorator function.""" def wrapper(self, **kwargs): """Wrap a group state change.""" pipeline = Pipeline() transition_time = DEFAULT_TRANSITION if self._effect == EFFECT_COLORLOOP: self.group.stop() self._effect = None # Set transition time. if ATTR_TRANSITION in kwargs: transition_time = int(kwargs[ATTR_TRANSITION]) # Do group type-specific work. function(self, transition_time, pipeline, **kwargs) # Update state. self._is_on = new_state self.group.enqueue(pipeline) self.schedule_update_ha_state() return wrapper return decorator class LimitlessLEDGroup(LightEntity, RestoreEntity): """Representation of a LimitessLED group.""" def __init__(self, group, config): """Initialize a group.""" if isinstance(group, WhiteGroup): self._supported = SUPPORT_LIMITLESSLED_WHITE self._effect_list = [EFFECT_NIGHT] elif isinstance(group, DimmerGroup): self._supported = SUPPORT_LIMITLESSLED_DIMMER self._effect_list = [] elif isinstance(group, RgbwGroup): self._supported = SUPPORT_LIMITLESSLED_RGB self._effect_list = [EFFECT_COLORLOOP, EFFECT_NIGHT, EFFECT_WHITE] elif isinstance(group, RgbwwGroup): self._supported = SUPPORT_LIMITLESSLED_RGBWW self._effect_list = [EFFECT_COLORLOOP, EFFECT_NIGHT, EFFECT_WHITE] self.group = group self.config = config self._is_on = False self._brightness = None self._temperature = None self._color = None self._effect = None async def async_added_to_hass(self): """Handle entity about to be added to hass event.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if last_state: self._is_on = last_state.state == STATE_ON self._brightness = last_state.attributes.get("brightness") self._temperature = last_state.attributes.get("color_temp") self._color = last_state.attributes.get("hs_color") @property def should_poll(self): """No polling needed.""" return False @property def assumed_state(self): """Return True because unable to access real state of the entity.""" return True @property def name(self): """Return the name of the group.""" return self.group.name @property def is_on(self): """Return true if device is on.""" return self._is_on @property def brightness(self): """Return the brightness property.""" if self._effect == EFFECT_NIGHT: return 1 return self._brightness @property def min_mireds(self): """Return the coldest color_temp that this light supports.""" return 154 @property def max_mireds(self): """Return the warmest color_temp that this light supports.""" return 370 @property def color_temp(self): """Return the temperature property.""" if self.hs_color is not None: return None return self._temperature @property def hs_color(self): """Return the color property.""" if self._effect == EFFECT_NIGHT: return None if self._color is None or self._color[1] == 0: return None return self._color @property def supported_features(self): """Flag supported features.""" return self._supported @property def effect(self): """Return the current effect for this light.""" return self._effect @property def effect_list(self): """Return the list of supported effects for this light.""" return self._effect_list # pylint: disable=arguments-differ @state(False) def turn_off(self, transition_time, pipeline, **kwargs): """Turn off a group.""" if self.config[CONF_FADE]: pipeline.transition(transition_time, brightness=0.0) pipeline.off() # pylint: disable=arguments-differ @state(True) def turn_on(self, transition_time, pipeline, **kwargs): """Turn on (or adjust property of) a group.""" # The night effect does not need a turned on light if kwargs.get(ATTR_EFFECT) == EFFECT_NIGHT: if EFFECT_NIGHT in self._effect_list: pipeline.night_light() self._effect = EFFECT_NIGHT return pipeline.on() # Set up transition. args = {} if self.config[CONF_FADE] and not self.is_on and self._brightness: args["brightness"] = self.limitlessled_brightness() if ATTR_BRIGHTNESS in kwargs: self._brightness = kwargs[ATTR_BRIGHTNESS] args["brightness"] = self.limitlessled_brightness() if ATTR_HS_COLOR in kwargs and self._supported & SUPPORT_COLOR: self._color = kwargs[ATTR_HS_COLOR] # White is a special case. if self._color[1] < MIN_SATURATION: pipeline.white() self._color = WHITE else: args["color"] = self.limitlessled_color() if ATTR_COLOR_TEMP in kwargs: if self._supported & SUPPORT_COLOR: pipeline.white() self._color = WHITE if self._supported & SUPPORT_COLOR_TEMP: self._temperature = kwargs[ATTR_COLOR_TEMP] args["temperature"] = self.limitlessled_temperature() if args: pipeline.transition(transition_time, **args) # Flash. if ATTR_FLASH in kwargs and self._supported & SUPPORT_FLASH: duration = 0 if kwargs[ATTR_FLASH] == FLASH_LONG: duration = 1 pipeline.flash(duration=duration) # Add effects. if ATTR_EFFECT in kwargs and self._effect_list: if kwargs[ATTR_EFFECT] == EFFECT_COLORLOOP: self._effect = EFFECT_COLORLOOP pipeline.append(COLORLOOP) if kwargs[ATTR_EFFECT] == EFFECT_WHITE: pipeline.white() self._color = WHITE def limitlessled_temperature(self): """Convert Home Assistant color temperature units to percentage.""" max_kelvin = color_temperature_mired_to_kelvin(self.min_mireds) min_kelvin = color_temperature_mired_to_kelvin(self.max_mireds) width = max_kelvin - min_kelvin kelvin = color_temperature_mired_to_kelvin(self._temperature) temperature = (kelvin - min_kelvin) / width return max(0, min(1, temperature)) def limitlessled_brightness(self): """Convert Home Assistant brightness units to percentage.""" return self._brightness / 255 def limitlessled_color(self): """Convert Home Assistant HS list to RGB Color tuple.""" return Color(*color_hs_to_RGB(*tuple(self._color)))
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/limitlessled/light.py
"""Support for MyQ-Enabled Garage Doors.""" import logging from pymyq.const import ( DEVICE_STATE as MYQ_DEVICE_STATE, DEVICE_STATE_ONLINE as MYQ_DEVICE_STATE_ONLINE, DEVICE_TYPE_GATE as MYQ_DEVICE_TYPE_GATE, KNOWN_MODELS, MANUFACTURER, ) from pymyq.errors import MyQError from homeassistant.components.cover import ( DEVICE_CLASS_GARAGE, DEVICE_CLASS_GATE, SUPPORT_CLOSE, SUPPORT_OPEN, CoverEntity, ) from homeassistant.const import STATE_CLOSED, STATE_CLOSING, STATE_OPEN, STATE_OPENING from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN, MYQ_COORDINATOR, MYQ_GATEWAY, MYQ_TO_HASS _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up mysq covers.""" data = hass.data[DOMAIN][config_entry.entry_id] myq = data[MYQ_GATEWAY] coordinator = data[MYQ_COORDINATOR] async_add_entities( [MyQDevice(coordinator, device) for device in myq.covers.values()], True ) class MyQDevice(CoordinatorEntity, CoverEntity): """Representation of a MyQ cover.""" def __init__(self, coordinator, device): """Initialize with API object, device id.""" super().__init__(coordinator) self._device = device @property def device_class(self): """Define this cover as a garage door.""" device_type = self._device.device_type if device_type is not None and device_type == MYQ_DEVICE_TYPE_GATE: return DEVICE_CLASS_GATE return DEVICE_CLASS_GARAGE @property def name(self): """Return the name of the garage door if any.""" return self._device.name @property def available(self): """Return if the device is online.""" if not self.coordinator.last_update_success: return False # Not all devices report online so assume True if its missing return self._device.device_json[MYQ_DEVICE_STATE].get( MYQ_DEVICE_STATE_ONLINE, True ) @property def is_closed(self): """Return true if cover is closed, else False.""" return MYQ_TO_HASS.get(self._device.state) == STATE_CLOSED @property def is_closing(self): """Return if the cover is closing or not.""" return MYQ_TO_HASS.get(self._device.state) == STATE_CLOSING @property def is_open(self): """Return if the cover is opening or not.""" return MYQ_TO_HASS.get(self._device.state) == STATE_OPEN @property def is_opening(self): """Return if the cover is opening or not.""" return MYQ_TO_HASS.get(self._device.state) == STATE_OPENING @property def supported_features(self): """Flag supported features.""" return SUPPORT_OPEN | SUPPORT_CLOSE @property def unique_id(self): """Return a unique, Home Assistant friendly identifier for this entity.""" return self._device.device_id async def async_close_cover(self, **kwargs): """Issue close command to cover.""" if self.is_closing or self.is_closed: return try: wait_task = await self._device.close(wait_for_state=False) except MyQError as err: _LOGGER.error( "Closing of cover %s failed with error: %s", self._device.name, str(err) ) return # Write closing state to HASS self.async_write_ha_state() if not await wait_task: _LOGGER.error("Closing of cover %s failed", self._device.name) # Write final state to HASS self.async_write_ha_state() async def async_open_cover(self, **kwargs): """Issue open command to cover.""" if self.is_opening or self.is_open: return try: wait_task = await self._device.open(wait_for_state=False) except MyQError as err: _LOGGER.error( "Opening of cover %s failed with error: %s", self._device.name, str(err) ) return # Write opening state to HASS self.async_write_ha_state() if not await wait_task: _LOGGER.error("Opening of cover %s failed", self._device.name) # Write final state to HASS self.async_write_ha_state() @property def device_info(self): """Return the device_info of the device.""" device_info = { "identifiers": {(DOMAIN, self._device.device_id)}, "name": self._device.name, "manufacturer": MANUFACTURER, "sw_version": self._device.firmware_version, } model = KNOWN_MODELS.get(self._device.device_id[2:4]) if model: device_info["model"] = model if self._device.parent_device_id: device_info["via_device"] = (DOMAIN, self._device.parent_device_id) return device_info async def async_added_to_hass(self): """Subscribe to updates.""" self.async_on_remove( self.coordinator.async_add_listener(self.async_write_ha_state) )
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/myq/cover.py
"""Support for w800rf32 binary sensors.""" import logging import W800rf32 as w800 import voluptuous as vol from homeassistant.components.binary_sensor import ( DEVICE_CLASSES_SCHEMA, PLATFORM_SCHEMA, BinarySensorEntity, ) from homeassistant.const import CONF_DEVICE_CLASS, CONF_DEVICES, CONF_NAME from homeassistant.core import callback from homeassistant.helpers import config_validation as cv, event as evt from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.util import dt as dt_util from . import W800RF32_DEVICE _LOGGER = logging.getLogger(__name__) CONF_OFF_DELAY = "off_delay" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_DEVICES): { cv.string: vol.Schema( { vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA, vol.Optional(CONF_OFF_DELAY): vol.All( cv.time_period, cv.positive_timedelta ), } ) } }, extra=vol.ALLOW_EXTRA, ) async def async_setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Binary Sensor platform to w800rf32.""" binary_sensors = [] # device_id --> "c1 or a3" X10 device. entity (type dictionary) # --> name, device_class etc for device_id, entity in config[CONF_DEVICES].items(): _LOGGER.debug( "Add %s w800rf32.binary_sensor (class %s)", entity[CONF_NAME], entity.get(CONF_DEVICE_CLASS), ) device = W800rf32BinarySensor( device_id, entity.get(CONF_NAME), entity.get(CONF_DEVICE_CLASS), entity.get(CONF_OFF_DELAY), ) binary_sensors.append(device) add_entities(binary_sensors) class W800rf32BinarySensor(BinarySensorEntity): """A representation of a w800rf32 binary sensor.""" def __init__(self, device_id, name, device_class=None, off_delay=None): """Initialize the w800rf32 sensor.""" self._signal = W800RF32_DEVICE.format(device_id) self._name = name self._device_class = device_class self._off_delay = off_delay self._state = False self._delay_listener = None @callback def _off_delay_listener(self, now): """Switch device off after a delay.""" self._delay_listener = None self.update_state(False) @property def name(self): """Return the device name.""" return self._name @property def should_poll(self): """No polling needed.""" return False @property def device_class(self): """Return the sensor class.""" return self._device_class @property def is_on(self): """Return true if the sensor state is True.""" return self._state @callback def binary_sensor_update(self, event): """Call for control updates from the w800rf32 gateway.""" if not isinstance(event, w800.W800rf32Event): return dev_id = event.device command = event.command _LOGGER.debug( "BinarySensor update (Device ID: %s Command %s ...)", dev_id, command ) # Update the w800rf32 device state if command in ("On", "Off"): is_on = command == "On" self.update_state(is_on) if self.is_on and self._off_delay is not None and self._delay_listener is None: self._delay_listener = evt.async_track_point_in_time( self.hass, self._off_delay_listener, dt_util.utcnow() + self._off_delay ) def update_state(self, state): """Update the state of the device.""" self._state = state self.async_write_ha_state() async def async_added_to_hass(self): """Register update callback.""" async_dispatcher_connect(self.hass, self._signal, self.binary_sensor_update)
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/w800rf32/binary_sensor.py
"""Support for Freebox devices (Freebox v6 and Freebox mini 4K).""" from __future__ import annotations import logging from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import DATA_RATE_KILOBYTES_PER_SECOND from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.typing import HomeAssistantType import homeassistant.util.dt as dt_util from .const import ( CALL_SENSORS, CONNECTION_SENSORS, DISK_PARTITION_SENSORS, DOMAIN, SENSOR_DEVICE_CLASS, SENSOR_ICON, SENSOR_NAME, SENSOR_UNIT, TEMPERATURE_SENSOR_TEMPLATE, ) from .router import FreeboxRouter _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Set up the sensors.""" router = hass.data[DOMAIN][entry.unique_id] entities = [] _LOGGER.debug( "%s - %s - %s temperature sensors", router.name, router.mac, len(router.sensors_temperature), ) for sensor_name in router.sensors_temperature: entities.append( FreeboxSensor( router, sensor_name, {**TEMPERATURE_SENSOR_TEMPLATE, SENSOR_NAME: f"Freebox {sensor_name}"}, ) ) for sensor_key in CONNECTION_SENSORS: entities.append( FreeboxSensor(router, sensor_key, CONNECTION_SENSORS[sensor_key]) ) for sensor_key in CALL_SENSORS: entities.append(FreeboxCallSensor(router, sensor_key, CALL_SENSORS[sensor_key])) _LOGGER.debug("%s - %s - %s disk(s)", router.name, router.mac, len(router.disks)) for disk in router.disks.values(): for partition in disk["partitions"]: for sensor_key in DISK_PARTITION_SENSORS: entities.append( FreeboxDiskSensor( router, disk, partition, sensor_key, DISK_PARTITION_SENSORS[sensor_key], ) ) async_add_entities(entities, True) class FreeboxSensor(SensorEntity): """Representation of a Freebox sensor.""" def __init__( self, router: FreeboxRouter, sensor_type: str, sensor: dict[str, any] ) -> None: """Initialize a Freebox sensor.""" self._state = None self._router = router self._sensor_type = sensor_type self._name = sensor[SENSOR_NAME] self._unit = sensor[SENSOR_UNIT] self._icon = sensor[SENSOR_ICON] self._device_class = sensor[SENSOR_DEVICE_CLASS] self._unique_id = f"{self._router.mac} {self._name}" @callback def async_update_state(self) -> None: """Update the Freebox sensor.""" state = self._router.sensors[self._sensor_type] if self._unit == DATA_RATE_KILOBYTES_PER_SECOND: self._state = round(state / 1000, 2) else: self._state = state @property def unique_id(self) -> str: """Return a unique ID.""" return self._unique_id @property def name(self) -> str: """Return the name.""" return self._name @property def state(self) -> str: """Return the state.""" return self._state @property def unit_of_measurement(self) -> str: """Return the unit.""" return self._unit @property def icon(self) -> str: """Return the icon.""" return self._icon @property def device_class(self) -> str: """Return the device_class.""" return self._device_class @property def device_info(self) -> dict[str, any]: """Return the device information.""" return self._router.device_info @property def should_poll(self) -> bool: """No polling needed.""" return False @callback def async_on_demand_update(self): """Update state.""" self.async_update_state() self.async_write_ha_state() async def async_added_to_hass(self): """Register state update callback.""" self.async_update_state() self.async_on_remove( async_dispatcher_connect( self.hass, self._router.signal_sensor_update, self.async_on_demand_update, ) ) class FreeboxCallSensor(FreeboxSensor): """Representation of a Freebox call sensor.""" def __init__( self, router: FreeboxRouter, sensor_type: str, sensor: dict[str, any] ) -> None: """Initialize a Freebox call sensor.""" super().__init__(router, sensor_type, sensor) self._call_list_for_type = [] @callback def async_update_state(self) -> None: """Update the Freebox call sensor.""" self._call_list_for_type = [] if self._router.call_list: for call in self._router.call_list: if not call["new"]: continue if call["type"] == self._sensor_type: self._call_list_for_type.append(call) self._state = len(self._call_list_for_type) @property def extra_state_attributes(self) -> dict[str, any]: """Return device specific state attributes.""" return { dt_util.utc_from_timestamp(call["datetime"]).isoformat(): call["name"] for call in self._call_list_for_type } class FreeboxDiskSensor(FreeboxSensor): """Representation of a Freebox disk sensor.""" def __init__( self, router: FreeboxRouter, disk: dict[str, any], partition: dict[str, any], sensor_type: str, sensor: dict[str, any], ) -> None: """Initialize a Freebox disk sensor.""" super().__init__(router, sensor_type, sensor) self._disk = disk self._partition = partition self._name = f"{partition['label']} {sensor[SENSOR_NAME]}" self._unique_id = f"{self._router.mac} {sensor_type} {self._disk['id']} {self._partition['id']}" @property def device_info(self) -> dict[str, any]: """Return the device information.""" return { "identifiers": {(DOMAIN, self._disk["id"])}, "name": f"Disk {self._disk['id']}", "model": self._disk["model"], "sw_version": self._disk["firmware"], "via_device": ( DOMAIN, self._router.mac, ), } @callback def async_update_state(self) -> None: """Update the Freebox disk sensor.""" self._state = round( self._partition["free_bytes"] * 100 / self._partition["total_bytes"], 2 )
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/freebox/sensor.py
"""Support for Spider switches.""" from homeassistant.components.switch import SwitchEntity from .const import DOMAIN async def async_setup_entry(hass, config, async_add_entities): """Initialize a Spider Power Plug.""" api = hass.data[DOMAIN][config.entry_id] async_add_entities( [ SpiderPowerPlug(api, entity) for entity in await hass.async_add_executor_job(api.get_power_plugs) ] ) class SpiderPowerPlug(SwitchEntity): """Representation of a Spider Power Plug.""" def __init__(self, api, power_plug): """Initialize the Spider Power Plug.""" self.api = api self.power_plug = power_plug @property def device_info(self): """Return the device_info of the device.""" return { "identifiers": {(DOMAIN, self.power_plug.id)}, "name": self.power_plug.name, "manufacturer": self.power_plug.manufacturer, "model": self.power_plug.model, } @property def unique_id(self): """Return the ID of this switch.""" return self.power_plug.id @property def name(self): """Return the name of the switch if any.""" return self.power_plug.name @property def current_power_w(self): """Return the current power usage in W.""" return round(self.power_plug.current_energy_consumption) @property def today_energy_kwh(self): """Return the current power usage in Kwh.""" return round(self.power_plug.today_energy_consumption / 1000, 2) @property def is_on(self): """Return true if switch is on. Standby is on.""" return self.power_plug.is_on @property def available(self): """Return true if switch is available.""" return self.power_plug.is_available def turn_on(self, **kwargs): """Turn device on.""" self.power_plug.turn_on() def turn_off(self, **kwargs): """Turn device off.""" self.power_plug.turn_off() def update(self): """Get the latest data.""" self.power_plug = self.api.get_power_plug(self.unique_id)
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/spider/switch.py
"""Asuswrt status sensors.""" from __future__ import annotations import logging from numbers import Number from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import DATA_GIGABYTES, DATA_RATE_MEGABITS_PER_SECOND from homeassistant.helpers.typing import HomeAssistantType from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, ) from .const import ( DATA_ASUSWRT, DOMAIN, SENSOR_CONNECTED_DEVICE, SENSOR_RX_BYTES, SENSOR_RX_RATES, SENSOR_TX_BYTES, SENSOR_TX_RATES, ) from .router import KEY_COORDINATOR, KEY_SENSORS, AsusWrtRouter DEFAULT_PREFIX = "Asuswrt" SENSOR_DEVICE_CLASS = "device_class" SENSOR_ICON = "icon" SENSOR_NAME = "name" SENSOR_UNIT = "unit" SENSOR_FACTOR = "factor" SENSOR_DEFAULT_ENABLED = "default_enabled" UNIT_DEVICES = "Devices" CONNECTION_SENSORS = { SENSOR_CONNECTED_DEVICE: { SENSOR_NAME: "Devices Connected", SENSOR_UNIT: UNIT_DEVICES, SENSOR_FACTOR: 0, SENSOR_ICON: "mdi:router-network", SENSOR_DEVICE_CLASS: None, SENSOR_DEFAULT_ENABLED: True, }, SENSOR_RX_RATES: { SENSOR_NAME: "Download Speed", SENSOR_UNIT: DATA_RATE_MEGABITS_PER_SECOND, SENSOR_FACTOR: 125000, SENSOR_ICON: "mdi:download-network", SENSOR_DEVICE_CLASS: None, }, SENSOR_TX_RATES: { SENSOR_NAME: "Upload Speed", SENSOR_UNIT: DATA_RATE_MEGABITS_PER_SECOND, SENSOR_FACTOR: 125000, SENSOR_ICON: "mdi:upload-network", SENSOR_DEVICE_CLASS: None, }, SENSOR_RX_BYTES: { SENSOR_NAME: "Download", SENSOR_UNIT: DATA_GIGABYTES, SENSOR_FACTOR: 1000000000, SENSOR_ICON: "mdi:download", SENSOR_DEVICE_CLASS: None, }, SENSOR_TX_BYTES: { SENSOR_NAME: "Upload", SENSOR_UNIT: DATA_GIGABYTES, SENSOR_FACTOR: 1000000000, SENSOR_ICON: "mdi:upload", SENSOR_DEVICE_CLASS: None, }, } _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Set up the sensors.""" router: AsusWrtRouter = hass.data[DOMAIN][entry.entry_id][DATA_ASUSWRT] entities = [] for sensor_data in router.sensors_coordinator.values(): coordinator = sensor_data[KEY_COORDINATOR] sensors = sensor_data[KEY_SENSORS] for sensor_key in sensors: if sensor_key in CONNECTION_SENSORS: entities.append( AsusWrtSensor( coordinator, router, sensor_key, CONNECTION_SENSORS[sensor_key] ) ) async_add_entities(entities, True) class AsusWrtSensor(CoordinatorEntity, SensorEntity): """Representation of a AsusWrt sensor.""" def __init__( self, coordinator: DataUpdateCoordinator, router: AsusWrtRouter, sensor_type: str, sensor: dict[str, any], ) -> None: """Initialize a AsusWrt sensor.""" super().__init__(coordinator) self._router = router self._sensor_type = sensor_type self._name = f"{DEFAULT_PREFIX} {sensor[SENSOR_NAME]}" self._unique_id = f"{DOMAIN} {self._name}" self._unit = sensor[SENSOR_UNIT] self._factor = sensor[SENSOR_FACTOR] self._icon = sensor[SENSOR_ICON] self._device_class = sensor[SENSOR_DEVICE_CLASS] self._default_enabled = sensor.get(SENSOR_DEFAULT_ENABLED, False) @property def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" return self._default_enabled @property def state(self) -> str: """Return current state.""" state = self.coordinator.data.get(self._sensor_type) if state is None: return None if self._factor and isinstance(state, Number): return round(state / self._factor, 2) return state @property def unique_id(self) -> str: """Return a unique ID.""" return self._unique_id @property def name(self) -> str: """Return the name.""" return self._name @property def unit_of_measurement(self) -> str: """Return the unit.""" return self._unit @property def icon(self) -> str: """Return the icon.""" return self._icon @property def device_class(self) -> str: """Return the device_class.""" return self._device_class @property def extra_state_attributes(self) -> dict[str, any]: """Return the attributes.""" return {"hostname": self._router.host} @property def device_info(self) -> dict[str, any]: """Return the device information.""" return self._router.device_info
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/asuswrt/sensor.py
"""Support for exposing NX584 elements as sensors.""" import logging import threading import time from nx584 import client as nx584_client import requests import voluptuous as vol from homeassistant.components.binary_sensor import ( DEVICE_CLASS_OPENING, DEVICE_CLASSES, PLATFORM_SCHEMA, BinarySensorEntity, ) from homeassistant.const import CONF_HOST, CONF_PORT import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_EXCLUDE_ZONES = "exclude_zones" CONF_ZONE_TYPES = "zone_types" DEFAULT_HOST = "localhost" DEFAULT_PORT = "5007" DEFAULT_SSL = False ZONE_TYPES_SCHEMA = vol.Schema({cv.positive_int: vol.In(DEVICE_CLASSES)}) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_EXCLUDE_ZONES, default=[]): vol.All( cv.ensure_list, [cv.positive_int] ), vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_ZONE_TYPES, default={}): ZONE_TYPES_SCHEMA, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the NX584 binary sensor platform.""" host = config.get(CONF_HOST) port = config.get(CONF_PORT) exclude = config.get(CONF_EXCLUDE_ZONES) zone_types = config.get(CONF_ZONE_TYPES) try: client = nx584_client.Client(f"http://{host}:{port}") zones = client.list_zones() except requests.exceptions.ConnectionError as ex: _LOGGER.error("Unable to connect to NX584: %s", str(ex)) return False version = [int(v) for v in client.get_version().split(".")] if version < [1, 1]: _LOGGER.error("NX584 is too old to use for sensors (>=0.2 required)") return False zone_sensors = { zone["number"]: NX584ZoneSensor( zone, zone_types.get(zone["number"], DEVICE_CLASS_OPENING) ) for zone in zones if zone["number"] not in exclude } if zone_sensors: add_entities(zone_sensors.values()) watcher = NX584Watcher(client, zone_sensors) watcher.start() else: _LOGGER.warning("No zones found on NX584") return True class NX584ZoneSensor(BinarySensorEntity): """Representation of a NX584 zone as a sensor.""" def __init__(self, zone, zone_type): """Initialize the nx594 binary sensor.""" self._zone = zone self._zone_type = zone_type @property def device_class(self): """Return the class of this sensor, from DEVICE_CLASSES.""" return self._zone_type @property def should_poll(self): """No polling needed.""" return False @property def name(self): """Return the name of the binary sensor.""" return self._zone["name"] @property def is_on(self): """Return true if the binary sensor is on.""" # True means "faulted" or "open" or "abnormal state" return self._zone["state"] @property def extra_state_attributes(self): """Return the state attributes.""" return {"zone_number": self._zone["number"]} class NX584Watcher(threading.Thread): """Event listener thread to process NX584 events.""" def __init__(self, client, zone_sensors): """Initialize NX584 watcher thread.""" super().__init__() self.daemon = True self._client = client self._zone_sensors = zone_sensors def _process_zone_event(self, event): zone = event["zone"] zone_sensor = self._zone_sensors.get(zone) # pylint: disable=protected-access if not zone_sensor: return zone_sensor._zone["state"] = event["zone_state"] zone_sensor.schedule_update_ha_state() def _process_events(self, events): for event in events: if event.get("type") == "zone_status": self._process_zone_event(event) def _run(self): """Throw away any existing events so we don't replay history.""" self._client.get_events() while True: events = self._client.get_events() if events: self._process_events(events) def run(self): """Run the watcher.""" while True: try: self._run() except requests.exceptions.ConnectionError: _LOGGER.error("Failed to reach NX584 server") time.sleep(10)
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/nx584/binary_sensor.py
"""Representation of Z-Wave binary sensors.""" from __future__ import annotations import logging from typing import Callable, TypedDict from zwave_js_server.client import Client as ZwaveClient from zwave_js_server.const import CommandClass from homeassistant.components.binary_sensor import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_DOOR, DEVICE_CLASS_GAS, DEVICE_CLASS_HEAT, DEVICE_CLASS_LOCK, DEVICE_CLASS_MOISTURE, DEVICE_CLASS_MOTION, DEVICE_CLASS_PROBLEM, DEVICE_CLASS_SAFETY, DEVICE_CLASS_SMOKE, DEVICE_CLASS_SOUND, DOMAIN as BINARY_SENSOR_DOMAIN, BinarySensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .const import DATA_CLIENT, DATA_UNSUBSCRIBE, DOMAIN from .discovery import ZwaveDiscoveryInfo from .entity import ZWaveBaseEntity LOGGER = logging.getLogger(__name__) NOTIFICATION_SMOKE_ALARM = 1 NOTIFICATION_CARBON_MONOOXIDE = 2 NOTIFICATION_CARBON_DIOXIDE = 3 NOTIFICATION_HEAT = 4 NOTIFICATION_WATER = 5 NOTIFICATION_ACCESS_CONTROL = 6 NOTIFICATION_HOME_SECURITY = 7 NOTIFICATION_POWER_MANAGEMENT = 8 NOTIFICATION_SYSTEM = 9 NOTIFICATION_EMERGENCY = 10 NOTIFICATION_CLOCK = 11 NOTIFICATION_APPLIANCE = 12 NOTIFICATION_HOME_HEALTH = 13 NOTIFICATION_SIREN = 14 NOTIFICATION_WATER_VALVE = 15 NOTIFICATION_WEATHER = 16 NOTIFICATION_IRRIGATION = 17 NOTIFICATION_GAS = 18 class NotificationSensorMapping(TypedDict, total=False): """Represent a notification sensor mapping dict type.""" type: int # required states: list[str] device_class: str enabled: bool # Mappings for Notification sensors # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/notifications.json NOTIFICATION_SENSOR_MAPPINGS: list[NotificationSensorMapping] = [ { # NotificationType 1: Smoke Alarm - State Id's 1 and 2 - Smoke detected "type": NOTIFICATION_SMOKE_ALARM, "states": ["1", "2"], "device_class": DEVICE_CLASS_SMOKE, }, { # NotificationType 1: Smoke Alarm - All other State Id's "type": NOTIFICATION_SMOKE_ALARM, "device_class": DEVICE_CLASS_PROBLEM, }, { # NotificationType 2: Carbon Monoxide - State Id's 1 and 2 "type": NOTIFICATION_CARBON_MONOOXIDE, "states": ["1", "2"], "device_class": DEVICE_CLASS_GAS, }, { # NotificationType 2: Carbon Monoxide - All other State Id's "type": NOTIFICATION_CARBON_MONOOXIDE, "device_class": DEVICE_CLASS_PROBLEM, }, { # NotificationType 3: Carbon Dioxide - State Id's 1 and 2 "type": NOTIFICATION_CARBON_DIOXIDE, "states": ["1", "2"], "device_class": DEVICE_CLASS_GAS, }, { # NotificationType 3: Carbon Dioxide - All other State Id's "type": NOTIFICATION_CARBON_DIOXIDE, "device_class": DEVICE_CLASS_PROBLEM, }, { # NotificationType 4: Heat - State Id's 1, 2, 5, 6 (heat/underheat) "type": NOTIFICATION_HEAT, "states": ["1", "2", "5", "6"], "device_class": DEVICE_CLASS_HEAT, }, { # NotificationType 4: Heat - All other State Id's "type": NOTIFICATION_HEAT, "device_class": DEVICE_CLASS_PROBLEM, }, { # NotificationType 5: Water - State Id's 1, 2, 3, 4 "type": NOTIFICATION_WATER, "states": ["1", "2", "3", "4"], "device_class": DEVICE_CLASS_MOISTURE, }, { # NotificationType 5: Water - All other State Id's "type": NOTIFICATION_WATER, "device_class": DEVICE_CLASS_PROBLEM, }, { # NotificationType 6: Access Control - State Id's 1, 2, 3, 4 (Lock) "type": NOTIFICATION_ACCESS_CONTROL, "states": ["1", "2", "3", "4"], "device_class": DEVICE_CLASS_LOCK, }, { # NotificationType 6: Access Control - State Id 16 (door/window open) "type": NOTIFICATION_ACCESS_CONTROL, "states": ["22"], "device_class": DEVICE_CLASS_DOOR, }, { # NotificationType 6: Access Control - State Id 17 (door/window closed) "type": NOTIFICATION_ACCESS_CONTROL, "states": ["23"], "enabled": False, }, { # NotificationType 7: Home Security - State Id's 1, 2 (intrusion) "type": NOTIFICATION_HOME_SECURITY, "states": ["1", "2"], "device_class": DEVICE_CLASS_SAFETY, }, { # NotificationType 7: Home Security - State Id's 3, 4, 9 (tampering) "type": NOTIFICATION_HOME_SECURITY, "states": ["3", "4", "9"], "device_class": DEVICE_CLASS_SAFETY, }, { # NotificationType 7: Home Security - State Id's 5, 6 (glass breakage) "type": NOTIFICATION_HOME_SECURITY, "states": ["5", "6"], "device_class": DEVICE_CLASS_SAFETY, }, { # NotificationType 7: Home Security - State Id's 7, 8 (motion) "type": NOTIFICATION_HOME_SECURITY, "states": ["7", "8"], "device_class": DEVICE_CLASS_MOTION, }, { # NotificationType 9: System - State Id's 1, 2, 6, 7 "type": NOTIFICATION_SYSTEM, "states": ["1", "2", "6", "7"], "device_class": DEVICE_CLASS_PROBLEM, }, { # NotificationType 10: Emergency - State Id's 1, 2, 3 "type": NOTIFICATION_EMERGENCY, "states": ["1", "2", "3"], "device_class": DEVICE_CLASS_PROBLEM, }, { # NotificationType 14: Siren "type": NOTIFICATION_SIREN, "states": ["1"], "device_class": DEVICE_CLASS_SOUND, }, { # NotificationType 18: Gas "type": NOTIFICATION_GAS, "states": ["1", "2", "3", "4"], "device_class": DEVICE_CLASS_GAS, }, { # NotificationType 18: Gas "type": NOTIFICATION_GAS, "states": ["6"], "device_class": DEVICE_CLASS_PROBLEM, }, ] PROPERTY_DOOR_STATUS = "doorStatus" class PropertySensorMapping(TypedDict, total=False): """Represent a property sensor mapping dict type.""" property_name: str # required on_states: list[str] # required device_class: str enabled: bool # Mappings for property sensors PROPERTY_SENSOR_MAPPINGS: list[PropertySensorMapping] = [ { "property_name": PROPERTY_DOOR_STATUS, "on_states": ["open"], "device_class": DEVICE_CLASS_DOOR, "enabled": True, }, ] async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: Callable ) -> None: """Set up Z-Wave binary sensor from config entry.""" client: ZwaveClient = hass.data[DOMAIN][config_entry.entry_id][DATA_CLIENT] @callback def async_add_binary_sensor(info: ZwaveDiscoveryInfo) -> None: """Add Z-Wave Binary Sensor.""" entities: list[BinarySensorEntity] = [] if info.platform_hint == "notification": # Get all sensors from Notification CC states for state_key in info.primary_value.metadata.states: # ignore idle key (0) if state_key == "0": continue entities.append( ZWaveNotificationBinarySensor(config_entry, client, info, state_key) ) elif info.platform_hint == "property": entities.append(ZWavePropertyBinarySensor(config_entry, client, info)) else: # boolean sensor entities.append(ZWaveBooleanBinarySensor(config_entry, client, info)) async_add_entities(entities) hass.data[DOMAIN][config_entry.entry_id][DATA_UNSUBSCRIBE].append( async_dispatcher_connect( hass, f"{DOMAIN}_{config_entry.entry_id}_add_{BINARY_SENSOR_DOMAIN}", async_add_binary_sensor, ) ) class ZWaveBooleanBinarySensor(ZWaveBaseEntity, BinarySensorEntity): """Representation of a Z-Wave binary_sensor.""" def __init__( self, config_entry: ConfigEntry, client: ZwaveClient, info: ZwaveDiscoveryInfo, ) -> None: """Initialize a ZWaveBooleanBinarySensor entity.""" super().__init__(config_entry, client, info) self._name = self.generate_name(include_value_name=True) @property def is_on(self) -> bool | None: """Return if the sensor is on or off.""" if self.info.primary_value.value is None: return None return bool(self.info.primary_value.value) @property def device_class(self) -> str | None: """Return device class.""" if self.info.primary_value.command_class == CommandClass.BATTERY: return DEVICE_CLASS_BATTERY return None @property def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" # Legacy binary sensors are phased out (replaced by notification sensors) # Disable by default to not confuse users return bool( self.info.primary_value.command_class != CommandClass.SENSOR_BINARY or self.info.node.device_class.generic.key == 0x20 ) class ZWaveNotificationBinarySensor(ZWaveBaseEntity, BinarySensorEntity): """Representation of a Z-Wave binary_sensor from Notification CommandClass.""" def __init__( self, config_entry: ConfigEntry, client: ZwaveClient, info: ZwaveDiscoveryInfo, state_key: str, ) -> None: """Initialize a ZWaveNotificationBinarySensor entity.""" super().__init__(config_entry, client, info) self.state_key = state_key self._name = self.generate_name( include_value_name=True, alternate_value_name=self.info.primary_value.property_name, additional_info=[self.info.primary_value.metadata.states[self.state_key]], ) # check if we have a custom mapping for this value self._mapping_info = self._get_sensor_mapping() @property def is_on(self) -> bool | None: """Return if the sensor is on or off.""" if self.info.primary_value.value is None: return None return int(self.info.primary_value.value) == int(self.state_key) @property def device_class(self) -> str | None: """Return device class.""" return self._mapping_info.get("device_class") @property def unique_id(self) -> str: """Return unique id for this entity.""" return f"{super().unique_id}.{self.state_key}" @property def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" if not self._mapping_info: return True return self._mapping_info.get("enabled", True) @callback def _get_sensor_mapping(self) -> NotificationSensorMapping: """Try to get a device specific mapping for this sensor.""" for mapping in NOTIFICATION_SENSOR_MAPPINGS: if ( mapping["type"] != self.info.primary_value.metadata.cc_specific["notificationType"] ): continue if not mapping.get("states") or self.state_key in mapping["states"]: # match found return mapping return {} class ZWavePropertyBinarySensor(ZWaveBaseEntity, BinarySensorEntity): """Representation of a Z-Wave binary_sensor from a property.""" def __init__( self, config_entry: ConfigEntry, client: ZwaveClient, info: ZwaveDiscoveryInfo ) -> None: """Initialize a ZWavePropertyBinarySensor entity.""" super().__init__(config_entry, client, info) # check if we have a custom mapping for this value self._mapping_info = self._get_sensor_mapping() self._name = self.generate_name(include_value_name=True) @property def is_on(self) -> bool | None: """Return if the sensor is on or off.""" if self.info.primary_value.value is None: return None return self.info.primary_value.value in self._mapping_info["on_states"] @property def device_class(self) -> str | None: """Return device class.""" return self._mapping_info.get("device_class") @property def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" # We hide some more advanced sensors by default to not overwhelm users # unless explicitly stated in a mapping, assume deisabled by default return self._mapping_info.get("enabled", False) @callback def _get_sensor_mapping(self) -> PropertySensorMapping: """Try to get a device specific mapping for this sensor.""" mapping_info = PropertySensorMapping() for mapping in PROPERTY_SENSOR_MAPPINGS: if mapping["property_name"] == self.info.primary_value.property_name: mapping_info = mapping.copy() break return mapping_info
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/zwave_js/binary_sensor.py
"""Support for Ness D8X/D16X devices.""" from collections import namedtuple import datetime from nessclient import ArmingState, Client import voluptuous as vol from homeassistant.components.binary_sensor import DEVICE_CLASSES from homeassistant.const import ( ATTR_CODE, ATTR_STATE, CONF_HOST, CONF_SCAN_INTERVAL, EVENT_HOMEASSISTANT_STOP, ) from homeassistant.helpers import config_validation as cv from homeassistant.helpers.discovery import async_load_platform from homeassistant.helpers.dispatcher import async_dispatcher_send DOMAIN = "ness_alarm" DATA_NESS = "ness_alarm" CONF_DEVICE_PORT = "port" CONF_INFER_ARMING_STATE = "infer_arming_state" CONF_ZONES = "zones" CONF_ZONE_NAME = "name" CONF_ZONE_TYPE = "type" CONF_ZONE_ID = "id" ATTR_OUTPUT_ID = "output_id" DEFAULT_ZONES = [] DEFAULT_SCAN_INTERVAL = datetime.timedelta(minutes=1) DEFAULT_INFER_ARMING_STATE = False SIGNAL_ZONE_CHANGED = "ness_alarm.zone_changed" SIGNAL_ARMING_STATE_CHANGED = "ness_alarm.arming_state_changed" ZoneChangedData = namedtuple("ZoneChangedData", ["zone_id", "state"]) DEFAULT_ZONE_TYPE = "motion" ZONE_SCHEMA = vol.Schema( { vol.Required(CONF_ZONE_NAME): cv.string, vol.Required(CONF_ZONE_ID): cv.positive_int, vol.Optional(CONF_ZONE_TYPE, default=DEFAULT_ZONE_TYPE): vol.In(DEVICE_CLASSES), } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_DEVICE_PORT): cv.port, vol.Optional( CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL ): cv.positive_time_period, vol.Optional(CONF_ZONES, default=DEFAULT_ZONES): vol.All( cv.ensure_list, [ZONE_SCHEMA] ), vol.Optional( CONF_INFER_ARMING_STATE, default=DEFAULT_INFER_ARMING_STATE ): cv.boolean, } ) }, extra=vol.ALLOW_EXTRA, ) SERVICE_PANIC = "panic" SERVICE_AUX = "aux" SERVICE_SCHEMA_PANIC = vol.Schema({vol.Required(ATTR_CODE): cv.string}) SERVICE_SCHEMA_AUX = vol.Schema( { vol.Required(ATTR_OUTPUT_ID): cv.positive_int, vol.Optional(ATTR_STATE, default=True): cv.boolean, } ) async def async_setup(hass, config): """Set up the Ness Alarm platform.""" conf = config[DOMAIN] zones = conf[CONF_ZONES] host = conf[CONF_HOST] port = conf[CONF_DEVICE_PORT] scan_interval = conf[CONF_SCAN_INTERVAL] infer_arming_state = conf[CONF_INFER_ARMING_STATE] client = Client( host=host, port=port, loop=hass.loop, update_interval=scan_interval.total_seconds(), infer_arming_state=infer_arming_state, ) hass.data[DATA_NESS] = client async def _close(event): await client.close() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _close) hass.async_create_task( async_load_platform(hass, "binary_sensor", DOMAIN, {CONF_ZONES: zones}, config) ) hass.async_create_task( async_load_platform(hass, "alarm_control_panel", DOMAIN, {}, config) ) def on_zone_change(zone_id: int, state: bool): """Receives and propagates zone state updates.""" async_dispatcher_send( hass, SIGNAL_ZONE_CHANGED, ZoneChangedData(zone_id=zone_id, state=state) ) def on_state_change(arming_state: ArmingState): """Receives and propagates arming state updates.""" async_dispatcher_send(hass, SIGNAL_ARMING_STATE_CHANGED, arming_state) client.on_zone_change(on_zone_change) client.on_state_change(on_state_change) # Force update for current arming status and current zone states hass.loop.create_task(client.keepalive()) hass.loop.create_task(client.update()) async def handle_panic(call): await client.panic(call.data[ATTR_CODE]) async def handle_aux(call): await client.aux(call.data[ATTR_OUTPUT_ID], call.data[ATTR_STATE]) hass.services.async_register( DOMAIN, SERVICE_PANIC, handle_panic, schema=SERVICE_SCHEMA_PANIC ) hass.services.async_register( DOMAIN, SERVICE_AUX, handle_aux, schema=SERVICE_SCHEMA_AUX ) return True
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/ness_alarm/__init__.py
"""Sonos specific exceptions.""" from homeassistant.components.media_player.errors import BrowseError class UnknownMediaType(BrowseError): """Unknown media type."""
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/sonos/exception.py
"""Closures channels module for Zigbee Home Automation.""" import zigpy.zcl.clusters.closures as closures from homeassistant.core import callback from .. import registries from ..const import REPORT_CONFIG_IMMEDIATE, SIGNAL_ATTR_UPDATED from .base import ClientChannel, ZigbeeChannel @registries.ZIGBEE_CHANNEL_REGISTRY.register(closures.DoorLock.cluster_id) class DoorLockChannel(ZigbeeChannel): """Door lock channel.""" _value_attribute = 0 REPORT_CONFIG = ({"attr": "lock_state", "config": REPORT_CONFIG_IMMEDIATE},) async def async_update(self): """Retrieve latest state.""" result = await self.get_attribute_value("lock_state", from_cache=True) if result is not None: self.async_send_signal( f"{self.unique_id}_{SIGNAL_ATTR_UPDATED}", 0, "lock_state", result ) @callback def cluster_command(self, tsn, command_id, args): """Handle a cluster command received on this cluster.""" if ( self._cluster.client_commands is None or self._cluster.client_commands.get(command_id) is None ): return command_name = self._cluster.client_commands.get(command_id, [command_id])[0] if command_name == "operation_event_notification": self.zha_send_event( command_name, { "source": args[0].name, "operation": args[1].name, "code_slot": (args[2] + 1), # start code slots at 1 }, ) @callback def attribute_updated(self, attrid, value): """Handle attribute update from lock cluster.""" attr_name = self.cluster.attributes.get(attrid, [attrid])[0] self.debug( "Attribute report '%s'[%s] = %s", self.cluster.name, attr_name, value ) if attrid == self._value_attribute: self.async_send_signal( f"{self.unique_id}_{SIGNAL_ATTR_UPDATED}", attrid, attr_name, value ) async def async_set_user_code(self, code_slot: int, user_code: str) -> None: """Set the user code for the code slot.""" await self.set_pin_code( code_slot - 1, # start code slots at 1, Zigbee internals use 0 closures.DoorLock.UserStatus.Enabled, closures.DoorLock.UserType.Unrestricted, user_code, ) async def async_enable_user_code(self, code_slot: int) -> None: """Enable the code slot.""" await self.set_user_status(code_slot - 1, closures.DoorLock.UserStatus.Enabled) async def async_disable_user_code(self, code_slot: int) -> None: """Disable the code slot.""" await self.set_user_status(code_slot - 1, closures.DoorLock.UserStatus.Disabled) async def async_get_user_code(self, code_slot: int) -> int: """Get the user code from the code slot.""" result = await self.get_pin_code(code_slot - 1) return result async def async_clear_user_code(self, code_slot: int) -> None: """Clear the code slot.""" await self.clear_pin_code(code_slot - 1) async def async_clear_all_user_codes(self) -> None: """Clear all code slots.""" await self.clear_all_pin_codes() async def async_set_user_type(self, code_slot: int, user_type: str) -> None: """Set user type.""" await self.set_user_type(code_slot - 1, user_type) async def async_get_user_type(self, code_slot: int) -> str: """Get user type.""" result = await self.get_user_type(code_slot - 1) return result @registries.ZIGBEE_CHANNEL_REGISTRY.register(closures.Shade.cluster_id) class Shade(ZigbeeChannel): """Shade channel.""" @registries.CLIENT_CHANNELS_REGISTRY.register(closures.WindowCovering.cluster_id) class WindowCoveringClient(ClientChannel): """Window client channel.""" @registries.ZIGBEE_CHANNEL_REGISTRY.register(closures.WindowCovering.cluster_id) class WindowCovering(ZigbeeChannel): """Window channel.""" _value_attribute = 8 REPORT_CONFIG = ( {"attr": "current_position_lift_percentage", "config": REPORT_CONFIG_IMMEDIATE}, ) async def async_update(self): """Retrieve latest state.""" result = await self.get_attribute_value( "current_position_lift_percentage", from_cache=False ) self.debug("read current position: %s", result) if result is not None: self.async_send_signal( f"{self.unique_id}_{SIGNAL_ATTR_UPDATED}", 8, "current_position_lift_percentage", result, ) @callback def attribute_updated(self, attrid, value): """Handle attribute update from window_covering cluster.""" attr_name = self.cluster.attributes.get(attrid, [attrid])[0] self.debug( "Attribute report '%s'[%s] = %s", self.cluster.name, attr_name, value ) if attrid == self._value_attribute: self.async_send_signal( f"{self.unique_id}_{SIGNAL_ATTR_UPDATED}", attrid, attr_name, value )
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/zha/core/channels/closures.py
"""Get ride details and liveboard details for NMBS (Belgian railway).""" import logging from pyrail import iRail import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ( ATTR_ATTRIBUTION, ATTR_LATITUDE, ATTR_LONGITUDE, CONF_NAME, CONF_SHOW_ON_MAP, TIME_MINUTES, ) import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "NMBS" DEFAULT_ICON = "mdi:train" DEFAULT_ICON_ALERT = "mdi:alert-octagon" CONF_STATION_FROM = "station_from" CONF_STATION_TO = "station_to" CONF_STATION_LIVE = "station_live" CONF_EXCLUDE_VIAS = "exclude_vias" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_STATION_FROM): cv.string, vol.Required(CONF_STATION_TO): cv.string, vol.Optional(CONF_STATION_LIVE): cv.string, vol.Optional(CONF_EXCLUDE_VIAS, default=False): cv.boolean, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_SHOW_ON_MAP, default=False): cv.boolean, } ) def get_time_until(departure_time=None): """Calculate the time between now and a train's departure time.""" if departure_time is None: return 0 delta = dt_util.utc_from_timestamp(int(departure_time)) - dt_util.now() return round(delta.total_seconds() / 60) def get_delay_in_minutes(delay=0): """Get the delay in minutes from a delay in seconds.""" return round(int(delay) / 60) def get_ride_duration(departure_time, arrival_time, delay=0): """Calculate the total travel time in minutes.""" duration = dt_util.utc_from_timestamp( int(arrival_time) ) - dt_util.utc_from_timestamp(int(departure_time)) duration_time = int(round(duration.total_seconds() / 60)) return duration_time + get_delay_in_minutes(delay) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the NMBS sensor with iRail API.""" api_client = iRail() name = config[CONF_NAME] show_on_map = config[CONF_SHOW_ON_MAP] station_from = config[CONF_STATION_FROM] station_to = config[CONF_STATION_TO] station_live = config.get(CONF_STATION_LIVE) excl_vias = config[CONF_EXCLUDE_VIAS] sensors = [ NMBSSensor(api_client, name, show_on_map, station_from, station_to, excl_vias) ] if station_live is not None: sensors.append( NMBSLiveBoard(api_client, station_live, station_from, station_to) ) add_entities(sensors, True) class NMBSLiveBoard(SensorEntity): """Get the next train from a station's liveboard.""" def __init__(self, api_client, live_station, station_from, station_to): """Initialize the sensor for getting liveboard data.""" self._station = live_station self._api_client = api_client self._station_from = station_from self._station_to = station_to self._attrs = {} self._state = None @property def name(self): """Return the sensor default name.""" return f"NMBS Live ({self._station})" @property def unique_id(self): """Return a unique ID.""" unique_id = f"{self._station}_{self._station_from}_{self._station_to}" return f"nmbs_live_{unique_id}" @property def icon(self): """Return the default icon or an alert icon if delays.""" if self._attrs and int(self._attrs["delay"]) > 0: return DEFAULT_ICON_ALERT return DEFAULT_ICON @property def state(self): """Return sensor state.""" return self._state @property def extra_state_attributes(self): """Return the sensor attributes if data is available.""" if self._state is None or not self._attrs: return None delay = get_delay_in_minutes(self._attrs["delay"]) departure = get_time_until(self._attrs["time"]) attrs = { "departure": f"In {departure} minutes", "departure_minutes": departure, "extra_train": int(self._attrs["isExtra"]) > 0, "vehicle_id": self._attrs["vehicle"], "monitored_station": self._station, ATTR_ATTRIBUTION: "https://api.irail.be/", } if delay > 0: attrs["delay"] = f"{delay} minutes" attrs["delay_minutes"] = delay return attrs def update(self): """Set the state equal to the next departure.""" liveboard = self._api_client.get_liveboard(self._station) if liveboard is None or not liveboard["departures"]: return next_departure = liveboard["departures"]["departure"][0] self._attrs = next_departure self._state = ( f"Track {next_departure['platform']} - {next_departure['station']}" ) class NMBSSensor(SensorEntity): """Get the the total travel time for a given connection.""" def __init__( self, api_client, name, show_on_map, station_from, station_to, excl_vias ): """Initialize the NMBS connection sensor.""" self._name = name self._show_on_map = show_on_map self._api_client = api_client self._station_from = station_from self._station_to = station_to self._excl_vias = excl_vias self._attrs = {} self._state = None @property def name(self): """Return the name of the sensor.""" return self._name @property def unit_of_measurement(self): """Return the unit of measurement.""" return TIME_MINUTES @property def icon(self): """Return the sensor default icon or an alert icon if any delay.""" if self._attrs: delay = get_delay_in_minutes(self._attrs["departure"]["delay"]) if delay > 0: return "mdi:alert-octagon" return "mdi:train" @property def extra_state_attributes(self): """Return sensor attributes if data is available.""" if self._state is None or not self._attrs: return None delay = get_delay_in_minutes(self._attrs["departure"]["delay"]) departure = get_time_until(self._attrs["departure"]["time"]) attrs = { "departure": f"In {departure} minutes", "departure_minutes": departure, "destination": self._station_to, "direction": self._attrs["departure"]["direction"]["name"], "platform_arriving": self._attrs["arrival"]["platform"], "platform_departing": self._attrs["departure"]["platform"], "vehicle_id": self._attrs["departure"]["vehicle"], ATTR_ATTRIBUTION: "https://api.irail.be/", } if self._show_on_map and self.station_coordinates: attrs[ATTR_LATITUDE] = self.station_coordinates[0] attrs[ATTR_LONGITUDE] = self.station_coordinates[1] if self.is_via_connection and not self._excl_vias: via = self._attrs["vias"]["via"][0] attrs["via"] = via["station"] attrs["via_arrival_platform"] = via["arrival"]["platform"] attrs["via_transfer_platform"] = via["departure"]["platform"] attrs["via_transfer_time"] = get_delay_in_minutes( via["timeBetween"] ) + get_delay_in_minutes(via["departure"]["delay"]) if delay > 0: attrs["delay"] = f"{delay} minutes" attrs["delay_minutes"] = delay return attrs @property def state(self): """Return the state of the device.""" return self._state @property def station_coordinates(self): """Get the lat, long coordinates for station.""" if self._state is None or not self._attrs: return [] latitude = float(self._attrs["departure"]["stationinfo"]["locationY"]) longitude = float(self._attrs["departure"]["stationinfo"]["locationX"]) return [latitude, longitude] @property def is_via_connection(self): """Return whether the connection goes through another station.""" if not self._attrs: return False return "vias" in self._attrs and int(self._attrs["vias"]["number"]) > 0 def update(self): """Set the state to the duration of a connection.""" connections = self._api_client.get_connections( self._station_from, self._station_to ) if connections is None or not connections["connection"]: return if int(connections["connection"][0]["departure"]["left"]) > 0: next_connection = connections["connection"][1] else: next_connection = connections["connection"][0] self._attrs = next_connection if self._excl_vias and self.is_via_connection: _LOGGER.debug( "Skipping update of NMBSSensor \ because this connection is a via" ) return duration = get_ride_duration( next_connection["departure"]["time"], next_connection["arrival"]["time"], next_connection["departure"]["delay"], ) self._state = duration
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/nmbs/sensor.py
"""Support for Netgear Arlo IP cameras.""" import logging from haffmpeg.camera import CameraMjpeg import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_BATTERY_LEVEL from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_connect from . import DATA_ARLO, DEFAULT_BRAND, SIGNAL_UPDATE_ARLO _LOGGER = logging.getLogger(__name__) ARLO_MODE_ARMED = "armed" ARLO_MODE_DISARMED = "disarmed" ATTR_BRIGHTNESS = "brightness" ATTR_FLIPPED = "flipped" ATTR_MIRRORED = "mirrored" ATTR_MOTION = "motion_detection_sensitivity" ATTR_POWERSAVE = "power_save_mode" ATTR_SIGNAL_STRENGTH = "signal_strength" ATTR_UNSEEN_VIDEOS = "unseen_videos" ATTR_LAST_REFRESH = "last_refresh" CONF_FFMPEG_ARGUMENTS = "ffmpeg_arguments" DEFAULT_ARGUMENTS = "-pred 1" POWERSAVE_MODE_MAPPING = {1: "best_battery_life", 2: "optimized", 3: "best_video"} PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Optional(CONF_FFMPEG_ARGUMENTS, default=DEFAULT_ARGUMENTS): cv.string} ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up an Arlo IP Camera.""" arlo = hass.data[DATA_ARLO] cameras = [] for camera in arlo.cameras: cameras.append(ArloCam(hass, camera, config)) add_entities(cameras) class ArloCam(Camera): """An implementation of a Netgear Arlo IP camera.""" def __init__(self, hass, camera, device_info): """Initialize an Arlo camera.""" super().__init__() self._camera = camera self._name = self._camera.name self._motion_status = False self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_refresh = None self.attrs = {} def camera_image(self): """Return a still image response from the camera.""" return self._camera.last_image_from_cache async def async_added_to_hass(self): """Register callbacks.""" self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_UPDATE_ARLO, self.async_write_ha_state ) ) async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" video = await self.hass.async_add_executor_job( getattr, self._camera, "last_video" ) if not video: error_msg = ( f"Video not found for {self.name}. " f"Is it older than {self._camera.min_days_vdo_cache} days?" ) _LOGGER.error(error_msg) return stream = CameraMjpeg(self._ffmpeg.binary) await stream.open_camera(video.video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type, ) finally: await stream.close() @property def name(self): """Return the name of this camera.""" return self._name @property def extra_state_attributes(self): """Return the state attributes.""" return { name: value for name, value in ( (ATTR_BATTERY_LEVEL, self._camera.battery_level), (ATTR_BRIGHTNESS, self._camera.brightness), (ATTR_FLIPPED, self._camera.flip_state), (ATTR_MIRRORED, self._camera.mirror_state), (ATTR_MOTION, self._camera.motion_detection_sensitivity), ( ATTR_POWERSAVE, POWERSAVE_MODE_MAPPING.get(self._camera.powersave_mode), ), (ATTR_SIGNAL_STRENGTH, self._camera.signal_strength), (ATTR_UNSEEN_VIDEOS, self._camera.unseen_videos), ) if value is not None } @property def model(self): """Return the camera model.""" return self._camera.model_id @property def brand(self): """Return the camera brand.""" return DEFAULT_BRAND @property def motion_detection_enabled(self): """Return the camera motion detection status.""" return self._motion_status def set_base_station_mode(self, mode): """Set the mode in the base station.""" # Get the list of base stations identified by library base_stations = self.hass.data[DATA_ARLO].base_stations # Some Arlo cameras does not have base station # So check if there is base station detected first # if yes, then choose the primary base station # Set the mode on the chosen base station if base_stations: primary_base_station = base_stations[0] primary_base_station.mode = mode def enable_motion_detection(self): """Enable the Motion detection in base station (Arm).""" self._motion_status = True self.set_base_station_mode(ARLO_MODE_ARMED) def disable_motion_detection(self): """Disable the motion detection in base station (Disarm).""" self._motion_status = False self.set_base_station_mode(ARLO_MODE_DISARMED)
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/arlo/camera.py
"""Support for Z-Wave fans.""" import math from homeassistant.components.fan import ( DOMAIN as FAN_DOMAIN, SUPPORT_SET_SPEED, FanEntity, ) from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.util.percentage import ( int_states_in_range, percentage_to_ranged_value, ranged_value_to_percentage, ) from .const import DATA_UNSUBSCRIBE, DOMAIN from .entity import ZWaveDeviceEntity SUPPORTED_FEATURES = SUPPORT_SET_SPEED SPEED_RANGE = (1, 99) # off is not included async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Z-Wave Fan from Config Entry.""" @callback def async_add_fan(values): """Add Z-Wave Fan.""" fan = ZwaveFan(values) async_add_entities([fan]) hass.data[DOMAIN][config_entry.entry_id][DATA_UNSUBSCRIBE].append( async_dispatcher_connect(hass, f"{DOMAIN}_new_{FAN_DOMAIN}", async_add_fan) ) class ZwaveFan(ZWaveDeviceEntity, FanEntity): """Representation of a Z-Wave fan.""" async def async_set_percentage(self, percentage): """Set the speed percentage of the fan.""" if percentage is None: # Value 255 tells device to return to previous value zwave_speed = 255 elif percentage == 0: zwave_speed = 0 else: zwave_speed = math.ceil(percentage_to_ranged_value(SPEED_RANGE, percentage)) self.values.primary.send_value(zwave_speed) async def async_turn_on( self, speed=None, percentage=None, preset_mode=None, **kwargs ): """Turn the device on.""" await self.async_set_percentage(percentage) async def async_turn_off(self, **kwargs): """Turn the device off.""" self.values.primary.send_value(0) @property def is_on(self): """Return true if device is on (speed above 0).""" return self.values.primary.value > 0 @property def percentage(self): """Return the current speed. The Z-Wave speed value is a byte 0-255. 255 means previous value. The normal range of the speed is 0-99. 0 means off. """ return ranged_value_to_percentage(SPEED_RANGE, self.values.primary.value) @property def speed_count(self) -> int: """Return the number of speeds the fan supports.""" return int_states_in_range(SPEED_RANGE) @property def supported_features(self): """Flag supported features.""" return SUPPORTED_FEATURES
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/ozw/fan.py
"""Config flow for Ring integration.""" import logging from oauthlib.oauth2 import AccessDeniedError, MissingTokenError from ring_doorbell import Auth import voluptuous as vol from homeassistant import config_entries, const, core, exceptions from . import DOMAIN _LOGGER = logging.getLogger(__name__) async def validate_input(hass: core.HomeAssistant, data): """Validate the user input allows us to connect.""" auth = Auth(f"HomeAssistant/{const.__version__}") try: token = await hass.async_add_executor_job( auth.fetch_token, data["username"], data["password"], data.get("2fa"), ) except MissingTokenError as err: raise Require2FA from err except AccessDeniedError as err: raise InvalidAuth from err return token class RingConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for Ring.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL user_pass = None async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: try: token = await validate_input(self.hass, user_input) await self.async_set_unique_id(user_input["username"]) return self.async_create_entry( title=user_input["username"], data={"username": user_input["username"], "token": token}, ) except Require2FA: self.user_pass = user_input return await self.async_step_2fa() except InvalidAuth: errors["base"] = "invalid_auth" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" return self.async_show_form( step_id="user", data_schema=vol.Schema({"username": str, "password": str}), errors=errors, ) async def async_step_2fa(self, user_input=None): """Handle 2fa step.""" if user_input: return await self.async_step_user({**self.user_pass, **user_input}) return self.async_show_form( step_id="2fa", data_schema=vol.Schema({"2fa": str}), ) class Require2FA(exceptions.HomeAssistantError): """Error to indicate we require 2FA.""" class InvalidAuth(exceptions.HomeAssistantError): """Error to indicate there is invalid auth."""
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/ring/config_flow.py
"""Describe logbook events.""" from homeassistant.components.logbook import LazyEventPartialState from homeassistant.const import ATTR_ENTITY_ID, ATTR_NAME from homeassistant.core import HomeAssistant, callback from . import ATTR_SOURCE, DOMAIN, EVENT_AUTOMATION_TRIGGERED @callback def async_describe_events(hass: HomeAssistant, async_describe_event): # type: ignore """Describe logbook events.""" @callback def async_describe_logbook_event(event: LazyEventPartialState): # type: ignore """Describe a logbook event.""" data = event.data message = "has been triggered" if ATTR_SOURCE in data: message = f"{message} by {data[ATTR_SOURCE]}" return { "name": data.get(ATTR_NAME), "message": message, "source": data.get(ATTR_SOURCE), "entity_id": data.get(ATTR_ENTITY_ID), "context_id": event.context_id, } async_describe_event( DOMAIN, EVENT_AUTOMATION_TRIGGERED, async_describe_logbook_event )
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/automation/logbook.py
"""Interface implementation for cloud client.""" from __future__ import annotations import asyncio import logging from pathlib import Path from typing import Any import aiohttp from hass_nabucasa.client import CloudClient as Interface from homeassistant.components.alexa import ( errors as alexa_errors, smart_home as alexa_sh, ) from homeassistant.components.google_assistant import const as gc, smart_home as ga from homeassistant.const import HTTP_OK from homeassistant.core import Context, HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.event import async_call_later from homeassistant.util.aiohttp import MockRequest from . import alexa_config, google_config, utils from .const import DISPATCHER_REMOTE_UPDATE, DOMAIN from .prefs import CloudPreferences class CloudClient(Interface): """Interface class for Home Assistant Cloud.""" def __init__( self, hass: HomeAssistant, prefs: CloudPreferences, websession: aiohttp.ClientSession, alexa_user_config: dict[str, Any], google_user_config: dict[str, Any], ): """Initialize client interface to Cloud.""" self._hass = hass self._prefs = prefs self._websession = websession self.google_user_config = google_user_config self.alexa_user_config = alexa_user_config self._alexa_config = None self._google_config = None @property def base_path(self) -> Path: """Return path to base dir.""" return Path(self._hass.config.config_dir) @property def prefs(self) -> CloudPreferences: """Return Cloud preferences.""" return self._prefs @property def loop(self) -> asyncio.BaseEventLoop: """Return client loop.""" return self._hass.loop @property def websession(self) -> aiohttp.ClientSession: """Return client session for aiohttp.""" return self._websession @property def aiohttp_runner(self) -> aiohttp.web.AppRunner: """Return client webinterface aiohttp application.""" return self._hass.http.runner @property def cloudhooks(self) -> dict[str, dict[str, str]]: """Return list of cloudhooks.""" return self._prefs.cloudhooks @property def remote_autostart(self) -> bool: """Return true if we want start a remote connection.""" return self._prefs.remote_enabled async def get_alexa_config(self) -> alexa_config.AlexaConfig: """Return Alexa config.""" if self._alexa_config is None: assert self.cloud is not None cloud_user = await self._prefs.get_cloud_user() self._alexa_config = alexa_config.AlexaConfig( self._hass, self.alexa_user_config, cloud_user, self._prefs, self.cloud ) return self._alexa_config async def get_google_config(self) -> google_config.CloudGoogleConfig: """Return Google config.""" if not self._google_config: assert self.cloud is not None cloud_user = await self._prefs.get_cloud_user() self._google_config = google_config.CloudGoogleConfig( self._hass, self.google_user_config, cloud_user, self._prefs, self.cloud ) await self._google_config.async_initialize() return self._google_config async def logged_in(self) -> None: """When user logs in.""" is_new_user = await self.prefs.async_set_username(self.cloud.username) async def enable_alexa(_): """Enable Alexa.""" aconf = await self.get_alexa_config() try: await aconf.async_enable_proactive_mode() except aiohttp.ClientError as err: # If no internet available yet if self._hass.is_running: logging.getLogger(__package__).warning( "Unable to activate Alexa Report State: %s. Retrying in 30 seconds", err, ) async_call_later(self._hass, 30, enable_alexa) except alexa_errors.NoTokenAvailable: pass async def enable_google(_): """Enable Google.""" gconf = await self.get_google_config() gconf.async_enable_local_sdk() if gconf.should_report_state: gconf.async_enable_report_state() if is_new_user: await gconf.async_sync_entities(gconf.agent_user_id) tasks = [] if self._prefs.alexa_enabled and self._prefs.alexa_report_state: tasks.append(enable_alexa) if self._prefs.google_enabled: tasks.append(enable_google) if tasks: await asyncio.gather(*[task(None) for task in tasks]) async def cleanups(self) -> None: """Cleanup some stuff after logout.""" await self.prefs.async_set_username(None) self._google_config = None @callback def user_message(self, identifier: str, title: str, message: str) -> None: """Create a message for user to UI.""" self._hass.components.persistent_notification.async_create( message, title, identifier ) @callback def dispatcher_message(self, identifier: str, data: Any = None) -> None: """Match cloud notification to dispatcher.""" if identifier.startswith("remote_"): async_dispatcher_send(self._hass, DISPATCHER_REMOTE_UPDATE, data) async def async_alexa_message(self, payload: dict[Any, Any]) -> dict[Any, Any]: """Process cloud alexa message to client.""" cloud_user = await self._prefs.get_cloud_user() aconfig = await self.get_alexa_config() return await alexa_sh.async_handle_message( self._hass, aconfig, payload, context=Context(user_id=cloud_user), enabled=self._prefs.alexa_enabled, ) async def async_google_message(self, payload: dict[Any, Any]) -> dict[Any, Any]: """Process cloud google message to client.""" if not self._prefs.google_enabled: return ga.turned_off_response(payload) gconf = await self.get_google_config() return await ga.async_handle_message( self._hass, gconf, gconf.cloud_user, payload, gc.SOURCE_CLOUD ) async def async_webhook_message(self, payload: dict[Any, Any]) -> dict[Any, Any]: """Process cloud webhook message to client.""" cloudhook_id = payload["cloudhook_id"] found = None for cloudhook in self._prefs.cloudhooks.values(): if cloudhook["cloudhook_id"] == cloudhook_id: found = cloudhook break if found is None: return {"status": HTTP_OK} request = MockRequest( content=payload["body"].encode("utf-8"), headers=payload["headers"], method=payload["method"], query_string=payload["query"], mock_source=DOMAIN, ) response = await self._hass.components.webhook.async_handle_webhook( found["webhook_id"], request ) response_dict = utils.aiohttp_serialize_response(response) body = response_dict.get("body") return { "body": body, "status": response_dict["status"], "headers": {"Content-Type": response.content_type}, } async def async_cloudhooks_update(self, data: dict[str, dict[str, str]]) -> None: """Update local list of cloudhooks.""" await self._prefs.async_update(cloudhooks=data)
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/cloud/client.py
"""Config flow for Elk-M1 Control integration.""" import asyncio import logging from urllib.parse import urlparse import elkm1_lib as elkm1 import voluptuous as vol from homeassistant import config_entries, exceptions from homeassistant.const import ( CONF_ADDRESS, CONF_HOST, CONF_PASSWORD, CONF_PREFIX, CONF_PROTOCOL, CONF_TEMPERATURE_UNIT, CONF_USERNAME, TEMP_CELSIUS, TEMP_FAHRENHEIT, ) from homeassistant.util import slugify from . import async_wait_for_elk_to_sync from .const import CONF_AUTO_CONFIGURE, DOMAIN _LOGGER = logging.getLogger(__name__) PROTOCOL_MAP = {"secure": "elks://", "non-secure": "elk://", "serial": "serial://"} DATA_SCHEMA = vol.Schema( { vol.Required(CONF_PROTOCOL, default="secure"): vol.In( ["secure", "non-secure", "serial"] ), vol.Required(CONF_ADDRESS): str, vol.Optional(CONF_USERNAME, default=""): str, vol.Optional(CONF_PASSWORD, default=""): str, vol.Optional(CONF_PREFIX, default=""): str, vol.Optional(CONF_TEMPERATURE_UNIT, default=TEMP_FAHRENHEIT): vol.In( [TEMP_FAHRENHEIT, TEMP_CELSIUS] ), } ) VALIDATE_TIMEOUT = 35 async def validate_input(data): """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. """ userid = data.get(CONF_USERNAME) password = data.get(CONF_PASSWORD) prefix = data[CONF_PREFIX] url = _make_url_from_data(data) requires_password = url.startswith("elks://") if requires_password and (not userid or not password): raise InvalidAuth elk = elkm1.Elk( {"url": url, "userid": userid, "password": password, "element_list": ["panel"]} ) elk.connect() if not await async_wait_for_elk_to_sync(elk, VALIDATE_TIMEOUT, url): raise InvalidAuth device_name = data[CONF_PREFIX] if data[CONF_PREFIX] else "ElkM1" # Return info that you want to store in the config entry. return {"title": device_name, CONF_HOST: url, CONF_PREFIX: slugify(prefix)} def _make_url_from_data(data): host = data.get(CONF_HOST) if host: return host protocol = PROTOCOL_MAP[data[CONF_PROTOCOL]] address = data[CONF_ADDRESS] return f"{protocol}{address}" class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for Elk-M1 Control.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH def __init__(self): """Initialize the elkm1 config flow.""" self.importing = False async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: if self._url_already_configured(_make_url_from_data(user_input)): return self.async_abort(reason="address_already_configured") try: info = await validate_input(user_input) except asyncio.TimeoutError: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" if "base" not in errors: await self.async_set_unique_id(user_input[CONF_PREFIX]) self._abort_if_unique_id_configured() if self.importing: return self.async_create_entry(title=info["title"], data=user_input) return self.async_create_entry( title=info["title"], data={ CONF_HOST: info[CONF_HOST], CONF_USERNAME: user_input[CONF_USERNAME], CONF_PASSWORD: user_input[CONF_PASSWORD], CONF_AUTO_CONFIGURE: True, CONF_TEMPERATURE_UNIT: user_input[CONF_TEMPERATURE_UNIT], CONF_PREFIX: info[CONF_PREFIX], }, ) return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors ) async def async_step_import(self, user_input): """Handle import.""" self.importing = True return await self.async_step_user(user_input) def _url_already_configured(self, url): """See if we already have a elkm1 matching user input configured.""" existing_hosts = { urlparse(entry.data[CONF_HOST]).hostname for entry in self._async_current_entries() } return urlparse(url).hostname in existing_hosts class InvalidAuth(exceptions.HomeAssistantError): """Error to indicate there is invalid auth."""
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/elkm1/config_flow.py
"""Support for HDMI CEC devices as switches.""" import logging from homeassistant.components.switch import DOMAIN, SwitchEntity from homeassistant.const import STATE_OFF, STATE_ON, STATE_STANDBY from . import ATTR_NEW, CecEntity _LOGGER = logging.getLogger(__name__) ENTITY_ID_FORMAT = DOMAIN + ".{}" def setup_platform(hass, config, add_entities, discovery_info=None): """Find and return HDMI devices as switches.""" if ATTR_NEW in discovery_info: _LOGGER.info("Setting up HDMI devices %s", discovery_info[ATTR_NEW]) entities = [] for device in discovery_info[ATTR_NEW]: hdmi_device = hass.data.get(device) entities.append(CecSwitchEntity(hdmi_device, hdmi_device.logical_address)) add_entities(entities, True) class CecSwitchEntity(CecEntity, SwitchEntity): """Representation of a HDMI device as a Switch.""" def __init__(self, device, logical) -> None: """Initialize the HDMI device.""" CecEntity.__init__(self, device, logical) self.entity_id = f"{DOMAIN}.hdmi_{hex(self._logical_address)[2:]}" def turn_on(self, **kwargs) -> None: """Turn device on.""" self._device.turn_on() self._state = STATE_ON self.schedule_update_ha_state(force_refresh=False) def turn_off(self, **kwargs) -> None: """Turn device off.""" self._device.turn_off() self._state = STATE_OFF self.schedule_update_ha_state(force_refresh=False) def toggle(self, **kwargs): """Toggle the entity.""" self._device.toggle() if self._state == STATE_ON: self._state = STATE_OFF else: self._state = STATE_ON self.schedule_update_ha_state(force_refresh=False) @property def is_on(self) -> bool: """Return True if entity is on.""" return self._state == STATE_ON @property def is_standby(self): """Return true if device is in standby.""" return self._state == STATE_OFF or self._state == STATE_STANDBY @property def state(self) -> str: """Return the cached state of device.""" return self._state
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/hdmi_cec/switch.py
"""Support for SMS notification services.""" import logging import gammu # pylint: disable=import-error import voluptuous as vol from homeassistant.components.notify import PLATFORM_SCHEMA, BaseNotificationService from homeassistant.const import CONF_NAME, CONF_RECIPIENT import homeassistant.helpers.config_validation as cv from .const import DOMAIN, SMS_GATEWAY _LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_RECIPIENT): cv.string, vol.Optional(CONF_NAME): cv.string} ) def get_service(hass, config, discovery_info=None): """Get the SMS notification service.""" if SMS_GATEWAY not in hass.data[DOMAIN]: _LOGGER.error("SMS gateway not found, cannot initialize service") return gateway = hass.data[DOMAIN][SMS_GATEWAY] if discovery_info is None: number = config[CONF_RECIPIENT] else: number = discovery_info[CONF_RECIPIENT] return SMSNotificationService(gateway, number) class SMSNotificationService(BaseNotificationService): """Implement the notification service for SMS.""" def __init__(self, gateway, number): """Initialize the service.""" self.gateway = gateway self.number = number async def async_send_message(self, message="", **kwargs): """Send SMS message.""" smsinfo = { "Class": -1, "Unicode": False, "Entries": [{"ID": "ConcatenatedTextLong", "Buffer": message}], } try: # Encode messages encoded = gammu.EncodeSMS(smsinfo) except gammu.GSMError as exc: _LOGGER.error("Encoding message %s failed: %s", message, exc) return # Send messages for encoded_message in encoded: # Fill in numbers encoded_message["SMSC"] = {"Location": 1} encoded_message["Number"] = self.number try: # Actually send the message await self.gateway.send_sms_async(encoded_message) except gammu.GSMError as exc: _LOGGER.error("Sending to %s failed: %s", self.number, exc)
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/sms/notify.py
"""Support for Fibaro binary sensors.""" from homeassistant.components.binary_sensor import ( DEVICE_CLASS_DOOR, DEVICE_CLASS_MOTION, DEVICE_CLASS_SMOKE, DEVICE_CLASS_WINDOW, DOMAIN, BinarySensorEntity, ) from homeassistant.const import CONF_DEVICE_CLASS, CONF_ICON from . import FIBARO_DEVICES, FibaroDevice SENSOR_TYPES = { "com.fibaro.floodSensor": ["Flood", "mdi:water", "flood"], "com.fibaro.motionSensor": ["Motion", "mdi:run", DEVICE_CLASS_MOTION], "com.fibaro.doorSensor": ["Door", "mdi:window-open", DEVICE_CLASS_DOOR], "com.fibaro.windowSensor": ["Window", "mdi:window-open", DEVICE_CLASS_WINDOW], "com.fibaro.smokeSensor": ["Smoke", "mdi:smoking", DEVICE_CLASS_SMOKE], "com.fibaro.FGMS001": ["Motion", "mdi:run", DEVICE_CLASS_MOTION], "com.fibaro.heatDetector": ["Heat", "mdi:fire", "heat"], } def setup_platform(hass, config, add_entities, discovery_info=None): """Perform the setup for Fibaro controller devices.""" if discovery_info is None: return add_entities( [ FibaroBinarySensor(device) for device in hass.data[FIBARO_DEVICES]["binary_sensor"] ], True, ) class FibaroBinarySensor(FibaroDevice, BinarySensorEntity): """Representation of a Fibaro Binary Sensor.""" def __init__(self, fibaro_device): """Initialize the binary_sensor.""" self._state = None super().__init__(fibaro_device) self.entity_id = f"{DOMAIN}.{self.ha_id}" stype = None devconf = fibaro_device.device_config if fibaro_device.type in SENSOR_TYPES: stype = fibaro_device.type elif fibaro_device.baseType in SENSOR_TYPES: stype = fibaro_device.baseType if stype: self._device_class = SENSOR_TYPES[stype][2] self._icon = SENSOR_TYPES[stype][1] else: self._device_class = None self._icon = None # device_config overrides: self._device_class = devconf.get(CONF_DEVICE_CLASS, self._device_class) self._icon = devconf.get(CONF_ICON, self._icon) @property def icon(self): """Icon to use in the frontend, if any.""" return self._icon @property def device_class(self): """Return the device class of the sensor.""" return self._device_class @property def is_on(self): """Return true if sensor is on.""" return self._state def update(self): """Get the latest data and update the state.""" self._state = self.current_binary_state
"""Tests for the Home Assistant auth module.""" from datetime import timedelta from unittest.mock import Mock, patch import jwt import pytest import voluptuous as vol from homeassistant import auth, data_entry_flow from homeassistant.auth import ( InvalidAuthError, auth_store, const as auth_const, models as auth_models, ) from homeassistant.auth.const import MFA_SESSION_EXPIRATION from homeassistant.core import callback from homeassistant.util import dt as dt_util from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded, flush_store @pytest.fixture def mock_hass(loop): """Home Assistant mock with minimum amount of data set to make it work with auth.""" hass = Mock() hass.config.skip_pip = True return hass async def test_auth_manager_from_config_validates_config(mock_hass): """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Invalid configuration because no users", "type": "insecure_example", "id": "invalid_config", }, ], [], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [], ) providers = [ {"name": provider.name, "id": provider.id, "type": provider.type} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] async def test_auth_manager_from_config_auth_modules(mock_hass): """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Invalid configuration because no data", "type": "insecure_example", "id": "another", }, ], ) manager = await auth.auth_manager_from_config( mock_hass, [ {"name": "Test Name", "type": "insecure_example", "users": []}, { "name": "Test Name 2", "type": "insecure_example", "id": "another", "users": [], }, ], [ {"name": "Module 1", "type": "insecure_example", "data": []}, { "name": "Module 2", "type": "insecure_example", "id": "another", "data": [], }, ], ) providers = [ {"name": provider.name, "type": provider.type, "id": provider.id} for provider in manager.auth_providers ] assert providers == [ {"name": "Test Name", "type": "insecure_example", "id": None}, {"name": "Test Name 2", "type": "insecure_example", "id": "another"}, ] modules = [ {"name": module.name, "type": module.type, "id": module.id} for module in manager.auth_mfa_modules ] assert modules == [ {"name": "Module 1", "type": "insecure_example", "id": "insecure_example"}, {"name": "Module 2", "type": "insecure_example", "id": "another"}, ] async def test_create_new_user(hass): """Test creating new user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] assert credential is not None user = await manager.async_get_or_create_user(credential) assert user is not None assert user.is_owner is False assert user.name == "Test Name" await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_login_as_existing_user(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add a fake user that we're not going to log in with user = MockUser( id="mock-user2", is_owner=False, is_active=False, name="Not user" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id2", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "other-user"}, is_new=False, ) ) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY credential = step["result"] user = await manager.async_get_user_by_credentials(credential) assert user is not None assert user.id == "mock-user" assert user.is_owner is False assert user.is_active is False assert user.name == "Paulus" async def test_linking_user_to_two_auth_providers(hass, hass_storage): """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], }, { "type": "insecure_example", "id": "another-provider", "users": [{"username": "another-user", "password": "another-password"}], }, ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None step = await manager.login_flow.async_init( ("insecure_example", "another-provider"), context={"credential_only": True} ) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "another-user", "password": "another-password"} ) new_credential = step["result"] await manager.async_link_user(user, new_credential) assert len(user.credentials) == 2 async def test_saving_loading(hass, hass_storage): """Test storing and saving data. Creates one of each type that we store to test we restore correctly. """ manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) await manager.async_activate_user(user) # the first refresh token will be used to create access token refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) manager.async_create_access_token(refresh_token, "192.168.0.1") # the second refresh token will not be used await manager.async_create_refresh_token( user, "dummy-client", credential=credential ) await flush_store(manager._store._store) store2 = auth_store.AuthStore(hass) users = await store2.async_get_users() assert len(users) == 1 assert users[0].permissions == user.permissions assert users[0] == user assert len(users[0].refresh_tokens) == 2 for r_token in users[0].refresh_tokens.values(): if r_token.client_id == CLIENT_ID: # verify the first refresh token assert r_token.last_used_at is not None assert r_token.last_used_ip == "192.168.0.1" elif r_token.client_id == "dummy-client": # verify the second refresh token assert r_token.last_used_at is None assert r_token.last_used_ip is None else: assert False, "Unknown client_id: %s" % r_token.client_id async def test_cannot_retrieve_expired_access_token(hass): """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.user.id is user.id assert refresh_token.client_id == CLIENT_ID access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is refresh_token with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() - auth_const.ACCESS_TOKEN_EXPIRATION - timedelta(seconds=11), ): access_token = manager.async_create_access_token(refresh_token) assert await manager.async_validate_access_token(access_token) is None async def test_generating_system_user(hass): """Test that we can add a system user.""" events = [] @callback def user_added(event): events.append(event) hass.bus.async_listen("user_added", user_added) manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") token = await manager.async_create_refresh_token(user) assert user.system_generated assert token is not None assert token.client_id is None await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_refresh_token_requires_client_for_user(hass): """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) assert user.system_generated is False with pytest.raises(ValueError): await manager.async_create_refresh_token(user) token = await manager.async_create_refresh_token(user, CLIENT_ID) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL # default access token expiration assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION async def test_refresh_token_not_requires_client_for_system_user(hass): """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") assert user.system_generated is True with pytest.raises(ValueError): await manager.async_create_refresh_token(user, CLIENT_ID) token = await manager.async_create_refresh_token(user) assert token is not None assert token.client_id is None assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM async def test_refresh_token_with_specific_access_token_expiration(hass): """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) token = await manager.async_create_refresh_token( user, CLIENT_ID, access_token_expiration=timedelta(days=100) ) assert token is not None assert token.client_id == CLIENT_ID assert token.access_token_expiration == timedelta(days=100) async def test_refresh_token_type(hass): """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_SYSTEM ) token = await manager.async_create_refresh_token( user, CLIENT_ID, token_type=auth_models.TOKEN_TYPE_NORMAL ) assert token is not None assert token.client_id == CLIENT_ID assert token.token_type == auth_models.TOKEN_TYPE_NORMAL async def test_refresh_token_type_long_lived_access_token(hass): """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_create_refresh_token( user, token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN ) token = await manager.async_create_refresh_token( user, client_name="GPS LOGGER", client_icon="mdi:home", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, ) assert token is not None assert token.client_id is None assert token.client_name == "GPS LOGGER" assert token.client_icon == "mdi:home" assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN async def test_refresh_token_provider_validation(mock_hass): """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [], ) credential = auth_models.Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) user = MockUser().add_to_auth_manager(manager) user.credentials.append(credential) refresh_token = await manager.async_create_refresh_token( user, CLIENT_ID, credential=credential ) ip = "127.0.0.1" assert manager.async_create_access_token(refresh_token, ip) is not None with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), ) as call, pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) async def test_cannot_deactive_owner(mock_hass): """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) with pytest.raises(ValueError): await manager.async_deactivate_user(owner) async def test_remove_refresh_token(mock_hass): """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) access_token = manager.async_create_access_token(refresh_token) await manager.async_remove_refresh_token(refresh_token) assert await manager.async_get_refresh_token(refresh_token.id) is None assert await manager.async_validate_access_token(access_token) is None async def test_create_access_token(mock_hass): """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) assert refresh_token.token_type == auth_models.TOKEN_TYPE_NORMAL jwt_key = refresh_token.jwt_key access_token = manager.async_create_access_token(refresh_token) assert access_token is not None assert refresh_token.jwt_key == jwt_key jwt_payload = jwt.decode(access_token, jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(minutes=30).total_seconds() ) async def test_create_long_lived_access_token(mock_hass): """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=300), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_payload = jwt.decode(access_token, refresh_token.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=300).total_seconds() ) async def test_one_long_lived_access_token_per_refresh_token(mock_hass): """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) refresh_token = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token = manager.async_create_access_token(refresh_token) jwt_key = refresh_token.jwt_key rt = await manager.async_validate_access_token(access_token) assert rt.id == refresh_token.id with pytest.raises(ValueError): await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) await manager.async_remove_refresh_token(refresh_token) assert refresh_token.id not in user.refresh_tokens rt = await manager.async_validate_access_token(access_token) assert rt is None, "Previous issued access token has been invoked" refresh_token_2 = await manager.async_create_refresh_token( user, client_name="GPS Logger", token_type=auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN, access_token_expiration=timedelta(days=3000), ) assert refresh_token_2.id != refresh_token.id assert refresh_token_2.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN access_token_2 = manager.async_create_access_token(refresh_token_2) jwt_key_2 = refresh_token_2.jwt_key assert access_token != access_token_2 assert jwt_key != jwt_key_2 rt = await manager.async_validate_access_token(access_token_2) jwt_payload = jwt.decode(access_token_2, rt.jwt_key, algorithm=["HS256"]) assert jwt_payload["iss"] == refresh_token_2.id assert ( jwt_payload["exp"] - jwt_payload["iat"] == timedelta(days=3000).total_seconds() ) async def test_login_with_auth_module(mock_hass): """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request auth module input form assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "invalid-pin"} ) # Invalid code error assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" assert step["errors"] == {"base": "invalid_code"} step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_login_with_multi_auth_module(mock_hass): """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], }, { "type": "insecure_example", "id": "module2", "data": [{"user_id": "mock-user", "pin": "test-pin2"}], }, ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) # After auth_provider validated, request select auth module assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "select_mfa_module" step = await manager.login_flow.async_configure( step["flow_id"], {"multi_factor_auth_module": "module2"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin2"} ) # Finally passed, get credential assert step["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert step["result"] assert step["result"].id == "mock-id" async def test_auth_module_expired_session(mock_hass): """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "test-pin"}], } ], ) mock_hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) step = await manager.login_flow.async_init(("insecure_example", None)) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert step["type"] == data_entry_flow.RESULT_TYPE_FORM assert step["step_id"] == "mfa" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.utcnow() + MFA_SESSION_EXPIRATION, ): step = await manager.login_flow.async_configure( step["flow_id"], {"pin": "test-pin"} ) # login flow abort due session timeout assert step["type"] == data_entry_flow.RESULT_TYPE_ABORT assert step["reason"] == "login_expired" async def test_enable_mfa_for_user(hass, hass_storage): """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [{"type": "insecure_example", "data": []}], ) step = await manager.login_flow.async_init(("insecure_example", None)) step = await manager.login_flow.async_configure( step["flow_id"], {"username": "test-user", "password": "test-pass"} ) credential = step["result"] user = await manager.async_get_or_create_user(credential) assert user is not None # new user don't have mfa enabled modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 module = manager.get_auth_mfa_module("insecure_example") # mfa module don't have data assert bool(module._data) is False # test enable mfa for user await manager.async_enable_user_mfa(user, "insecure_example", {"pin": "test-pin"}) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin"} # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # re-enable mfa for user will override await manager.async_enable_user_mfa( user, "insecure_example", {"pin": "test-pin-new"} ) assert len(module._data) == 1 assert module._data[0] == {"user_id": user.id, "pin": "test-pin-new"} modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 1 assert "insecure_example" in modules # system user cannot enable mfa system_user = await manager.async_create_system_user("system-user") with pytest.raises(ValueError): await manager.async_enable_user_mfa( system_user, "insecure_example", {"pin": "test-pin"} ) assert len(module._data) == 1 modules = await manager.async_get_enabled_mfa(system_user) assert len(modules) == 0 # disable mfa for user await manager.async_disable_user_mfa(user, "insecure_example") assert bool(module._data) is False # test get enabled mfa modules = await manager.async_get_enabled_mfa(user) assert len(modules) == 0 # disable mfa for user don't enabled just silent fail await manager.async_disable_user_mfa(user, "insecure_example") async def test_async_remove_user(hass): """Test removing a user.""" events = [] @callback def user_removed(event): events.append(event) hass.bus.async_listen("user_removed", user_removed) manager = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", } ], } ], [], ) hass.auth = manager ensure_auth_manager_loaded(manager) # Add fake user with credentials for example auth provider. user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(manager) user.credentials.append( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ) ) assert len(user.credentials) == 1 await hass.auth.async_remove_user(user) assert len(await manager.async_get_users()) == 0 assert len(user.credentials) == 0 await hass.async_block_till_done() assert len(events) == 1 assert events[0].data["user_id"] == user.id async def test_new_users(mock_hass): """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, [ { "type": "insecure_example", "users": [ { "username": "test-user", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-2", "password": "test-pass", "name": "Test Name", }, { "username": "test-user-3", "password": "test-pass", "name": "Test Name", }, ], } ], [], ) ensure_auth_manager_loaded(manager) user = await manager.async_create_user("Hello") # first user in the system is owner and admin assert user.is_owner assert user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 2") assert not user.is_admin assert user.groups == [] user = await manager.async_create_user("Hello 3", ["system-admin"]) assert user.is_admin assert user.groups[0].id == "system-admin" user_cred = await manager.async_get_or_create_user( auth_models.Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=True, ) ) assert user_cred.is_admin
adrienbrault/home-assistant
tests/auth/test_init.py
homeassistant/components/fibaro/binary_sensor.py
"""Constants for Daikin.""" from homeassistant.const import CONF_ICON, CONF_NAME, CONF_TYPE ATTR_TARGET_TEMPERATURE = 'target_temperature' ATTR_INSIDE_TEMPERATURE = 'inside_temperature' ATTR_OUTSIDE_TEMPERATURE = 'outside_temperature' SENSOR_TYPE_TEMPERATURE = 'temperature' SENSOR_TYPES = { ATTR_INSIDE_TEMPERATURE: { CONF_NAME: 'Inside Temperature', CONF_ICON: 'mdi:thermometer', CONF_TYPE: SENSOR_TYPE_TEMPERATURE }, ATTR_OUTSIDE_TEMPERATURE: { CONF_NAME: 'Outside Temperature', CONF_ICON: 'mdi:thermometer', CONF_TYPE: SENSOR_TYPE_TEMPERATURE } } KEY_MAC = 'mac' KEY_IP = 'ip'
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/daikin/const.py
"""Support for interface with a Ziggo Mediabox XL.""" import logging import socket import voluptuous as vol from homeassistant.components.media_player import ( MediaPlayerDevice, PLATFORM_SCHEMA) from homeassistant.components.media_player.const import ( SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PREVIOUS_TRACK, SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF, SUPPORT_TURN_ON) from homeassistant.const import ( CONF_HOST, CONF_NAME, STATE_OFF, STATE_PAUSED, STATE_PLAYING) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DATA_KNOWN_DEVICES = 'ziggo_mediabox_xl_known_devices' SUPPORT_ZIGGO = SUPPORT_TURN_ON | SUPPORT_TURN_OFF | \ SUPPORT_NEXT_TRACK | SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | \ SUPPORT_SELECT_SOURCE | SUPPORT_PLAY PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_NAME): cv.string, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Ziggo Mediabox XL platform.""" from ziggo_mediabox_xl import ZiggoMediaboxXL hass.data[DATA_KNOWN_DEVICES] = known_devices = set() # Is this a manual configuration? if config.get(CONF_HOST) is not None: host = config.get(CONF_HOST) name = config.get(CONF_NAME) manual_config = True elif discovery_info is not None: host = discovery_info.get('host') name = discovery_info.get('name') manual_config = False else: _LOGGER.error("Cannot determine device") return # Only add a device once, so discovered devices do not override manual # config. hosts = [] connection_successful = False ip_addr = socket.gethostbyname(host) if ip_addr not in known_devices: try: # Mediabox instance with a timeout of 3 seconds. mediabox = ZiggoMediaboxXL(ip_addr, 3) # Check if a connection can be established to the device. if mediabox.test_connection(): connection_successful = True else: if manual_config: _LOGGER.info("Can't connect to %s", host) else: _LOGGER.error("Can't connect to %s", host) # When the device is in eco mode it's not connected to the network # so it needs to be added anyway if it's configured manually. if manual_config or connection_successful: hosts.append(ZiggoMediaboxXLDevice(mediabox, host, name, connection_successful)) known_devices.add(ip_addr) except socket.error as error: _LOGGER.error("Can't connect to %s: %s", host, error) else: _LOGGER.info("Ignoring duplicate Ziggo Mediabox XL %s", host) add_entities(hosts, True) class ZiggoMediaboxXLDevice(MediaPlayerDevice): """Representation of a Ziggo Mediabox XL Device.""" def __init__(self, mediabox, host, name, available): """Initialize the device.""" self._mediabox = mediabox self._host = host self._name = name self._available = available self._state = None def update(self): """Retrieve the state of the device.""" try: if self._mediabox.test_connection(): if self._mediabox.turned_on(): if self._state != STATE_PAUSED: self._state = STATE_PLAYING else: self._state = STATE_OFF self._available = True else: self._available = False except socket.error: _LOGGER.error("Couldn't fetch state from %s", self._host) self._available = False def send_keys(self, keys): """Send keys to the device and handle exceptions.""" try: self._mediabox.send_keys(keys) except socket.error: _LOGGER.error("Couldn't send keys to %s", self._host) @property def name(self): """Return the name of the device.""" return self._name @property def state(self): """Return the state of the device.""" return self._state @property def available(self): """Return True if the device is available.""" return self._available @property def source_list(self): """List of available sources (channels).""" return [self._mediabox.channels()[c] for c in sorted(self._mediabox.channels().keys())] @property def supported_features(self): """Flag media player features that are supported.""" return SUPPORT_ZIGGO def turn_on(self): """Turn the media player on.""" self.send_keys(['POWER']) def turn_off(self): """Turn off media player.""" self.send_keys(['POWER']) def media_play(self): """Send play command.""" self.send_keys(['PLAY']) self._state = STATE_PLAYING def media_pause(self): """Send pause command.""" self.send_keys(['PAUSE']) self._state = STATE_PAUSED def media_play_pause(self): """Simulate play pause media player.""" self.send_keys(['PAUSE']) if self._state == STATE_PAUSED: self._state = STATE_PLAYING else: self._state = STATE_PAUSED def media_next_track(self): """Channel up.""" self.send_keys(['CHAN_UP']) self._state = STATE_PLAYING def media_previous_track(self): """Channel down.""" self.send_keys(['CHAN_DOWN']) self._state = STATE_PLAYING def select_source(self, source): """Select the channel.""" if str(source).isdigit(): digits = str(source) else: digits = next(( key for key, value in self._mediabox.channels().items() if value == source), None) if digits is None: return self.send_keys(['NUM_{}'.format(digit) for digit in str(digits)]) self._state = STATE_PLAYING
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/ziggo_mediabox_xl/media_player.py
"""The HTTP api to control the cloud integration.""" import asyncio from functools import wraps import logging import attr import aiohttp import async_timeout import voluptuous as vol from homeassistant.core import callback from homeassistant.components.http import HomeAssistantView from homeassistant.components.http.data_validator import ( RequestDataValidator) from homeassistant.components import websocket_api from homeassistant.components.websocket_api import const as ws_const from homeassistant.components.alexa import ( entities as alexa_entities, errors as alexa_errors, ) from homeassistant.components.google_assistant import helpers as google_helpers from .const import ( DOMAIN, REQUEST_TIMEOUT, PREF_ENABLE_ALEXA, PREF_ENABLE_GOOGLE, PREF_GOOGLE_SECURE_DEVICES_PIN, InvalidTrustedNetworks, InvalidTrustedProxies, PREF_ALEXA_REPORT_STATE, RequireRelink) _LOGGER = logging.getLogger(__name__) WS_TYPE_STATUS = 'cloud/status' SCHEMA_WS_STATUS = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({ vol.Required('type'): WS_TYPE_STATUS, }) WS_TYPE_SUBSCRIPTION = 'cloud/subscription' SCHEMA_WS_SUBSCRIPTION = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({ vol.Required('type'): WS_TYPE_SUBSCRIPTION, }) WS_TYPE_HOOK_CREATE = 'cloud/cloudhook/create' SCHEMA_WS_HOOK_CREATE = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({ vol.Required('type'): WS_TYPE_HOOK_CREATE, vol.Required('webhook_id'): str }) WS_TYPE_HOOK_DELETE = 'cloud/cloudhook/delete' SCHEMA_WS_HOOK_DELETE = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({ vol.Required('type'): WS_TYPE_HOOK_DELETE, vol.Required('webhook_id'): str }) _CLOUD_ERRORS = { InvalidTrustedNetworks: (500, 'Remote UI not compatible with 127.0.0.1/::1' ' as a trusted network.'), InvalidTrustedProxies: (500, 'Remote UI not compatible with 127.0.0.1/::1' ' as trusted proxies.'), } async def async_setup(hass): """Initialize the HTTP API.""" hass.components.websocket_api.async_register_command( WS_TYPE_STATUS, websocket_cloud_status, SCHEMA_WS_STATUS ) hass.components.websocket_api.async_register_command( WS_TYPE_SUBSCRIPTION, websocket_subscription, SCHEMA_WS_SUBSCRIPTION ) hass.components.websocket_api.async_register_command( websocket_update_prefs) hass.components.websocket_api.async_register_command( WS_TYPE_HOOK_CREATE, websocket_hook_create, SCHEMA_WS_HOOK_CREATE ) hass.components.websocket_api.async_register_command( WS_TYPE_HOOK_DELETE, websocket_hook_delete, SCHEMA_WS_HOOK_DELETE ) hass.components.websocket_api.async_register_command( websocket_remote_connect) hass.components.websocket_api.async_register_command( websocket_remote_disconnect) hass.components.websocket_api.async_register_command( google_assistant_list) hass.components.websocket_api.async_register_command( google_assistant_update) hass.components.websocket_api.async_register_command(alexa_list) hass.components.websocket_api.async_register_command(alexa_update) hass.components.websocket_api.async_register_command(alexa_sync) hass.http.register_view(GoogleActionsSyncView) hass.http.register_view(CloudLoginView) hass.http.register_view(CloudLogoutView) hass.http.register_view(CloudRegisterView) hass.http.register_view(CloudResendConfirmView) hass.http.register_view(CloudForgotPasswordView) from hass_nabucasa import auth _CLOUD_ERRORS.update({ auth.UserNotFound: (400, "User does not exist."), auth.UserNotConfirmed: (400, 'Email not confirmed.'), auth.UserExists: (400, 'An account with the given email already exists.'), auth.Unauthenticated: (401, 'Authentication failed.'), auth.PasswordChangeRequired: (400, 'Password change required.'), asyncio.TimeoutError: (502, 'Unable to reach the Home Assistant cloud.'), aiohttp.ClientError: (500, 'Error making internal request'), }) def _handle_cloud_errors(handler): """Webview decorator to handle auth errors.""" @wraps(handler) async def error_handler(view, request, *args, **kwargs): """Handle exceptions that raise from the wrapped request handler.""" try: result = await handler(view, request, *args, **kwargs) return result except Exception as err: # pylint: disable=broad-except status, msg = _process_cloud_exception(err, request.path) return view.json_message( msg, status_code=status, message_code=err.__class__.__name__.lower()) return error_handler def _ws_handle_cloud_errors(handler): """Websocket decorator to handle auth errors.""" @wraps(handler) async def error_handler(hass, connection, msg): """Handle exceptions that raise from the wrapped handler.""" try: return await handler(hass, connection, msg) except Exception as err: # pylint: disable=broad-except err_status, err_msg = _process_cloud_exception(err, msg['type']) connection.send_error(msg['id'], err_status, err_msg) return error_handler def _process_cloud_exception(exc, where): """Process a cloud exception.""" err_info = _CLOUD_ERRORS.get(exc.__class__) if err_info is None: _LOGGER.exception( "Unexpected error processing request for %s", where) err_info = (502, 'Unexpected error: {}'.format(exc)) return err_info class GoogleActionsSyncView(HomeAssistantView): """Trigger a Google Actions Smart Home Sync.""" url = '/api/cloud/google_actions/sync' name = 'api:cloud:google_actions/sync' @_handle_cloud_errors async def post(self, request): """Trigger a Google Actions sync.""" hass = request.app['hass'] cloud = hass.data[DOMAIN] websession = hass.helpers.aiohttp_client.async_get_clientsession() with async_timeout.timeout(REQUEST_TIMEOUT): await hass.async_add_job(cloud.auth.check_token) with async_timeout.timeout(REQUEST_TIMEOUT): req = await websession.post( cloud.google_actions_sync_url, headers={ 'authorization': cloud.id_token }) return self.json({}, status_code=req.status) class CloudLoginView(HomeAssistantView): """Login to Home Assistant cloud.""" url = '/api/cloud/login' name = 'api:cloud:login' @_handle_cloud_errors @RequestDataValidator(vol.Schema({ vol.Required('email'): str, vol.Required('password'): str, })) async def post(self, request, data): """Handle login request.""" hass = request.app['hass'] cloud = hass.data[DOMAIN] with async_timeout.timeout(REQUEST_TIMEOUT): await hass.async_add_job(cloud.auth.login, data['email'], data['password']) hass.async_add_job(cloud.iot.connect) return self.json({'success': True}) class CloudLogoutView(HomeAssistantView): """Log out of the Home Assistant cloud.""" url = '/api/cloud/logout' name = 'api:cloud:logout' @_handle_cloud_errors async def post(self, request): """Handle logout request.""" hass = request.app['hass'] cloud = hass.data[DOMAIN] with async_timeout.timeout(REQUEST_TIMEOUT): await cloud.logout() return self.json_message('ok') class CloudRegisterView(HomeAssistantView): """Register on the Home Assistant cloud.""" url = '/api/cloud/register' name = 'api:cloud:register' @_handle_cloud_errors @RequestDataValidator(vol.Schema({ vol.Required('email'): str, vol.Required('password'): vol.All(str, vol.Length(min=6)), })) async def post(self, request, data): """Handle registration request.""" hass = request.app['hass'] cloud = hass.data[DOMAIN] with async_timeout.timeout(REQUEST_TIMEOUT): await hass.async_add_job( cloud.auth.register, data['email'], data['password']) return self.json_message('ok') class CloudResendConfirmView(HomeAssistantView): """Resend email confirmation code.""" url = '/api/cloud/resend_confirm' name = 'api:cloud:resend_confirm' @_handle_cloud_errors @RequestDataValidator(vol.Schema({ vol.Required('email'): str, })) async def post(self, request, data): """Handle resending confirm email code request.""" hass = request.app['hass'] cloud = hass.data[DOMAIN] with async_timeout.timeout(REQUEST_TIMEOUT): await hass.async_add_job( cloud.auth.resend_email_confirm, data['email']) return self.json_message('ok') class CloudForgotPasswordView(HomeAssistantView): """View to start Forgot Password flow..""" url = '/api/cloud/forgot_password' name = 'api:cloud:forgot_password' @_handle_cloud_errors @RequestDataValidator(vol.Schema({ vol.Required('email'): str, })) async def post(self, request, data): """Handle forgot password request.""" hass = request.app['hass'] cloud = hass.data[DOMAIN] with async_timeout.timeout(REQUEST_TIMEOUT): await hass.async_add_job( cloud.auth.forgot_password, data['email']) return self.json_message('ok') @callback def websocket_cloud_status(hass, connection, msg): """Handle request for account info. Async friendly. """ cloud = hass.data[DOMAIN] connection.send_message( websocket_api.result_message(msg['id'], _account_data(cloud))) def _require_cloud_login(handler): """Websocket decorator that requires cloud to be logged in.""" @wraps(handler) def with_cloud_auth(hass, connection, msg): """Require to be logged into the cloud.""" cloud = hass.data[DOMAIN] if not cloud.is_logged_in: connection.send_message(websocket_api.error_message( msg['id'], 'not_logged_in', 'You need to be logged in to the cloud.')) return handler(hass, connection, msg) return with_cloud_auth @_require_cloud_login @websocket_api.async_response async def websocket_subscription(hass, connection, msg): """Handle request for account info.""" from hass_nabucasa.const import STATE_DISCONNECTED cloud = hass.data[DOMAIN] with async_timeout.timeout(REQUEST_TIMEOUT): response = await cloud.fetch_subscription_info() if response.status != 200: connection.send_message(websocket_api.error_message( msg['id'], 'request_failed', 'Failed to request subscription')) data = await response.json() # Check if a user is subscribed but local info is outdated # In that case, let's refresh and reconnect if data.get('provider') and not cloud.is_connected: _LOGGER.debug( "Found disconnected account with valid subscriotion, connecting") await hass.async_add_executor_job(cloud.auth.renew_access_token) # Cancel reconnect in progress if cloud.iot.state != STATE_DISCONNECTED: await cloud.iot.disconnect() hass.async_create_task(cloud.iot.connect()) connection.send_message(websocket_api.result_message(msg['id'], data)) @_require_cloud_login @websocket_api.async_response @websocket_api.websocket_command({ vol.Required('type'): 'cloud/update_prefs', vol.Optional(PREF_ENABLE_GOOGLE): bool, vol.Optional(PREF_ENABLE_ALEXA): bool, vol.Optional(PREF_ALEXA_REPORT_STATE): bool, vol.Optional(PREF_GOOGLE_SECURE_DEVICES_PIN): vol.Any(None, str), }) async def websocket_update_prefs(hass, connection, msg): """Handle request for account info.""" cloud = hass.data[DOMAIN] changes = dict(msg) changes.pop('id') changes.pop('type') # If we turn alexa linking on, validate that we can fetch access token if changes.get(PREF_ALEXA_REPORT_STATE): try: with async_timeout.timeout(10): await cloud.client.alexa_config.async_get_access_token() except asyncio.TimeoutError: connection.send_error(msg['id'], 'alexa_timeout', 'Timeout validating Alexa access token.') return except (alexa_errors.NoTokenAvailable, RequireRelink): connection.send_error( msg['id'], 'alexa_relink', 'Please go to the Alexa app and re-link the Home Assistant ' 'skill and then try to enable state reporting.' ) return await cloud.client.prefs.async_update(**changes) connection.send_message(websocket_api.result_message(msg['id'])) @_require_cloud_login @websocket_api.async_response @_ws_handle_cloud_errors async def websocket_hook_create(hass, connection, msg): """Handle request for account info.""" cloud = hass.data[DOMAIN] hook = await cloud.cloudhooks.async_create(msg['webhook_id'], False) connection.send_message(websocket_api.result_message(msg['id'], hook)) @_require_cloud_login @websocket_api.async_response @_ws_handle_cloud_errors async def websocket_hook_delete(hass, connection, msg): """Handle request for account info.""" cloud = hass.data[DOMAIN] await cloud.cloudhooks.async_delete(msg['webhook_id']) connection.send_message(websocket_api.result_message(msg['id'])) def _account_data(cloud): """Generate the auth data JSON response.""" from hass_nabucasa.const import STATE_DISCONNECTED if not cloud.is_logged_in: return { 'logged_in': False, 'cloud': STATE_DISCONNECTED, } claims = cloud.claims client = cloud.client remote = cloud.remote # Load remote certificate if remote.certificate: certificate = attr.asdict(remote.certificate) else: certificate = None return { 'logged_in': True, 'email': claims['email'], 'cloud': cloud.iot.state, 'prefs': client.prefs.as_dict(), 'google_entities': client.google_user_config['filter'].config, 'alexa_entities': client.alexa_user_config['filter'].config, 'remote_domain': remote.instance_domain, 'remote_connected': remote.is_connected, 'remote_certificate': certificate, } @websocket_api.require_admin @_require_cloud_login @websocket_api.async_response @_ws_handle_cloud_errors @websocket_api.websocket_command({ 'type': 'cloud/remote/connect' }) async def websocket_remote_connect(hass, connection, msg): """Handle request for connect remote.""" cloud = hass.data[DOMAIN] await cloud.client.prefs.async_update(remote_enabled=True) await cloud.remote.connect() connection.send_result(msg['id'], _account_data(cloud)) @websocket_api.require_admin @_require_cloud_login @websocket_api.async_response @_ws_handle_cloud_errors @websocket_api.websocket_command({ 'type': 'cloud/remote/disconnect' }) async def websocket_remote_disconnect(hass, connection, msg): """Handle request for disconnect remote.""" cloud = hass.data[DOMAIN] await cloud.client.prefs.async_update(remote_enabled=False) await cloud.remote.disconnect() connection.send_result(msg['id'], _account_data(cloud)) @websocket_api.require_admin @_require_cloud_login @websocket_api.async_response @_ws_handle_cloud_errors @websocket_api.websocket_command({ 'type': 'cloud/google_assistant/entities' }) async def google_assistant_list(hass, connection, msg): """List all google assistant entities.""" cloud = hass.data[DOMAIN] entities = google_helpers.async_get_entities( hass, cloud.client.google_config ) result = [] for entity in entities: result.append({ 'entity_id': entity.entity_id, 'traits': [trait.name for trait in entity.traits()], 'might_2fa': entity.might_2fa(), }) connection.send_result(msg['id'], result) @websocket_api.require_admin @_require_cloud_login @websocket_api.async_response @_ws_handle_cloud_errors @websocket_api.websocket_command({ 'type': 'cloud/google_assistant/entities/update', 'entity_id': str, vol.Optional('should_expose'): bool, vol.Optional('override_name'): str, vol.Optional('aliases'): [str], vol.Optional('disable_2fa'): bool, }) async def google_assistant_update(hass, connection, msg): """Update google assistant config.""" cloud = hass.data[DOMAIN] changes = dict(msg) changes.pop('type') changes.pop('id') await cloud.client.prefs.async_update_google_entity_config(**changes) connection.send_result( msg['id'], cloud.client.prefs.google_entity_configs.get(msg['entity_id'])) @websocket_api.require_admin @_require_cloud_login @websocket_api.async_response @_ws_handle_cloud_errors @websocket_api.websocket_command({ 'type': 'cloud/alexa/entities' }) async def alexa_list(hass, connection, msg): """List all alexa entities.""" cloud = hass.data[DOMAIN] entities = alexa_entities.async_get_entities( hass, cloud.client.alexa_config ) result = [] for entity in entities: result.append({ 'entity_id': entity.entity_id, 'display_categories': entity.default_display_categories(), 'interfaces': [ifc.name() for ifc in entity.interfaces()], }) connection.send_result(msg['id'], result) @websocket_api.require_admin @_require_cloud_login @websocket_api.async_response @_ws_handle_cloud_errors @websocket_api.websocket_command({ 'type': 'cloud/alexa/entities/update', 'entity_id': str, vol.Optional('should_expose'): bool, }) async def alexa_update(hass, connection, msg): """Update alexa entity config.""" cloud = hass.data[DOMAIN] changes = dict(msg) changes.pop('type') changes.pop('id') await cloud.client.prefs.async_update_alexa_entity_config(**changes) connection.send_result( msg['id'], cloud.client.prefs.alexa_entity_configs.get(msg['entity_id'])) @websocket_api.require_admin @_require_cloud_login @websocket_api.async_response @websocket_api.websocket_command({ 'type': 'cloud/alexa/sync', }) async def alexa_sync(hass, connection, msg): """Sync with Alexa.""" cloud = hass.data[DOMAIN] with async_timeout.timeout(10): try: success = await cloud.client.alexa_config.async_sync_entities() except alexa_errors.NoTokenAvailable: connection.send_error( msg['id'], 'alexa_relink', 'Please go to the Alexa app and re-link the Home Assistant ' 'skill.' ) return if success: connection.send_result(msg['id']) else: connection.send_error( msg['id'], ws_const.ERR_UNKNOWN_ERROR, 'Unknown error')
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/cloud/http_api.py
"""Support for Google Home alarm sensor.""" from datetime import timedelta import logging from homeassistant.const import DEVICE_CLASS_TIMESTAMP from homeassistant.helpers.entity import Entity import homeassistant.util.dt as dt_util from . import CLIENT, DOMAIN as GOOGLEHOME_DOMAIN, NAME SCAN_INTERVAL = timedelta(seconds=10) _LOGGER = logging.getLogger(__name__) ICON = 'mdi:alarm' SENSOR_TYPES = { 'timer': 'Timer', 'alarm': 'Alarm', } async def async_setup_platform( hass, config, async_add_entities, discovery_info=None): """Set up the googlehome sensor platform.""" if discovery_info is None: _LOGGER.warning( "To use this you need to configure the 'googlehome' component") return await hass.data[CLIENT].update_info(discovery_info['host']) data = hass.data[GOOGLEHOME_DOMAIN][discovery_info['host']] info = data.get('info', {}) devices = [] for condition in SENSOR_TYPES: device = GoogleHomeAlarm(hass.data[CLIENT], condition, discovery_info, info.get('name', NAME)) devices.append(device) async_add_entities(devices, True) class GoogleHomeAlarm(Entity): """Representation of a GoogleHomeAlarm.""" def __init__(self, client, condition, config, name): """Initialize the GoogleHomeAlarm sensor.""" self._host = config['host'] self._client = client self._condition = condition self._name = None self._state = None self._available = True self._name = "{} {}".format(name, SENSOR_TYPES[self._condition]) async def async_update(self): """Update the data.""" await self._client.update_alarms(self._host) data = self.hass.data[GOOGLEHOME_DOMAIN][self._host] alarms = data.get('alarms')[self._condition] if not alarms: self._available = False return self._available = True time_date = dt_util.utc_from_timestamp(min(element['fire_time'] for element in alarms) / 1000) self._state = time_date.isoformat() @property def state(self): """Return the state.""" return self._state @property def name(self): """Return the name.""" return self._name @property def device_class(self): """Return the device class.""" return DEVICE_CLASS_TIMESTAMP @property def available(self): """Return the availability state.""" return self._available @property def icon(self): """Return the icon.""" return ICON
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/googlehome/sensor.py
"""Support for Alexa skill service end point.""" import copy from datetime import datetime import logging import uuid from homeassistant.components import http from homeassistant.core import callback from homeassistant.helpers import template from .const import ( ATTR_MAIN_TEXT, ATTR_REDIRECTION_URL, ATTR_STREAM_URL, ATTR_TITLE_TEXT, ATTR_UID, ATTR_UPDATE_DATE, CONF_AUDIO, CONF_DISPLAY_URL, CONF_TEXT, CONF_TITLE, CONF_UID, DATE_FORMAT) _LOGGER = logging.getLogger(__name__) FLASH_BRIEFINGS_API_ENDPOINT = '/api/alexa/flash_briefings/{briefing_id}' @callback def async_setup(hass, flash_briefing_config): """Activate Alexa component.""" hass.http.register_view( AlexaFlashBriefingView(hass, flash_briefing_config)) class AlexaFlashBriefingView(http.HomeAssistantView): """Handle Alexa Flash Briefing skill requests.""" url = FLASH_BRIEFINGS_API_ENDPOINT name = 'api:alexa:flash_briefings' def __init__(self, hass, flash_briefings): """Initialize Alexa view.""" super().__init__() self.flash_briefings = copy.deepcopy(flash_briefings) template.attach(hass, self.flash_briefings) @callback def get(self, request, briefing_id): """Handle Alexa Flash Briefing request.""" _LOGGER.debug("Received Alexa flash briefing request for: %s", briefing_id) if self.flash_briefings.get(briefing_id) is None: err = "No configured Alexa flash briefing was found for: %s" _LOGGER.error(err, briefing_id) return b'', 404 briefing = [] for item in self.flash_briefings.get(briefing_id, []): output = {} if item.get(CONF_TITLE) is not None: if isinstance(item.get(CONF_TITLE), template.Template): output[ATTR_TITLE_TEXT] = item[CONF_TITLE].async_render() else: output[ATTR_TITLE_TEXT] = item.get(CONF_TITLE) if item.get(CONF_TEXT) is not None: if isinstance(item.get(CONF_TEXT), template.Template): output[ATTR_MAIN_TEXT] = item[CONF_TEXT].async_render() else: output[ATTR_MAIN_TEXT] = item.get(CONF_TEXT) uid = item.get(CONF_UID) if uid is None: uid = str(uuid.uuid4()) output[ATTR_UID] = uid if item.get(CONF_AUDIO) is not None: if isinstance(item.get(CONF_AUDIO), template.Template): output[ATTR_STREAM_URL] = item[CONF_AUDIO].async_render() else: output[ATTR_STREAM_URL] = item.get(CONF_AUDIO) if item.get(CONF_DISPLAY_URL) is not None: if isinstance(item.get(CONF_DISPLAY_URL), template.Template): output[ATTR_REDIRECTION_URL] = \ item[CONF_DISPLAY_URL].async_render() else: output[ATTR_REDIRECTION_URL] = item.get(CONF_DISPLAY_URL) output[ATTR_UPDATE_DATE] = datetime.now().strftime(DATE_FORMAT) briefing.append(output) return self.json(briefing)
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/alexa/flash_briefings.py
"""Get your own public IP address or that of any host.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) CONF_HOSTNAME = 'hostname' CONF_IPV6 = 'ipv6' CONF_RESOLVER = 'resolver' CONF_RESOLVER_IPV6 = 'resolver_ipv6' DEFAULT_HOSTNAME = 'myip.opendns.com' DEFAULT_IPV6 = False DEFAULT_NAME = 'myip' DEFAULT_RESOLVER = '208.67.222.222' DEFAULT_RESOLVER_IPV6 = '2620:0:ccc::2' SCAN_INTERVAL = timedelta(seconds=120) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_HOSTNAME, default=DEFAULT_HOSTNAME): cv.string, vol.Optional(CONF_RESOLVER, default=DEFAULT_RESOLVER): cv.string, vol.Optional(CONF_RESOLVER_IPV6, default=DEFAULT_RESOLVER_IPV6): cv.string, vol.Optional(CONF_IPV6, default=DEFAULT_IPV6): cv.boolean, }) async def async_setup_platform( hass, config, async_add_devices, discovery_info=None): """Set up the DNS IP sensor.""" hostname = config.get(CONF_HOSTNAME) name = config.get(CONF_NAME) if not name: if hostname == DEFAULT_HOSTNAME: name = DEFAULT_NAME else: name = hostname ipv6 = config.get(CONF_IPV6) if ipv6: resolver = config.get(CONF_RESOLVER_IPV6) else: resolver = config.get(CONF_RESOLVER) async_add_devices([WanIpSensor( hass, name, hostname, resolver, ipv6)], True) class WanIpSensor(Entity): """Implementation of a DNS IP sensor.""" def __init__(self, hass, name, hostname, resolver, ipv6): """Initialize the DNS IP sensor.""" import aiodns self.hass = hass self._name = name self.hostname = hostname self.resolver = aiodns.DNSResolver() self.resolver.nameservers = [resolver] self.querytype = 'AAAA' if ipv6 else 'A' self._state = None @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the current DNS IP address for hostname.""" return self._state async def async_update(self): """Get the current DNS IP address for hostname.""" from aiodns.error import DNSError try: response = await self.resolver.query( self.hostname, self.querytype) except DNSError as err: _LOGGER.warning("Exception while resolving host: %s", err) response = None if response: self._state = response[0].host else: self._state = None
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/dnsip/sensor.py
"""Support for the KIWI.KI lock platform.""" import logging import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.lock import (LockDevice, PLATFORM_SCHEMA) from homeassistant.const import ( CONF_PASSWORD, CONF_USERNAME, ATTR_ID, ATTR_LONGITUDE, ATTR_LATITUDE, STATE_LOCKED, STATE_UNLOCKED) from homeassistant.helpers.event import async_call_later from homeassistant.core import callback _LOGGER = logging.getLogger(__name__) ATTR_TYPE = 'hardware_type' ATTR_PERMISSION = 'permission' ATTR_CAN_INVITE = 'can_invite_others' UNLOCK_MAINTAIN_TIME = 5 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the KIWI lock platform.""" from kiwiki import KiwiClient, KiwiException try: kiwi = KiwiClient(config[CONF_USERNAME], config[CONF_PASSWORD]) except KiwiException as exc: _LOGGER.error(exc) return available_locks = kiwi.get_locks() if not available_locks: # No locks found; abort setup routine. _LOGGER.info("No KIWI locks found in your account.") return add_entities([KiwiLock(lock, kiwi) for lock in available_locks], True) class KiwiLock(LockDevice): """Representation of a Kiwi lock.""" def __init__(self, kiwi_lock, client): """Initialize the lock.""" self._sensor = kiwi_lock self._client = client self.lock_id = kiwi_lock['sensor_id'] self._state = STATE_LOCKED address = kiwi_lock.get('address') address.update({ ATTR_LATITUDE: address.pop('lat', None), ATTR_LONGITUDE: address.pop('lng', None) }) self._device_attrs = { ATTR_ID: self.lock_id, ATTR_TYPE: kiwi_lock.get('hardware_type'), ATTR_PERMISSION: kiwi_lock.get('highest_permission'), ATTR_CAN_INVITE: kiwi_lock.get('can_invite'), **address } @property def name(self): """Return the name of the lock.""" name = self._sensor.get('name') specifier = self._sensor['address'].get('specifier') return name or specifier @property def is_locked(self): """Return true if lock is locked.""" return self._state == STATE_LOCKED @property def device_state_attributes(self): """Return the device specific state attributes.""" return self._device_attrs @callback def clear_unlock_state(self, _): """Clear unlock state automatically.""" self._state = STATE_LOCKED self.async_schedule_update_ha_state() def unlock(self, **kwargs): """Unlock the device.""" from kiwiki import KiwiException try: self._client.open_door(self.lock_id) except KiwiException: _LOGGER.error("failed to open door") else: self._state = STATE_UNLOCKED self.hass.add_job( async_call_later, self.hass, UNLOCK_MAINTAIN_TIME, self.clear_unlock_state )
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/kiwi/lock.py
"""Support for showing the date and the time.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.core import callback from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_DISPLAY_OPTIONS from homeassistant.helpers.entity import Entity import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util from homeassistant.helpers.event import async_track_point_in_utc_time _LOGGER = logging.getLogger(__name__) TIME_STR_FORMAT = '%H:%M' OPTION_TYPES = { 'time': 'Time', 'date': 'Date', 'date_time': 'Date & Time', 'date_time_iso': 'Date & Time ISO', 'time_date': 'Time & Date', 'beat': 'Internet Time', 'time_utc': 'Time (UTC)', } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_DISPLAY_OPTIONS, default=['time']): vol.All(cv.ensure_list, [vol.In(OPTION_TYPES)]), }) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Time and Date sensor.""" if hass.config.time_zone is None: _LOGGER.error("Timezone is not set in Home Assistant configuration") return False devices = [] for variable in config[CONF_DISPLAY_OPTIONS]: device = TimeDateSensor(hass, variable) async_track_point_in_utc_time( hass, device.point_in_time_listener, device.get_next_interval()) devices.append(device) async_add_entities(devices, True) class TimeDateSensor(Entity): """Implementation of a Time and Date sensor.""" def __init__(self, hass, option_type): """Initialize the sensor.""" self._name = OPTION_TYPES[option_type] self.type = option_type self._state = None self.hass = hass self._update_internal_state(dt_util.utcnow()) @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def icon(self): """Icon to use in the frontend, if any.""" if 'date' in self.type and 'time' in self.type: return 'mdi:calendar-clock' if 'date' in self.type: return 'mdi:calendar' return 'mdi:clock' def get_next_interval(self, now=None): """Compute next time an update should occur.""" if now is None: now = dt_util.utcnow() if self.type == 'date': now = dt_util.start_of_local_day(dt_util.as_local(now)) return now + timedelta(seconds=86400) if self.type == 'beat': interval = 86.4 else: interval = 60 timestamp = int(dt_util.as_timestamp(now)) delta = interval - (timestamp % interval) return now + timedelta(seconds=delta) def _update_internal_state(self, time_date): time = dt_util.as_local(time_date).strftime(TIME_STR_FORMAT) time_utc = time_date.strftime(TIME_STR_FORMAT) date = dt_util.as_local(time_date).date().isoformat() # Calculate Swatch Internet Time. time_bmt = time_date + timedelta(hours=1) delta = timedelta( hours=time_bmt.hour, minutes=time_bmt.minute, seconds=time_bmt.second, microseconds=time_bmt.microsecond) beat = int((delta.seconds + delta.microseconds / 1000000.0) / 86.4) if self.type == 'time': self._state = time elif self.type == 'date': self._state = date elif self.type == 'date_time': self._state = '{}, {}'.format(date, time) elif self.type == 'time_date': self._state = '{}, {}'.format(time, date) elif self.type == 'time_utc': self._state = time_utc elif self.type == 'beat': self._state = '@{0:03d}'.format(beat) elif self.type == 'date_time_iso': self._state = dt_util.parse_datetime( '{} {}'.format(date, time)).isoformat() @callback def point_in_time_listener(self, time_date): """Get the latest data and update state.""" self._update_internal_state(time_date) self.async_schedule_update_ha_state() async_track_point_in_utc_time( self.hass, self.point_in_time_listener, self.get_next_interval())
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/time_date/sensor.py
"""Support for statistics for sensor values.""" import logging import statistics from collections import deque import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_NAME, CONF_ENTITY_ID, EVENT_HOMEASSISTANT_START, STATE_UNKNOWN, ATTR_UNIT_OF_MEASUREMENT) from homeassistant.core import callback from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_state_change from homeassistant.util import dt as dt_util from homeassistant.components.recorder.util import session_scope, execute _LOGGER = logging.getLogger(__name__) ATTR_AVERAGE_CHANGE = 'average_change' ATTR_CHANGE = 'change' ATTR_CHANGE_RATE = 'change_rate' ATTR_COUNT = 'count' ATTR_MAX_AGE = 'max_age' ATTR_MAX_VALUE = 'max_value' ATTR_MEAN = 'mean' ATTR_MEDIAN = 'median' ATTR_MIN_AGE = 'min_age' ATTR_MIN_VALUE = 'min_value' ATTR_SAMPLING_SIZE = 'sampling_size' ATTR_STANDARD_DEVIATION = 'standard_deviation' ATTR_TOTAL = 'total' ATTR_VARIANCE = 'variance' CONF_SAMPLING_SIZE = 'sampling_size' CONF_MAX_AGE = 'max_age' CONF_PRECISION = 'precision' DEFAULT_NAME = 'Stats' DEFAULT_SIZE = 20 DEFAULT_PRECISION = 2 ICON = 'mdi:calculator' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_SAMPLING_SIZE, default=DEFAULT_SIZE): vol.All(vol.Coerce(int), vol.Range(min=1)), vol.Optional(CONF_MAX_AGE): cv.time_period, vol.Optional(CONF_PRECISION, default=DEFAULT_PRECISION): vol.Coerce(int) }) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Statistics sensor.""" entity_id = config.get(CONF_ENTITY_ID) name = config.get(CONF_NAME) sampling_size = config.get(CONF_SAMPLING_SIZE) max_age = config.get(CONF_MAX_AGE, None) precision = config.get(CONF_PRECISION) async_add_entities([StatisticsSensor(entity_id, name, sampling_size, max_age, precision)], True) return True class StatisticsSensor(Entity): """Representation of a Statistics sensor.""" def __init__(self, entity_id, name, sampling_size, max_age, precision): """Initialize the Statistics sensor.""" self._entity_id = entity_id self.is_binary = self._entity_id.split('.')[0] == 'binary_sensor' if not self.is_binary: self._name = '{} {}'.format(name, ATTR_MEAN) else: self._name = '{} {}'.format(name, ATTR_COUNT) self._sampling_size = sampling_size self._max_age = max_age self._precision = precision self._unit_of_measurement = None self.states = deque(maxlen=self._sampling_size) self.ages = deque(maxlen=self._sampling_size) self.count = 0 self.mean = self.median = self.stdev = self.variance = None self.total = self.min = self.max = None self.min_age = self.max_age = None self.change = self.average_change = self.change_rate = None async def async_added_to_hass(self): """Register callbacks.""" @callback def async_stats_sensor_state_listener(entity, old_state, new_state): """Handle the sensor state changes.""" self._unit_of_measurement = new_state.attributes.get( ATTR_UNIT_OF_MEASUREMENT) self._add_state_to_queue(new_state) self.async_schedule_update_ha_state(True) @callback def async_stats_sensor_startup(event): """Add listener and get recorded state.""" _LOGGER.debug("Startup for %s", self.entity_id) async_track_state_change( self.hass, self._entity_id, async_stats_sensor_state_listener) if 'recorder' in self.hass.config.components: # Only use the database if it's configured self.hass.async_create_task( self._async_initialize_from_database() ) self.hass.bus.async_listen_once( EVENT_HOMEASSISTANT_START, async_stats_sensor_startup) def _add_state_to_queue(self, new_state): """Add the state to the queue.""" if new_state.state == STATE_UNKNOWN: return try: if self.is_binary: self.states.append(new_state.state) else: self.states.append(float(new_state.state)) self.ages.append(new_state.last_updated) except ValueError: _LOGGER.error("%s: parsing error, expected number and received %s", self.entity_id, new_state.state) @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self.mean if not self.is_binary else self.count @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self._unit_of_measurement if not self.is_binary else None @property def should_poll(self): """No polling needed.""" return False @property def device_state_attributes(self): """Return the state attributes of the sensor.""" if not self.is_binary: return { ATTR_SAMPLING_SIZE: self._sampling_size, ATTR_COUNT: self.count, ATTR_MEAN: self.mean, ATTR_MEDIAN: self.median, ATTR_STANDARD_DEVIATION: self.stdev, ATTR_VARIANCE: self.variance, ATTR_TOTAL: self.total, ATTR_MIN_VALUE: self.min, ATTR_MAX_VALUE: self.max, ATTR_MIN_AGE: self.min_age, ATTR_MAX_AGE: self.max_age, ATTR_CHANGE: self.change, ATTR_AVERAGE_CHANGE: self.average_change, ATTR_CHANGE_RATE: self.change_rate, } @property def icon(self): """Return the icon to use in the frontend, if any.""" return ICON def _purge_old(self): """Remove states which are older than self._max_age.""" now = dt_util.utcnow() _LOGGER.debug("%s: purging records older then %s(%s)", self.entity_id, dt_util.as_local(now - self._max_age), self._max_age) while self.ages and (now - self.ages[0]) > self._max_age: _LOGGER.debug("%s: purging record with datetime %s(%s)", self.entity_id, dt_util.as_local(self.ages[0]), (now - self.ages[0])) self.ages.popleft() self.states.popleft() async def async_update(self): """Get the latest data and updates the states.""" _LOGGER.debug("%s: updating statistics.", self.entity_id) if self._max_age is not None: self._purge_old() self.count = len(self.states) if not self.is_binary: try: # require only one data point self.mean = round(statistics.mean(self.states), self._precision) self.median = round(statistics.median(self.states), self._precision) except statistics.StatisticsError as err: _LOGGER.debug("%s: %s", self.entity_id, err) self.mean = self.median = STATE_UNKNOWN try: # require at least two data points self.stdev = round(statistics.stdev(self.states), self._precision) self.variance = round(statistics.variance(self.states), self._precision) except statistics.StatisticsError as err: _LOGGER.debug("%s: %s", self.entity_id, err) self.stdev = self.variance = STATE_UNKNOWN if self.states: self.total = round(sum(self.states), self._precision) self.min = round(min(self.states), self._precision) self.max = round(max(self.states), self._precision) self.min_age = self.ages[0] self.max_age = self.ages[-1] self.change = self.states[-1] - self.states[0] self.average_change = self.change self.change_rate = 0 if len(self.states) > 1: self.average_change /= len(self.states) - 1 time_diff = (self.max_age - self.min_age).total_seconds() if time_diff > 0: self.change_rate = self.average_change / time_diff self.change = round(self.change, self._precision) self.average_change = round(self.average_change, self._precision) self.change_rate = round(self.change_rate, self._precision) else: self.total = self.min = self.max = STATE_UNKNOWN self.min_age = self.max_age = dt_util.utcnow() self.change = self.average_change = STATE_UNKNOWN self.change_rate = STATE_UNKNOWN async def _async_initialize_from_database(self): """Initialize the list of states from the database. The query will get the list of states in DESCENDING order so that we can limit the result to self._sample_size. Afterwards reverse the list so that we get it in the right order again. If MaxAge is provided then query will restrict to entries younger then current datetime - MaxAge. """ from homeassistant.components.recorder.models import States _LOGGER.debug("%s: initializing values from the database", self.entity_id) with session_scope(hass=self.hass) as session: query = session.query(States)\ .filter(States.entity_id == self._entity_id.lower()) if self._max_age is not None: records_older_then = dt_util.utcnow() - self._max_age _LOGGER.debug("%s: retrieve records not older then %s", self.entity_id, records_older_then) query = query.filter(States.last_updated >= records_older_then) else: _LOGGER.debug("%s: retrieving all records.", self.entity_id) query = query\ .order_by(States.last_updated.desc())\ .limit(self._sampling_size) states = execute(query) for state in reversed(states): self._add_state_to_queue(state) self.async_schedule_update_ha_state(True) _LOGGER.debug("%s: initializing from database completed", self.entity_id)
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/statistics/sensor.py
"""Binary sensor support for Wireless Sensor Tags.""" import logging import voluptuous as vol from homeassistant.components.binary_sensor import ( PLATFORM_SCHEMA, BinarySensorDevice) from homeassistant.const import CONF_MONITORED_CONDITIONS, STATE_OFF, STATE_ON from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_connect from . import ( DOMAIN as WIRELESSTAG_DOMAIN, SIGNAL_BINARY_EVENT_UPDATE, WirelessTagBaseSensor) _LOGGER = logging.getLogger(__name__) # On means in range, Off means out of range SENSOR_PRESENCE = 'presence' # On means motion detected, Off means clear SENSOR_MOTION = 'motion' # On means open, Off means closed SENSOR_DOOR = 'door' # On means temperature become too cold, Off means normal SENSOR_COLD = 'cold' # On means hot, Off means normal SENSOR_HEAT = 'heat' # On means too dry (humidity), Off means normal SENSOR_DRY = 'dry' # On means too wet (humidity), Off means normal SENSOR_WET = 'wet' # On means light detected, Off means no light SENSOR_LIGHT = 'light' # On means moisture detected (wet), Off means no moisture (dry) SENSOR_MOISTURE = 'moisture' # On means tag battery is low, Off means normal SENSOR_BATTERY = 'battery' # Sensor types: Name, device_class, push notification type representing 'on', # attr to check SENSOR_TYPES = { SENSOR_PRESENCE: 'Presence', SENSOR_MOTION: 'Motion', SENSOR_DOOR: 'Door', SENSOR_COLD: 'Cold', SENSOR_HEAT: 'Heat', SENSOR_DRY: 'Too dry', SENSOR_WET: 'Too wet', SENSOR_LIGHT: 'Light', SENSOR_MOISTURE: 'Leak', SENSOR_BATTERY: 'Low Battery' } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_MONITORED_CONDITIONS, default=[]): vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]), }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the platform for a WirelessTags.""" platform = hass.data.get(WIRELESSTAG_DOMAIN) sensors = [] tags = platform.tags for tag in tags.values(): allowed_sensor_types = tag.supported_binary_events_types for sensor_type in config.get(CONF_MONITORED_CONDITIONS): if sensor_type in allowed_sensor_types: sensors.append(WirelessTagBinarySensor(platform, tag, sensor_type)) add_entities(sensors, True) hass.add_job(platform.install_push_notifications, sensors) class WirelessTagBinarySensor(WirelessTagBaseSensor, BinarySensorDevice): """A binary sensor implementation for WirelessTags.""" def __init__(self, api, tag, sensor_type): """Initialize a binary sensor for a Wireless Sensor Tags.""" super().__init__(api, tag) self._sensor_type = sensor_type self._name = '{0} {1}'.format(self._tag.name, self.event.human_readable_name) async def async_added_to_hass(self): """Register callbacks.""" tag_id = self.tag_id event_type = self.device_class mac = self.tag_manager_mac async_dispatcher_connect( self.hass, SIGNAL_BINARY_EVENT_UPDATE.format(tag_id, event_type, mac), self._on_binary_event_callback) @property def is_on(self): """Return True if the binary sensor is on.""" return self._state == STATE_ON @property def device_class(self): """Return the class of the binary sensor.""" return self._sensor_type @property def event(self): """Binary event of tag.""" return self._tag.event[self._sensor_type] @property def principal_value(self): """Return value of tag. Subclasses need override based on type of sensor. """ return STATE_ON if self.event.is_state_on else STATE_OFF def updated_state_value(self): """Use raw princial value.""" return self.principal_value @callback def _on_binary_event_callback(self, event): """Update state from arrived push notification.""" # state should be 'on' or 'off' self._state = event.data.get('state') self.async_schedule_update_ha_state()
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/wirelesstag/binary_sensor.py
# coding: utf-8 """Constants for the LCN component.""" from itertools import product from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT DOMAIN = 'lcn' DATA_LCN = 'lcn' DEFAULT_NAME = 'pchk' CONF_CONNECTIONS = 'connections' CONF_SK_NUM_TRIES = 'sk_num_tries' CONF_OUTPUT = 'output' CONF_DIM_MODE = 'dim_mode' CONF_DIMMABLE = 'dimmable' CONF_TRANSITION = 'transition' CONF_MOTOR = 'motor' CONF_LOCKABLE = 'lockable' CONF_VARIABLE = 'variable' CONF_VALUE = 'value' CONF_RELVARREF = 'value_reference' CONF_SOURCE = 'source' CONF_SETPOINT = 'setpoint' CONF_LED = 'led' CONF_KEYS = 'keys' CONF_TIME = 'time' CONF_TIME_UNIT = 'time_unit' CONF_TABLE = 'table' CONF_ROW = 'row' CONF_TEXT = 'text' CONF_PCK = 'pck' CONF_CLIMATES = 'climates' CONF_MAX_TEMP = 'max_temp' CONF_MIN_TEMP = 'min_temp' CONF_SCENES = 'scenes' CONF_REGISTER = 'register' CONF_SCENE = 'scene' CONF_OUTPUTS = 'outputs' DIM_MODES = ['STEPS50', 'STEPS200'] OUTPUT_PORTS = ['OUTPUT1', 'OUTPUT2', 'OUTPUT3', 'OUTPUT4'] RELAY_PORTS = ['RELAY1', 'RELAY2', 'RELAY3', 'RELAY4', 'RELAY5', 'RELAY6', 'RELAY7', 'RELAY8', 'MOTORONOFF1', 'MOTORUPDOWN1', 'MOTORONOFF2', 'MOTORUPDOWN2', 'MOTORONOFF3', 'MOTORUPDOWN3', 'MOTORONOFF4', 'MOTORUPDOWN4'] MOTOR_PORTS = ['MOTOR1', 'MOTOR2', 'MOTOR3', 'MOTOR4'] LED_PORTS = ['LED1', 'LED2', 'LED3', 'LED4', 'LED5', 'LED6', 'LED7', 'LED8', 'LED9', 'LED10', 'LED11', 'LED12'] LED_STATUS = ['OFF', 'ON', 'BLINK', 'FLICKER'] LOGICOP_PORTS = ['LOGICOP1', 'LOGICOP2', 'LOGICOP3', 'LOGICOP4'] BINSENSOR_PORTS = ['BINSENSOR1', 'BINSENSOR2', 'BINSENSOR3', 'BINSENSOR4', 'BINSENSOR5', 'BINSENSOR6', 'BINSENSOR7', 'BINSENSOR8'] KEYS = ['{:s}{:d}'.format(t[0], t[1]) for t in product(['A', 'B', 'C', 'D'], range(1, 9))] VARIABLES = ['VAR1ORTVAR', 'VAR2ORR1VAR', 'VAR3ORR2VAR', 'TVAR', 'R1VAR', 'R2VAR', 'VAR1', 'VAR2', 'VAR3', 'VAR4', 'VAR5', 'VAR6', 'VAR7', 'VAR8', 'VAR9', 'VAR10', 'VAR11', 'VAR12'] SETPOINTS = ['R1VARSETPOINT', 'R2VARSETPOINT'] THRESHOLDS = ['THRS1', 'THRS2', 'THRS3', 'THRS4', 'THRS5', 'THRS2_1', 'THRS2_2', 'THRS2_3', 'THRS2_4', 'THRS3_1', 'THRS3_2', 'THRS3_3', 'THRS3_4', 'THRS4_1', 'THRS4_2', 'THRS4_3', 'THRS4_4'] S0_INPUTS = ['S0INPUT1', 'S0INPUT2', 'S0INPUT3', 'S0INPUT4'] VAR_UNITS = ['', 'LCN', 'NATIVE', TEMP_CELSIUS, '°K', TEMP_FAHRENHEIT, 'LUX_T', 'LX_T', 'LUX_I', 'LUX', 'LX', 'M/S', 'METERPERSECOND', '%', 'PERCENT', 'PPM', 'VOLT', 'V', 'AMPERE', 'AMP', 'A', 'DEGREE', '°'] RELVARREF = ['CURRENT', 'PROG'] SENDKEYCOMMANDS = ['HIT', 'MAKE', 'BREAK', 'DONTSEND'] TIME_UNITS = ['SECONDS', 'SECOND', 'SEC', 'S', 'MINUTES', 'MINUTE', 'MIN', 'M', 'HOURS', 'HOUR', 'H', 'DAYS', 'DAY', 'D']
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/lcn/const.py
"""Support for OASA Telematics from telematics.oasa.gr.""" import logging from datetime import timedelta from operator import itemgetter import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_NAME, ATTR_ATTRIBUTION, DEVICE_CLASS_TIMESTAMP) from homeassistant.helpers.entity import Entity from homeassistant.util import dt as dt_util _LOGGER = logging.getLogger(__name__) ATTR_STOP_ID = 'stop_id' ATTR_STOP_NAME = 'stop_name' ATTR_ROUTE_ID = 'route_id' ATTR_ROUTE_NAME = 'route_name' ATTR_NEXT_ARRIVAL = 'next_arrival' ATTR_SECOND_NEXT_ARRIVAL = 'second_next_arrival' ATTR_NEXT_DEPARTURE = 'next_departure' ATTRIBUTION = "Data retrieved from telematics.oasa.gr" CONF_STOP_ID = 'stop_id' CONF_ROUTE_ID = 'route_id' DEFAULT_NAME = 'OASA Telematics' ICON = 'mdi:bus' SCAN_INTERVAL = timedelta(seconds=60) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_STOP_ID): cv.string, vol.Required(CONF_ROUTE_ID): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the OASA Telematics sensor.""" name = config[CONF_NAME] stop_id = config[CONF_STOP_ID] route_id = config.get(CONF_ROUTE_ID) data = OASATelematicsData(stop_id, route_id) add_entities([OASATelematicsSensor( data, stop_id, route_id, name)], True) class OASATelematicsSensor(Entity): """Implementation of the OASA Telematics sensor.""" def __init__(self, data, stop_id, route_id, name): """Initialize the sensor.""" self.data = data self._name = name self._stop_id = stop_id self._route_id = route_id self._name_data = self._times = self._state = None @property def name(self): """Return the name of the sensor.""" return self._name @property def device_class(self): """Return the class of this sensor.""" return DEVICE_CLASS_TIMESTAMP @property def state(self): """Return the state of the sensor.""" return self._state @property def device_state_attributes(self): """Return the state attributes.""" params = {} if self._times is not None: next_arrival_data = self._times[0] if ATTR_NEXT_ARRIVAL in next_arrival_data: next_arrival = next_arrival_data[ATTR_NEXT_ARRIVAL] params.update({ ATTR_NEXT_ARRIVAL: next_arrival.isoformat() }) if len(self._times) > 1: second_next_arrival_time = self._times[1][ATTR_NEXT_ARRIVAL] if second_next_arrival_time is not None: second_arrival = second_next_arrival_time params.update({ ATTR_SECOND_NEXT_ARRIVAL: second_arrival.isoformat() }) params.update({ ATTR_ROUTE_ID: self._times[0][ATTR_ROUTE_ID], ATTR_STOP_ID: self._stop_id, ATTR_ATTRIBUTION: ATTRIBUTION, }) params.update({ ATTR_ROUTE_NAME: self._name_data[ATTR_ROUTE_NAME], ATTR_STOP_NAME: self._name_data[ATTR_STOP_NAME] }) return {k: v for k, v in params.items() if v} @property def icon(self): """Icon to use in the frontend, if any.""" return ICON def update(self): """Get the latest data from OASA API and update the states.""" self.data.update() self._times = self.data.info self._name_data = self.data.name_data next_arrival_data = self._times[0] if ATTR_NEXT_ARRIVAL in next_arrival_data: self._state = next_arrival_data[ATTR_NEXT_ARRIVAL].isoformat() class OASATelematicsData(): """The class for handling data retrieval.""" def __init__(self, stop_id, route_id): """Initialize the data object.""" import oasatelematics self.stop_id = stop_id self.route_id = route_id self.info = self.empty_result() self.oasa_api = oasatelematics self.name_data = {ATTR_ROUTE_NAME: self.get_route_name(), ATTR_STOP_NAME: self.get_stop_name()} def empty_result(self): """Object returned when no arrivals are found.""" return [{ATTR_ROUTE_ID: self.route_id}] def get_route_name(self): """Get the route name from the API.""" try: route = self.oasa_api.getRouteName(self.route_id) if route: return route[0].get('route_departure_eng') except TypeError: _LOGGER.error("Cannot get route name from OASA API") return None def get_stop_name(self): """Get the stop name from the API.""" try: name_data = self.oasa_api.getStopNameAndXY(self.stop_id) if name_data: return name_data[0].get('stop_descr_matrix_eng') except TypeError: _LOGGER.error("Cannot get stop name from OASA API") return None def update(self): """Get the latest arrival data from telematics.oasa.gr API.""" self.info = [] results = self.oasa_api.getStopArrivals(self.stop_id) if not results: self.info = self.empty_result() return # Parse results results = [r for r in results if r.get('route_code') in self.route_id] current_time = dt_util.utcnow() for result in results: btime2 = result.get('btime2') if btime2 is not None: arrival_min = int(btime2) timestamp = current_time + timedelta(minutes=arrival_min) arrival_data = {ATTR_NEXT_ARRIVAL: timestamp, ATTR_ROUTE_ID: self.route_id} self.info.append(arrival_data) if not self.info: _LOGGER.debug("No arrivals with given parameters") self.info = self.empty_result() return # Sort the data by time sort = sorted(self.info, key=itemgetter(ATTR_NEXT_ARRIVAL)) self.info = sort
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/oasa_telematics/sensor.py
"""Support turning on/off motion detection on Hikvision cameras.""" import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_NAME, CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_PORT, STATE_OFF, STATE_ON) from homeassistant.helpers.entity import ToggleEntity import homeassistant.helpers.config_validation as cv # This is the last working version, please test before updating _LOGGING = logging.getLogger(__name__) DEFAULT_NAME = 'Hikvision Camera Motion Detection' DEFAULT_PASSWORD = '12345' DEFAULT_PORT = 80 DEFAULT_USERNAME = 'admin' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD, default=DEFAULT_PASSWORD): cv.string, vol.Optional(CONF_PORT): cv.port, vol.Optional(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up Hikvision camera.""" import hikvision.api from hikvision.error import HikvisionError, MissingParamError host = config.get(CONF_HOST) port = config.get(CONF_PORT) name = config.get(CONF_NAME) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) try: hikvision_cam = hikvision.api.CreateDevice( host, port=port, username=username, password=password, is_https=False) except MissingParamError as param_err: _LOGGING.error("Missing required param: %s", param_err) return False except HikvisionError as conn_err: _LOGGING.error("Unable to connect: %s", conn_err) return False add_entities([HikvisionMotionSwitch(name, hikvision_cam)]) class HikvisionMotionSwitch(ToggleEntity): """Representation of a switch to toggle on/off motion detection.""" def __init__(self, name, hikvision_cam): """Initialize the switch.""" self._name = name self._hikvision_cam = hikvision_cam self._state = STATE_OFF @property def should_poll(self): """Poll for status regularly.""" return True @property def name(self): """Return the name of the device if any.""" return self._name @property def state(self): """Return the state of the device if any.""" return self._state @property def is_on(self): """Return true if device is on.""" return self._state == STATE_ON def turn_on(self, **kwargs): """Turn the device on.""" _LOGGING.info("Turning on Motion Detection ") self._hikvision_cam.enable_motion_detection() def turn_off(self, **kwargs): """Turn the device off.""" _LOGGING.info("Turning off Motion Detection ") self._hikvision_cam.disable_motion_detection() def update(self): """Update Motion Detection state.""" enabled = self._hikvision_cam.is_motion_detection_enabled() _LOGGING.info("enabled: %s", enabled) self._state = STATE_ON if enabled else STATE_OFF
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/hikvisioncam/switch.py
"""Each ElkM1 area will be created as a separate alarm_control_panel.""" import voluptuous as vol import homeassistant.components.alarm_control_panel as alarm from homeassistant.const import ( ATTR_CODE, ATTR_ENTITY_ID, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_NIGHT, STATE_ALARM_ARMING, STATE_ALARM_DISARMED, STATE_ALARM_PENDING, STATE_ALARM_TRIGGERED) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, async_dispatcher_send) from . import DOMAIN as ELK_DOMAIN, ElkEntity, create_elk_entities SIGNAL_ARM_ENTITY = 'elkm1_arm' SIGNAL_DISPLAY_MESSAGE = 'elkm1_display_message' ELK_ALARM_SERVICE_SCHEMA = vol.Schema({ vol.Required(ATTR_ENTITY_ID, default=[]): cv.entity_ids, vol.Required(ATTR_CODE): vol.All(vol.Coerce(int), vol.Range(0, 999999)), }) DISPLAY_MESSAGE_SERVICE_SCHEMA = vol.Schema({ vol.Optional(ATTR_ENTITY_ID, default=[]): cv.entity_ids, vol.Optional('clear', default=2): vol.In([0, 1, 2]), vol.Optional('beep', default=False): cv.boolean, vol.Optional('timeout', default=0): vol.Range(min=0, max=65535), vol.Optional('line1', default=''): cv.string, vol.Optional('line2', default=''): cv.string, }) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the ElkM1 alarm platform.""" if discovery_info is None: return elk = hass.data[ELK_DOMAIN]['elk'] entities = create_elk_entities(hass, elk.areas, 'area', ElkArea, []) async_add_entities(entities, True) def _dispatch(signal, entity_ids, *args): for entity_id in entity_ids: async_dispatcher_send( hass, '{}_{}'.format(signal, entity_id), *args) def _arm_service(service): entity_ids = service.data.get(ATTR_ENTITY_ID, []) arm_level = _arm_services().get(service.service) args = (arm_level, service.data.get(ATTR_CODE)) _dispatch(SIGNAL_ARM_ENTITY, entity_ids, *args) for service in _arm_services(): hass.services.async_register( alarm.DOMAIN, service, _arm_service, ELK_ALARM_SERVICE_SCHEMA) def _display_message_service(service): entity_ids = service.data.get(ATTR_ENTITY_ID, []) data = service.data args = (data['clear'], data['beep'], data['timeout'], data['line1'], data['line2']) _dispatch(SIGNAL_DISPLAY_MESSAGE, entity_ids, *args) hass.services.async_register( alarm.DOMAIN, 'elkm1_alarm_display_message', _display_message_service, DISPLAY_MESSAGE_SERVICE_SCHEMA) def _arm_services(): from elkm1_lib.const import ArmLevel return { 'elkm1_alarm_arm_vacation': ArmLevel.ARMED_VACATION.value, 'elkm1_alarm_arm_home_instant': ArmLevel.ARMED_STAY_INSTANT.value, 'elkm1_alarm_arm_night_instant': ArmLevel.ARMED_NIGHT_INSTANT.value, } class ElkArea(ElkEntity, alarm.AlarmControlPanel): """Representation of an Area / Partition within the ElkM1 alarm panel.""" def __init__(self, element, elk, elk_data): """Initialize Area as Alarm Control Panel.""" super().__init__(element, elk, elk_data) self._changed_by_entity_id = '' self._state = None async def async_added_to_hass(self): """Register callback for ElkM1 changes.""" await super().async_added_to_hass() for keypad in self._elk.keypads: keypad.add_callback(self._watch_keypad) async_dispatcher_connect( self.hass, '{}_{}'.format(SIGNAL_ARM_ENTITY, self.entity_id), self._arm_service) async_dispatcher_connect( self.hass, '{}_{}'.format(SIGNAL_DISPLAY_MESSAGE, self.entity_id), self._display_message) def _watch_keypad(self, keypad, changeset): if keypad.area != self._element.index: return if changeset.get('last_user') is not None: self._changed_by_entity_id = self.hass.data[ ELK_DOMAIN]['keypads'].get(keypad.index, '') self.async_schedule_update_ha_state(True) @property def code_format(self): """Return the alarm code format.""" return alarm.FORMAT_NUMBER @property def state(self): """Return the state of the element.""" return self._state @property def device_state_attributes(self): """Attributes of the area.""" from elkm1_lib.const import AlarmState, ArmedStatus, ArmUpState attrs = self.initial_attrs() elmt = self._element attrs['is_exit'] = elmt.is_exit attrs['timer1'] = elmt.timer1 attrs['timer2'] = elmt.timer2 if elmt.armed_status is not None: attrs['armed_status'] = \ ArmedStatus(elmt.armed_status).name.lower() if elmt.arm_up_state is not None: attrs['arm_up_state'] = ArmUpState(elmt.arm_up_state).name.lower() if elmt.alarm_state is not None: attrs['alarm_state'] = AlarmState(elmt.alarm_state).name.lower() attrs['changed_by_entity_id'] = self._changed_by_entity_id return attrs def _element_changed(self, element, changeset): from elkm1_lib.const import ArmedStatus elk_state_to_hass_state = { ArmedStatus.DISARMED.value: STATE_ALARM_DISARMED, ArmedStatus.ARMED_AWAY.value: STATE_ALARM_ARMED_AWAY, ArmedStatus.ARMED_STAY.value: STATE_ALARM_ARMED_HOME, ArmedStatus.ARMED_STAY_INSTANT.value: STATE_ALARM_ARMED_HOME, ArmedStatus.ARMED_TO_NIGHT.value: STATE_ALARM_ARMED_NIGHT, ArmedStatus.ARMED_TO_NIGHT_INSTANT.value: STATE_ALARM_ARMED_NIGHT, ArmedStatus.ARMED_TO_VACATION.value: STATE_ALARM_ARMED_AWAY, } if self._element.alarm_state is None: self._state = None elif self._area_is_in_alarm_state(): self._state = STATE_ALARM_TRIGGERED elif self._entry_exit_timer_is_running(): self._state = STATE_ALARM_ARMING \ if self._element.is_exit else STATE_ALARM_PENDING else: self._state = elk_state_to_hass_state[self._element.armed_status] def _entry_exit_timer_is_running(self): return self._element.timer1 > 0 or self._element.timer2 > 0 def _area_is_in_alarm_state(self): from elkm1_lib.const import AlarmState return self._element.alarm_state >= AlarmState.FIRE_ALARM.value async def async_alarm_disarm(self, code=None): """Send disarm command.""" self._element.disarm(int(code)) async def async_alarm_arm_home(self, code=None): """Send arm home command.""" from elkm1_lib.const import ArmLevel self._element.arm(ArmLevel.ARMED_STAY.value, int(code)) async def async_alarm_arm_away(self, code=None): """Send arm away command.""" from elkm1_lib.const import ArmLevel self._element.arm(ArmLevel.ARMED_AWAY.value, int(code)) async def async_alarm_arm_night(self, code=None): """Send arm night command.""" from elkm1_lib.const import ArmLevel self._element.arm(ArmLevel.ARMED_NIGHT.value, int(code)) async def _arm_service(self, arm_level, code): self._element.arm(arm_level, code) async def _display_message(self, clear, beep, timeout, line1, line2): """Display a message on all keypads for the area.""" self._element.display_message(clear, beep, timeout, line1, line2)
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/elkm1/alarm_control_panel.py
"""Support for LCN lights.""" import pypck from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_TRANSITION, SUPPORT_BRIGHTNESS, SUPPORT_TRANSITION, Light) from homeassistant.const import CONF_ADDRESS from . import LcnDevice from .const import ( CONF_CONNECTIONS, CONF_DIMMABLE, CONF_OUTPUT, CONF_TRANSITION, DATA_LCN, OUTPUT_PORTS) from .helpers import get_connection async def async_setup_platform( hass, hass_config, async_add_entities, discovery_info=None): """Set up the LCN light platform.""" if discovery_info is None: return devices = [] for config in discovery_info: address, connection_id = config[CONF_ADDRESS] addr = pypck.lcn_addr.LcnAddr(*address) connections = hass.data[DATA_LCN][CONF_CONNECTIONS] connection = get_connection(connections, connection_id) address_connection = connection.get_address_conn(addr) if config[CONF_OUTPUT] in OUTPUT_PORTS: device = LcnOutputLight(config, address_connection) else: # in RELAY_PORTS device = LcnRelayLight(config, address_connection) devices.append(device) async_add_entities(devices) class LcnOutputLight(LcnDevice, Light): """Representation of a LCN light for output ports.""" def __init__(self, config, address_connection): """Initialize the LCN light.""" super().__init__(config, address_connection) self.output = pypck.lcn_defs.OutputPort[config[CONF_OUTPUT]] self._transition = pypck.lcn_defs.time_to_ramp_value( config[CONF_TRANSITION]) self.dimmable = config[CONF_DIMMABLE] self._brightness = 255 self._is_on = None self._is_dimming_to_zero = False async def async_added_to_hass(self): """Run when entity about to be added to hass.""" await super().async_added_to_hass() await self.address_connection.activate_status_request_handler( self.output) @property def supported_features(self): """Flag supported features.""" features = SUPPORT_TRANSITION if self.dimmable: features |= SUPPORT_BRIGHTNESS return features @property def brightness(self): """Return the brightness of this light between 0..255.""" return self._brightness @property def is_on(self): """Return True if entity is on.""" return self._is_on async def async_turn_on(self, **kwargs): """Turn the entity on.""" self._is_on = True self._is_dimming_to_zero = False if ATTR_BRIGHTNESS in kwargs: percent = int(kwargs[ATTR_BRIGHTNESS] / 255. * 100) else: percent = 100 if ATTR_TRANSITION in kwargs: transition = pypck.lcn_defs.time_to_ramp_value( kwargs[ATTR_TRANSITION] * 1000) else: transition = self._transition self.address_connection.dim_output(self.output.value, percent, transition) await self.async_update_ha_state() async def async_turn_off(self, **kwargs): """Turn the entity off.""" self._is_on = False if ATTR_TRANSITION in kwargs: transition = pypck.lcn_defs.time_to_ramp_value( kwargs[ATTR_TRANSITION] * 1000) else: transition = self._transition self._is_dimming_to_zero = bool(transition) self.address_connection.dim_output(self.output.value, 0, transition) await self.async_update_ha_state() def input_received(self, input_obj): """Set light state when LCN input object (command) is received.""" if not isinstance(input_obj, pypck.inputs.ModStatusOutput) or \ input_obj.get_output_id() != self.output.value: return self._brightness = int(input_obj.get_percent() / 100.*255) if self.brightness == 0: self._is_dimming_to_zero = False if not self._is_dimming_to_zero: self._is_on = self.brightness > 0 self.async_schedule_update_ha_state() class LcnRelayLight(LcnDevice, Light): """Representation of a LCN light for relay ports.""" def __init__(self, config, address_connection): """Initialize the LCN light.""" super().__init__(config, address_connection) self.output = pypck.lcn_defs.RelayPort[config[CONF_OUTPUT]] self._is_on = None async def async_added_to_hass(self): """Run when entity about to be added to hass.""" await super().async_added_to_hass() await self.address_connection.activate_status_request_handler( self.output) @property def is_on(self): """Return True if entity is on.""" return self._is_on async def async_turn_on(self, **kwargs): """Turn the entity on.""" self._is_on = True states = [pypck.lcn_defs.RelayStateModifier.NOCHANGE] * 8 states[self.output.value] = pypck.lcn_defs.RelayStateModifier.ON self.address_connection.control_relays(states) await self.async_update_ha_state() async def async_turn_off(self, **kwargs): """Turn the entity off.""" self._is_on = False states = [pypck.lcn_defs.RelayStateModifier.NOCHANGE] * 8 states[self.output.value] = pypck.lcn_defs.RelayStateModifier.OFF self.address_connection.control_relays(states) await self.async_update_ha_state() def input_received(self, input_obj): """Set light state when LCN input object (command) is received.""" if not isinstance(input_obj, pypck.inputs.ModStatusRelays): return self._is_on = input_obj.get_state(self.output.value) self.async_schedule_update_ha_state()
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/lcn/light.py
"""Support for Lutron scenes.""" import logging from homeassistant.components.scene import Scene from . import LUTRON_CONTROLLER, LUTRON_DEVICES, LutronDevice _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Lutron scenes.""" devs = [] for scene_data in hass.data[LUTRON_DEVICES]['scene']: (area_name, keypad_name, device, led) = scene_data dev = LutronScene(area_name, keypad_name, device, led, hass.data[LUTRON_CONTROLLER]) devs.append(dev) add_entities(devs, True) class LutronScene(LutronDevice, Scene): """Representation of a Lutron Scene.""" def __init__( self, area_name, keypad_name, lutron_device, lutron_led, controller): """Initialize the scene/button.""" super().__init__(area_name, lutron_device, controller) self._keypad_name = keypad_name self._led = lutron_led def activate(self): """Activate the scene.""" self._lutron_device.press() @property def name(self): """Return the name of the device.""" return "{} {}: {}".format( self._area_name, self._keypad_name, self._lutron_device.name)
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/lutron/scene.py
"""Support for transport.opendata.ch.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity import homeassistant.util.dt as dt_util _LOGGER = logging.getLogger(__name__) ATTR_DEPARTURE_TIME1 = 'next_departure' ATTR_DEPARTURE_TIME2 = 'next_on_departure' ATTR_DURATION = 'duration' ATTR_PLATFORM = 'platform' ATTR_REMAINING_TIME = 'remaining_time' ATTR_START = 'start' ATTR_TARGET = 'destination' ATTR_TRAIN_NUMBER = 'train_number' ATTR_TRANSFERS = 'transfers' ATTRIBUTION = "Data provided by transport.opendata.ch" CONF_DESTINATION = 'to' CONF_START = 'from' DEFAULT_NAME = 'Next Departure' ICON = 'mdi:bus' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_DESTINATION): cv.string, vol.Required(CONF_START): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, }) async def async_setup_platform( hass, config, async_add_entities, discovery_info=None): """Set up the Swiss public transport sensor.""" from opendata_transport import OpendataTransport, exceptions name = config.get(CONF_NAME) start = config.get(CONF_START) destination = config.get(CONF_DESTINATION) session = async_get_clientsession(hass) opendata = OpendataTransport(start, destination, hass.loop, session) try: await opendata.async_get_data() except exceptions.OpendataTransportError: _LOGGER.error( "Check at http://transport.opendata.ch/examples/stationboard.html " "if your station names are valid") return async_add_entities( [SwissPublicTransportSensor(opendata, start, destination, name)]) class SwissPublicTransportSensor(Entity): """Implementation of an Swiss public transport sensor.""" def __init__(self, opendata, start, destination, name): """Initialize the sensor.""" self._opendata = opendata self._name = name self._from = start self._to = destination self._remaining_time = "" @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._opendata.connections[0]['departure'] \ if self._opendata is not None else None @property def device_state_attributes(self): """Return the state attributes.""" if self._opendata is None: return self._remaining_time = dt_util.parse_datetime( self._opendata.connections[0]['departure']) -\ dt_util.as_local(dt_util.utcnow()) attr = { ATTR_TRAIN_NUMBER: self._opendata.connections[0]['number'], ATTR_PLATFORM: self._opendata.connections[0]['platform'], ATTR_TRANSFERS: self._opendata.connections[0]['transfers'], ATTR_DURATION: self._opendata.connections[0]['duration'], ATTR_DEPARTURE_TIME1: self._opendata.connections[1]['departure'], ATTR_DEPARTURE_TIME2: self._opendata.connections[2]['departure'], ATTR_START: self._opendata.from_name, ATTR_TARGET: self._opendata.to_name, ATTR_REMAINING_TIME: '{}'.format(self._remaining_time), ATTR_ATTRIBUTION: ATTRIBUTION, } return attr @property def icon(self): """Icon to use in the frontend, if any.""" return ICON async def async_update(self): """Get the latest data from opendata.ch and update the states.""" from opendata_transport.exceptions import OpendataTransportError try: if self._remaining_time.total_seconds() < 0: await self._opendata.async_get_data() except OpendataTransportError: _LOGGER.error("Unable to retrieve data from transport.opendata.ch")
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/swiss_public_transport/sensor.py
"""Class to hold all alarm control panel accessories.""" import logging from pyhap.const import CATEGORY_ALARM_SYSTEM from homeassistant.components.alarm_control_panel import DOMAIN from homeassistant.const import ( ATTR_CODE, ATTR_ENTITY_ID, SERVICE_ALARM_ARM_AWAY, SERVICE_ALARM_ARM_HOME, SERVICE_ALARM_ARM_NIGHT, SERVICE_ALARM_DISARM, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_NIGHT, STATE_ALARM_DISARMED, STATE_ALARM_TRIGGERED) from . import TYPES from .accessories import HomeAccessory from .const import ( CHAR_CURRENT_SECURITY_STATE, CHAR_TARGET_SECURITY_STATE, SERV_SECURITY_SYSTEM) _LOGGER = logging.getLogger(__name__) HASS_TO_HOMEKIT = { STATE_ALARM_ARMED_HOME: 0, STATE_ALARM_ARMED_AWAY: 1, STATE_ALARM_ARMED_NIGHT: 2, STATE_ALARM_DISARMED: 3, STATE_ALARM_TRIGGERED: 4, } HOMEKIT_TO_HASS = {c: s for s, c in HASS_TO_HOMEKIT.items()} STATE_TO_SERVICE = { STATE_ALARM_ARMED_AWAY: SERVICE_ALARM_ARM_AWAY, STATE_ALARM_ARMED_HOME: SERVICE_ALARM_ARM_HOME, STATE_ALARM_ARMED_NIGHT: SERVICE_ALARM_ARM_NIGHT, STATE_ALARM_DISARMED: SERVICE_ALARM_DISARM, } @TYPES.register('SecuritySystem') class SecuritySystem(HomeAccessory): """Generate an SecuritySystem accessory for an alarm control panel.""" def __init__(self, *args): """Initialize a SecuritySystem accessory object.""" super().__init__(*args, category=CATEGORY_ALARM_SYSTEM) self._alarm_code = self.config.get(ATTR_CODE) self._flag_state = False serv_alarm = self.add_preload_service(SERV_SECURITY_SYSTEM) self.char_current_state = serv_alarm.configure_char( CHAR_CURRENT_SECURITY_STATE, value=3) self.char_target_state = serv_alarm.configure_char( CHAR_TARGET_SECURITY_STATE, value=3, setter_callback=self.set_security_state) def set_security_state(self, value): """Move security state to value if call came from HomeKit.""" _LOGGER.debug('%s: Set security state to %d', self.entity_id, value) self._flag_state = True hass_value = HOMEKIT_TO_HASS[value] service = STATE_TO_SERVICE[hass_value] params = {ATTR_ENTITY_ID: self.entity_id} if self._alarm_code: params[ATTR_CODE] = self._alarm_code self.call_service(DOMAIN, service, params) def update_state(self, new_state): """Update security state after state changed.""" hass_state = new_state.state if hass_state in HASS_TO_HOMEKIT: current_security_state = HASS_TO_HOMEKIT[hass_state] self.char_current_state.set_value(current_security_state) _LOGGER.debug('%s: Updated current state to %s (%d)', self.entity_id, hass_state, current_security_state) # SecuritySystemTargetState does not support triggered if not self._flag_state and \ hass_state != STATE_ALARM_TRIGGERED: self.char_target_state.set_value(current_security_state) self._flag_state = False
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/homekit/type_security_systems.py
"""Support for WeMo binary sensors.""" import asyncio import logging import async_timeout import requests from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.exceptions import PlatformNotReady from . import SUBSCRIPTION_REGISTRY _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Register discovered WeMo binary sensors.""" from pywemo import discovery if discovery_info is not None: location = discovery_info['ssdp_description'] mac = discovery_info['mac_address'] try: device = discovery.device_from_description(location, mac) except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as err: _LOGGER.error('Unable to access %s (%s)', location, err) raise PlatformNotReady if device: add_entities([WemoBinarySensor(hass, device)]) class WemoBinarySensor(BinarySensorDevice): """Representation a WeMo binary sensor.""" def __init__(self, hass, device): """Initialize the WeMo sensor.""" self.wemo = device self._state = None self._available = True self._update_lock = None self._model_name = self.wemo.model_name self._name = self.wemo.name self._serialnumber = self.wemo.serialnumber def _subscription_callback(self, _device, _type, _params): """Update the state by the Wemo sensor.""" _LOGGER.debug("Subscription update for %s", self.name) updated = self.wemo.subscription_update(_type, _params) self.hass.add_job( self._async_locked_subscription_callback(not updated)) async def _async_locked_subscription_callback(self, force_update): """Handle an update from a subscription.""" # If an update is in progress, we don't do anything if self._update_lock.locked(): return await self._async_locked_update(force_update) self.async_schedule_update_ha_state() async def async_added_to_hass(self): """Wemo sensor added to HASS.""" # Define inside async context so we know our event loop self._update_lock = asyncio.Lock() registry = SUBSCRIPTION_REGISTRY await self.hass.async_add_executor_job(registry.register, self.wemo) registry.on(self.wemo, None, self._subscription_callback) async def async_update(self): """Update WeMo state. Wemo has an aggressive retry logic that sometimes can take over a minute to return. If we don't get a state after 5 seconds, assume the Wemo sensor is unreachable. If update goes through, it will be made available again. """ # If an update is in progress, we don't do anything if self._update_lock.locked(): return try: with async_timeout.timeout(5): await asyncio.shield(self._async_locked_update(True)) except asyncio.TimeoutError: _LOGGER.warning('Lost connection to %s', self.name) self._available = False async def _async_locked_update(self, force_update): """Try updating within an async lock.""" async with self._update_lock: await self.hass.async_add_executor_job(self._update, force_update) def _update(self, force_update=True): """Update the sensor state.""" try: self._state = self.wemo.get_state(force_update) if not self._available: _LOGGER.info('Reconnected to %s', self.name) self._available = True except AttributeError as err: _LOGGER.warning("Could not update status for %s (%s)", self.name, err) self._available = False @property def unique_id(self): """Return the id of this WeMo sensor.""" return self._serialnumber @property def name(self): """Return the name of the service if any.""" return self._name @property def is_on(self): """Return true if sensor is on.""" return self._state @property def available(self): """Return true if sensor is available.""" return self._available
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/wemo/binary_sensor.py
"""Support for Fast.com internet speed testing sensor.""" import logging from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.restore_state import RestoreEntity from . import DATA_UPDATED, DOMAIN as FASTDOTCOM_DOMAIN _LOGGER = logging.getLogger(__name__) ICON = 'mdi:speedometer' UNIT_OF_MEASUREMENT = 'Mbit/s' async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Fast.com sensor.""" async_add_entities([SpeedtestSensor(hass.data[FASTDOTCOM_DOMAIN])]) class SpeedtestSensor(RestoreEntity): """Implementation of a FAst.com sensor.""" def __init__(self, speedtest_data): """Initialize the sensor.""" self._name = 'Fast.com Download' self.speedtest_client = speedtest_data self._state = None @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the device.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return UNIT_OF_MEASUREMENT @property def icon(self): """Return icon.""" return ICON @property def should_poll(self): """Return the polling requirement for this sensor.""" return False async def async_added_to_hass(self): """Handle entity which will be added.""" await super().async_added_to_hass() state = await self.async_get_last_state() if not state: return self._state = state.state async_dispatcher_connect( self.hass, DATA_UPDATED, self._schedule_immediate_update ) def update(self): """Get the latest data and update the states.""" data = self.speedtest_client.data if data is None: return self._state = data['download'] @callback def _schedule_immediate_update(self): self.async_schedule_update_ha_state(True)
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/fastdotcom/sensor.py
"""Support for OpenUV sensors.""" import logging from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.util.dt import as_local, parse_datetime from . import ( DATA_OPENUV_CLIENT, DATA_UV, DOMAIN, SENSORS, TOPIC_UPDATE, TYPE_CURRENT_OZONE_LEVEL, TYPE_CURRENT_UV_INDEX, TYPE_CURRENT_UV_LEVEL, TYPE_MAX_UV_INDEX, TYPE_SAFE_EXPOSURE_TIME_1, TYPE_SAFE_EXPOSURE_TIME_2, TYPE_SAFE_EXPOSURE_TIME_3, TYPE_SAFE_EXPOSURE_TIME_4, TYPE_SAFE_EXPOSURE_TIME_5, TYPE_SAFE_EXPOSURE_TIME_6, OpenUvEntity) _LOGGER = logging.getLogger(__name__) ATTR_MAX_UV_TIME = 'time' EXPOSURE_TYPE_MAP = { TYPE_SAFE_EXPOSURE_TIME_1: 'st1', TYPE_SAFE_EXPOSURE_TIME_2: 'st2', TYPE_SAFE_EXPOSURE_TIME_3: 'st3', TYPE_SAFE_EXPOSURE_TIME_4: 'st4', TYPE_SAFE_EXPOSURE_TIME_5: 'st5', TYPE_SAFE_EXPOSURE_TIME_6: 'st6' } UV_LEVEL_EXTREME = 'Extreme' UV_LEVEL_VHIGH = 'Very High' UV_LEVEL_HIGH = 'High' UV_LEVEL_MODERATE = 'Moderate' UV_LEVEL_LOW = 'Low' async def async_setup_platform( hass, config, async_add_entities, discovery_info=None): """Set up an OpenUV sensor based on existing config.""" pass async def async_setup_entry(hass, entry, async_add_entities): """Set up a Nest sensor based on a config entry.""" openuv = hass.data[DOMAIN][DATA_OPENUV_CLIENT][entry.entry_id] sensors = [] for sensor_type in openuv.sensor_conditions: name, icon, unit = SENSORS[sensor_type] sensors.append( OpenUvSensor( openuv, sensor_type, name, icon, unit, entry.entry_id)) async_add_entities(sensors, True) class OpenUvSensor(OpenUvEntity): """Define a binary sensor for OpenUV.""" def __init__(self, openuv, sensor_type, name, icon, unit, entry_id): """Initialize the sensor.""" super().__init__(openuv) self._async_unsub_dispatcher_connect = None self._entry_id = entry_id self._icon = icon self._latitude = openuv.client.latitude self._longitude = openuv.client.longitude self._name = name self._sensor_type = sensor_type self._state = None self._unit = unit @property def icon(self): """Return the icon.""" return self._icon @property def should_poll(self): """Disable polling.""" return False @property def state(self): """Return the status of the sensor.""" return self._state @property def unique_id(self) -> str: """Return a unique, HASS-friendly identifier for this entity.""" return '{0}_{1}_{2}'.format( self._latitude, self._longitude, self._sensor_type) @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self._unit async def async_added_to_hass(self): """Register callbacks.""" @callback def update(): """Update the state.""" self.async_schedule_update_ha_state(True) self._async_unsub_dispatcher_connect = async_dispatcher_connect( self.hass, TOPIC_UPDATE, update) async def async_will_remove_from_hass(self): """Disconnect dispatcher listener when removed.""" if self._async_unsub_dispatcher_connect: self._async_unsub_dispatcher_connect() async def async_update(self): """Update the state.""" data = self.openuv.data[DATA_UV]['result'] if self._sensor_type == TYPE_CURRENT_OZONE_LEVEL: self._state = data['ozone'] elif self._sensor_type == TYPE_CURRENT_UV_INDEX: self._state = data['uv'] elif self._sensor_type == TYPE_CURRENT_UV_LEVEL: if data['uv'] >= 11: self._state = UV_LEVEL_EXTREME elif data['uv'] >= 8: self._state = UV_LEVEL_VHIGH elif data['uv'] >= 6: self._state = UV_LEVEL_HIGH elif data['uv'] >= 3: self._state = UV_LEVEL_MODERATE else: self._state = UV_LEVEL_LOW elif self._sensor_type == TYPE_MAX_UV_INDEX: self._state = data['uv_max'] self._attrs.update({ ATTR_MAX_UV_TIME: as_local(parse_datetime(data['uv_max_time'])) }) elif self._sensor_type in (TYPE_SAFE_EXPOSURE_TIME_1, TYPE_SAFE_EXPOSURE_TIME_2, TYPE_SAFE_EXPOSURE_TIME_3, TYPE_SAFE_EXPOSURE_TIME_4, TYPE_SAFE_EXPOSURE_TIME_5, TYPE_SAFE_EXPOSURE_TIME_6): self._state = data['safe_exposure_time'][EXPOSURE_TYPE_MAP[ self._sensor_type]]
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/openuv/sensor.py
""" Support for MQTT Template lights. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/light.mqtt_template/ """ import logging import voluptuous as vol from homeassistant.core import callback from homeassistant.components import mqtt from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_FLASH, ATTR_HS_COLOR, ATTR_TRANSITION, ATTR_WHITE_VALUE, Light, SUPPORT_BRIGHTNESS, SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_FLASH, SUPPORT_COLOR, SUPPORT_TRANSITION, SUPPORT_WHITE_VALUE) from homeassistant.const import ( CONF_DEVICE, CONF_NAME, CONF_OPTIMISTIC, STATE_ON, STATE_OFF) from homeassistant.components.mqtt import ( CONF_COMMAND_TOPIC, CONF_QOS, CONF_RETAIN, CONF_STATE_TOPIC, CONF_UNIQUE_ID, MqttAttributes, MqttAvailability, MqttDiscoveryUpdate, MqttEntityDeviceInfo, subscription) import homeassistant.helpers.config_validation as cv import homeassistant.util.color as color_util from homeassistant.helpers.restore_state import RestoreEntity from . import MQTT_LIGHT_SCHEMA_SCHEMA _LOGGER = logging.getLogger(__name__) DOMAIN = 'mqtt_template' DEFAULT_NAME = 'MQTT Template Light' DEFAULT_OPTIMISTIC = False CONF_BLUE_TEMPLATE = 'blue_template' CONF_BRIGHTNESS_TEMPLATE = 'brightness_template' CONF_COLOR_TEMP_TEMPLATE = 'color_temp_template' CONF_COMMAND_OFF_TEMPLATE = 'command_off_template' CONF_COMMAND_ON_TEMPLATE = 'command_on_template' CONF_EFFECT_LIST = 'effect_list' CONF_EFFECT_TEMPLATE = 'effect_template' CONF_GREEN_TEMPLATE = 'green_template' CONF_RED_TEMPLATE = 'red_template' CONF_STATE_TEMPLATE = 'state_template' CONF_WHITE_VALUE_TEMPLATE = 'white_value_template' PLATFORM_SCHEMA_TEMPLATE = mqtt.MQTT_RW_PLATFORM_SCHEMA.extend({ vol.Optional(CONF_BLUE_TEMPLATE): cv.template, vol.Optional(CONF_BRIGHTNESS_TEMPLATE): cv.template, vol.Optional(CONF_COLOR_TEMP_TEMPLATE): cv.template, vol.Required(CONF_COMMAND_OFF_TEMPLATE): cv.template, vol.Required(CONF_COMMAND_ON_TEMPLATE): cv.template, vol.Optional(CONF_DEVICE): mqtt.MQTT_ENTITY_DEVICE_INFO_SCHEMA, vol.Optional(CONF_EFFECT_LIST): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_EFFECT_TEMPLATE): cv.template, vol.Optional(CONF_GREEN_TEMPLATE): cv.template, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_OPTIMISTIC, default=DEFAULT_OPTIMISTIC): cv.boolean, vol.Optional(CONF_RED_TEMPLATE): cv.template, vol.Optional(CONF_STATE_TEMPLATE): cv.template, vol.Optional(CONF_UNIQUE_ID): cv.string, vol.Optional(CONF_WHITE_VALUE_TEMPLATE): cv.template, }).extend(mqtt.MQTT_AVAILABILITY_SCHEMA.schema).extend( mqtt.MQTT_JSON_ATTRS_SCHEMA.schema).extend(MQTT_LIGHT_SCHEMA_SCHEMA.schema) async def async_setup_entity_template(config, async_add_entities, config_entry, discovery_hash): """Set up a MQTT Template light.""" async_add_entities([MqttTemplate(config, config_entry, discovery_hash)]) # pylint: disable=too-many-ancestors class MqttTemplate(MqttAttributes, MqttAvailability, MqttDiscoveryUpdate, MqttEntityDeviceInfo, Light, RestoreEntity): """Representation of a MQTT Template light.""" def __init__(self, config, config_entry, discovery_hash): """Initialize a MQTT Template light.""" self._state = False self._sub_state = None self._topics = None self._templates = None self._optimistic = False # features self._brightness = None self._color_temp = None self._white_value = None self._hs = None self._effect = None self._unique_id = config.get(CONF_UNIQUE_ID) # Load config self._setup_from_config(config) device_config = config.get(CONF_DEVICE) MqttAttributes.__init__(self, config) MqttAvailability.__init__(self, config) MqttDiscoveryUpdate.__init__(self, discovery_hash, self.discovery_update) MqttEntityDeviceInfo.__init__(self, device_config, config_entry) async def async_added_to_hass(self): """Subscribe to MQTT events.""" await super().async_added_to_hass() await self._subscribe_topics() async def discovery_update(self, discovery_payload): """Handle updated discovery message.""" config = PLATFORM_SCHEMA_TEMPLATE(discovery_payload) self._setup_from_config(config) await self.attributes_discovery_update(config) await self.availability_discovery_update(config) await self.device_info_discovery_update(config) await self._subscribe_topics() self.async_write_ha_state() def _setup_from_config(self, config): """(Re)Setup the entity.""" self._config = config self._topics = { key: config.get(key) for key in ( CONF_STATE_TOPIC, CONF_COMMAND_TOPIC ) } self._templates = { key: config.get(key) for key in ( CONF_BLUE_TEMPLATE, CONF_BRIGHTNESS_TEMPLATE, CONF_COLOR_TEMP_TEMPLATE, CONF_COMMAND_OFF_TEMPLATE, CONF_COMMAND_ON_TEMPLATE, CONF_EFFECT_TEMPLATE, CONF_GREEN_TEMPLATE, CONF_RED_TEMPLATE, CONF_STATE_TEMPLATE, CONF_WHITE_VALUE_TEMPLATE, ) } optimistic = config[CONF_OPTIMISTIC] self._optimistic = optimistic \ or self._topics[CONF_STATE_TOPIC] is None \ or self._templates[CONF_STATE_TEMPLATE] is None # features if self._templates[CONF_BRIGHTNESS_TEMPLATE] is not None: self._brightness = 255 else: self._brightness = None if self._templates[CONF_COLOR_TEMP_TEMPLATE] is not None: self._color_temp = 255 else: self._color_temp = None if self._templates[CONF_WHITE_VALUE_TEMPLATE] is not None: self._white_value = 255 else: self._white_value = None if (self._templates[CONF_RED_TEMPLATE] is not None and self._templates[CONF_GREEN_TEMPLATE] is not None and self._templates[CONF_BLUE_TEMPLATE] is not None): self._hs = [0, 0] else: self._hs = None self._effect = None async def _subscribe_topics(self): """(Re)Subscribe to topics.""" for tpl in self._templates.values(): if tpl is not None: tpl.hass = self.hass last_state = await self.async_get_last_state() @callback def state_received(msg): """Handle new MQTT messages.""" state = self._templates[CONF_STATE_TEMPLATE].\ async_render_with_possible_json_value(msg.payload) if state == STATE_ON: self._state = True elif state == STATE_OFF: self._state = False else: _LOGGER.warning("Invalid state value received") if self._brightness is not None: try: self._brightness = int( self._templates[CONF_BRIGHTNESS_TEMPLATE]. async_render_with_possible_json_value(msg.payload) ) except ValueError: _LOGGER.warning("Invalid brightness value received") if self._color_temp is not None: try: self._color_temp = int( self._templates[CONF_COLOR_TEMP_TEMPLATE]. async_render_with_possible_json_value(msg.payload) ) except ValueError: _LOGGER.warning("Invalid color temperature value received") if self._hs is not None: try: red = int( self._templates[CONF_RED_TEMPLATE]. async_render_with_possible_json_value(msg.payload)) green = int( self._templates[CONF_GREEN_TEMPLATE]. async_render_with_possible_json_value(msg.payload)) blue = int( self._templates[CONF_BLUE_TEMPLATE]. async_render_with_possible_json_value(msg.payload)) self._hs = color_util.color_RGB_to_hs(red, green, blue) except ValueError: _LOGGER.warning("Invalid color value received") if self._white_value is not None: try: self._white_value = int( self._templates[CONF_WHITE_VALUE_TEMPLATE]. async_render_with_possible_json_value(msg.payload) ) except ValueError: _LOGGER.warning('Invalid white value received') if self._templates[CONF_EFFECT_TEMPLATE] is not None: effect = self._templates[CONF_EFFECT_TEMPLATE].\ async_render_with_possible_json_value(msg.payload) if effect in self._config.get(CONF_EFFECT_LIST): self._effect = effect else: _LOGGER.warning("Unsupported effect value received") self.async_write_ha_state() if self._topics[CONF_STATE_TOPIC] is not None: self._sub_state = await subscription.async_subscribe_topics( self.hass, self._sub_state, {'state_topic': {'topic': self._topics[CONF_STATE_TOPIC], 'msg_callback': state_received, 'qos': self._config[CONF_QOS]}}) if self._optimistic and last_state: self._state = last_state.state == STATE_ON if last_state.attributes.get(ATTR_BRIGHTNESS): self._brightness = last_state.attributes.get(ATTR_BRIGHTNESS) if last_state.attributes.get(ATTR_HS_COLOR): self._hs = last_state.attributes.get(ATTR_HS_COLOR) if last_state.attributes.get(ATTR_COLOR_TEMP): self._color_temp = last_state.attributes.get(ATTR_COLOR_TEMP) if last_state.attributes.get(ATTR_EFFECT): self._effect = last_state.attributes.get(ATTR_EFFECT) if last_state.attributes.get(ATTR_WHITE_VALUE): self._white_value = last_state.attributes.get(ATTR_WHITE_VALUE) async def async_will_remove_from_hass(self): """Unsubscribe when removed.""" self._sub_state = await subscription.async_unsubscribe_topics( self.hass, self._sub_state) await MqttAttributes.async_will_remove_from_hass(self) await MqttAvailability.async_will_remove_from_hass(self) @property def brightness(self): """Return the brightness of this light between 0..255.""" return self._brightness @property def color_temp(self): """Return the color temperature in mired.""" return self._color_temp @property def hs_color(self): """Return the hs color value [int, int].""" return self._hs @property def white_value(self): """Return the white property.""" return self._white_value @property def should_poll(self): """Return True if entity has to be polled for state. False if entity pushes its state to HA. """ return False @property def name(self): """Return the name of the entity.""" return self._config[CONF_NAME] @property def unique_id(self): """Return a unique ID.""" return self._unique_id @property def is_on(self): """Return True if entity is on.""" return self._state @property def assumed_state(self): """Return True if unable to access real state of the entity.""" return self._optimistic @property def effect_list(self): """Return the list of supported effects.""" return self._config.get(CONF_EFFECT_LIST) @property def effect(self): """Return the current effect.""" return self._effect async def async_turn_on(self, **kwargs): """Turn the entity on. This method is a coroutine. """ values = {'state': True} if self._optimistic: self._state = True if ATTR_BRIGHTNESS in kwargs: values['brightness'] = int(kwargs[ATTR_BRIGHTNESS]) if self._optimistic: self._brightness = kwargs[ATTR_BRIGHTNESS] if ATTR_COLOR_TEMP in kwargs: values['color_temp'] = int(kwargs[ATTR_COLOR_TEMP]) if self._optimistic: self._color_temp = kwargs[ATTR_COLOR_TEMP] if ATTR_HS_COLOR in kwargs: hs_color = kwargs[ATTR_HS_COLOR] # If there's a brightness topic set, we don't want to scale the RGB # values given using the brightness. if self._templates[CONF_BRIGHTNESS_TEMPLATE] is not None: brightness = 255 else: brightness = kwargs.get( ATTR_BRIGHTNESS, self._brightness if self._brightness else 255) rgb = color_util.color_hsv_to_RGB( hs_color[0], hs_color[1], brightness / 255 * 100) values['red'] = rgb[0] values['green'] = rgb[1] values['blue'] = rgb[2] if self._optimistic: self._hs = kwargs[ATTR_HS_COLOR] if ATTR_WHITE_VALUE in kwargs: values['white_value'] = int(kwargs[ATTR_WHITE_VALUE]) if self._optimistic: self._white_value = kwargs[ATTR_WHITE_VALUE] if ATTR_EFFECT in kwargs: values['effect'] = kwargs.get(ATTR_EFFECT) if ATTR_FLASH in kwargs: values['flash'] = kwargs.get(ATTR_FLASH) if ATTR_TRANSITION in kwargs: values['transition'] = int(kwargs[ATTR_TRANSITION]) mqtt.async_publish( self.hass, self._topics[CONF_COMMAND_TOPIC], self._templates[CONF_COMMAND_ON_TEMPLATE].async_render(**values), self._config[CONF_QOS], self._config[CONF_RETAIN] ) if self._optimistic: self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Turn the entity off. This method is a coroutine. """ values = {'state': False} if self._optimistic: self._state = False if ATTR_TRANSITION in kwargs: values['transition'] = int(kwargs[ATTR_TRANSITION]) mqtt.async_publish( self.hass, self._topics[CONF_COMMAND_TOPIC], self._templates[CONF_COMMAND_OFF_TEMPLATE].async_render(**values), self._config[CONF_QOS], self._config[CONF_RETAIN] ) if self._optimistic: self.async_write_ha_state() @property def supported_features(self): """Flag supported features.""" features = (SUPPORT_FLASH | SUPPORT_TRANSITION) if self._brightness is not None: features = features | SUPPORT_BRIGHTNESS if self._hs is not None: features = features | SUPPORT_COLOR if self._config.get(CONF_EFFECT_LIST) is not None: features = features | SUPPORT_EFFECT if self._color_temp is not None: features = features | SUPPORT_COLOR_TEMP if self._white_value is not None: features = features | SUPPORT_WHITE_VALUE return features
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/mqtt/light/schema_template.py
"""Permission constants for the websocket API. Separate file to avoid circular imports. """ from homeassistant.const import ( EVENT_COMPONENT_LOADED, EVENT_SERVICE_REGISTERED, EVENT_SERVICE_REMOVED, EVENT_STATE_CHANGED, EVENT_THEMES_UPDATED) from homeassistant.components.persistent_notification import ( EVENT_PERSISTENT_NOTIFICATIONS_UPDATED) from homeassistant.components.lovelace import EVENT_LOVELACE_UPDATED from homeassistant.helpers.area_registry import EVENT_AREA_REGISTRY_UPDATED from homeassistant.helpers.device_registry import EVENT_DEVICE_REGISTRY_UPDATED from homeassistant.helpers.entity_registry import EVENT_ENTITY_REGISTRY_UPDATED from homeassistant.components.frontend import EVENT_PANELS_UPDATED # These are events that do not contain any sensitive data # Except for state_changed, which is handled accordingly. SUBSCRIBE_WHITELIST = { EVENT_COMPONENT_LOADED, EVENT_PANELS_UPDATED, EVENT_PERSISTENT_NOTIFICATIONS_UPDATED, EVENT_SERVICE_REGISTERED, EVENT_SERVICE_REMOVED, EVENT_STATE_CHANGED, EVENT_THEMES_UPDATED, EVENT_AREA_REGISTRY_UPDATED, EVENT_DEVICE_REGISTRY_UPDATED, EVENT_ENTITY_REGISTRY_UPDATED, EVENT_LOVELACE_UPDATED, }
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/websocket_api/permissions.py
"""Support for Tellstick sensors.""" import logging from collections import namedtuple import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import TEMP_CELSIUS, CONF_ID, CONF_NAME from homeassistant.helpers.entity import Entity import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DatatypeDescription = namedtuple('DatatypeDescription', ['name', 'unit']) CONF_DATATYPE_MASK = 'datatype_mask' CONF_ONLY_NAMED = 'only_named' CONF_TEMPERATURE_SCALE = 'temperature_scale' DEFAULT_DATATYPE_MASK = 127 DEFAULT_TEMPERATURE_SCALE = TEMP_CELSIUS PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_TEMPERATURE_SCALE, default=DEFAULT_TEMPERATURE_SCALE): cv.string, vol.Optional(CONF_DATATYPE_MASK, default=DEFAULT_DATATYPE_MASK): cv.positive_int, vol.Optional(CONF_ONLY_NAMED, default=[]): vol.All(cv.ensure_list, [vol.Schema({ vol.Required(CONF_ID): cv.positive_int, vol.Required(CONF_NAME): cv.string, })]) }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Tellstick sensors.""" from tellcore import telldus import tellcore.constants as tellcore_constants sensor_value_descriptions = { tellcore_constants.TELLSTICK_TEMPERATURE: DatatypeDescription('temperature', config.get(CONF_TEMPERATURE_SCALE)), tellcore_constants.TELLSTICK_HUMIDITY: DatatypeDescription('humidity', '%'), tellcore_constants.TELLSTICK_RAINRATE: DatatypeDescription('rain rate', ''), tellcore_constants.TELLSTICK_RAINTOTAL: DatatypeDescription('rain total', ''), tellcore_constants.TELLSTICK_WINDDIRECTION: DatatypeDescription('wind direction', ''), tellcore_constants.TELLSTICK_WINDAVERAGE: DatatypeDescription('wind average', ''), tellcore_constants.TELLSTICK_WINDGUST: DatatypeDescription('wind gust', '') } try: tellcore_lib = telldus.TelldusCore() except OSError: _LOGGER.exception('Could not initialize Tellstick') return sensors = [] datatype_mask = config.get(CONF_DATATYPE_MASK) if config[CONF_ONLY_NAMED]: named_sensors = { named_sensor[CONF_ID]: named_sensor[CONF_NAME] for named_sensor in config[CONF_ONLY_NAMED]} for tellcore_sensor in tellcore_lib.sensors(): if not config[CONF_ONLY_NAMED]: sensor_name = str(tellcore_sensor.id) else: if tellcore_sensor.id not in named_sensors: continue sensor_name = named_sensors[tellcore_sensor.id] for datatype in sensor_value_descriptions: if datatype & datatype_mask and \ tellcore_sensor.has_value(datatype): sensor_info = sensor_value_descriptions[datatype] sensors.append(TellstickSensor( sensor_name, tellcore_sensor, datatype, sensor_info)) add_entities(sensors) class TellstickSensor(Entity): """Representation of a Tellstick sensor.""" def __init__(self, name, tellcore_sensor, datatype, sensor_info): """Initialize the sensor.""" self._datatype = datatype self._tellcore_sensor = tellcore_sensor self._unit_of_measurement = sensor_info.unit or None self._value = None self._name = '{} {}'.format(name, sensor_info.name) @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._value @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement def update(self): """Update tellstick sensor.""" self._value = self._tellcore_sensor.value(self._datatype).value
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/tellstick/sensor.py
"""Support for LaCrosse sensor components.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.sensor import ENTITY_ID_FORMAT, PLATFORM_SCHEMA from homeassistant.const import ( CONF_DEVICE, CONF_ID, CONF_NAME, CONF_SENSORS, CONF_TYPE, EVENT_HOMEASSISTANT_STOP, TEMP_CELSIUS) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity, async_generate_entity_id from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.util import dt as dt_util _LOGGER = logging.getLogger(__name__) CONF_BAUD = 'baud' CONF_DATARATE = 'datarate' CONF_EXPIRE_AFTER = 'expire_after' CONF_FREQUENCY = 'frequency' CONF_JEELINK_LED = 'led' CONF_TOGGLE_INTERVAL = 'toggle_interval' CONF_TOGGLE_MASK = 'toggle_mask' DEFAULT_DEVICE = '/dev/ttyUSB0' DEFAULT_BAUD = '57600' DEFAULT_EXPIRE_AFTER = 300 TYPES = ['battery', 'humidity', 'temperature'] SENSOR_SCHEMA = vol.Schema({ vol.Required(CONF_ID): cv.positive_int, vol.Required(CONF_TYPE): vol.In(TYPES), vol.Optional(CONF_EXPIRE_AFTER): cv.positive_int, vol.Optional(CONF_NAME): cv.string, }) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_SENSORS): cv.schema_with_slug_keys(SENSOR_SCHEMA), vol.Optional(CONF_BAUD, default=DEFAULT_BAUD): cv.string, vol.Optional(CONF_DATARATE): cv.positive_int, vol.Optional(CONF_DEVICE, default=DEFAULT_DEVICE): cv.string, vol.Optional(CONF_FREQUENCY): cv.positive_int, vol.Optional(CONF_JEELINK_LED): cv.boolean, vol.Optional(CONF_TOGGLE_INTERVAL): cv.positive_int, vol.Optional(CONF_TOGGLE_MASK): cv.positive_int, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the LaCrosse sensors.""" import pylacrosse from serial import SerialException usb_device = config.get(CONF_DEVICE) baud = int(config.get(CONF_BAUD)) expire_after = config.get(CONF_EXPIRE_AFTER) _LOGGER.debug("%s %s", usb_device, baud) try: lacrosse = pylacrosse.LaCrosse(usb_device, baud) lacrosse.open() except SerialException as exc: _LOGGER.warning("Unable to open serial port: %s", exc) return False hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, lacrosse.close) if CONF_JEELINK_LED in config: lacrosse.led_mode_state(config.get(CONF_JEELINK_LED)) if CONF_FREQUENCY in config: lacrosse.set_frequency(config.get(CONF_FREQUENCY)) if CONF_DATARATE in config: lacrosse.set_datarate(config.get(CONF_DATARATE)) if CONF_TOGGLE_INTERVAL in config: lacrosse.set_toggle_interval(config.get(CONF_TOGGLE_INTERVAL)) if CONF_TOGGLE_MASK in config: lacrosse.set_toggle_mask(config.get(CONF_TOGGLE_MASK)) lacrosse.start_scan() sensors = [] for device, device_config in config[CONF_SENSORS].items(): _LOGGER.debug("%s %s", device, device_config) typ = device_config.get(CONF_TYPE) sensor_class = TYPE_CLASSES[typ] name = device_config.get(CONF_NAME, device) sensors.append( sensor_class( hass, lacrosse, device, name, expire_after, device_config ) ) add_entities(sensors) class LaCrosseSensor(Entity): """Implementation of a Lacrosse sensor.""" _temperature = None _humidity = None _low_battery = None _new_battery = None def __init__(self, hass, lacrosse, device_id, name, expire_after, config): """Initialize the sensor.""" self.hass = hass self.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, device_id, hass=hass) self._config = config self._name = name self._value = None self._expire_after = expire_after self._expiration_trigger = None lacrosse.register_callback( int(self._config['id']), self._callback_lacrosse, None) @property def name(self): """Return the name of the sensor.""" return self._name @property def device_state_attributes(self): """Return the state attributes.""" attributes = { 'low_battery': self._low_battery, 'new_battery': self._new_battery, } return attributes def _callback_lacrosse(self, lacrosse_sensor, user_data): """Handle a function that is called from pylacrosse with new values.""" if self._expire_after is not None and self._expire_after > 0: # Reset old trigger if self._expiration_trigger: self._expiration_trigger() self._expiration_trigger = None # Set new trigger expiration_at = ( dt_util.utcnow() + timedelta(seconds=self._expire_after)) self._expiration_trigger = async_track_point_in_utc_time( self.hass, self.value_is_expired, expiration_at) self._temperature = lacrosse_sensor.temperature self._humidity = lacrosse_sensor.humidity self._low_battery = lacrosse_sensor.low_battery self._new_battery = lacrosse_sensor.new_battery @callback def value_is_expired(self, *_): """Triggered when value is expired.""" self._expiration_trigger = None self._value = None self.async_schedule_update_ha_state() class LaCrosseTemperature(LaCrosseSensor): """Implementation of a Lacrosse temperature sensor.""" @property def unit_of_measurement(self): """Return the unit of measurement.""" return TEMP_CELSIUS @property def state(self): """Return the state of the sensor.""" return self._temperature class LaCrosseHumidity(LaCrosseSensor): """Implementation of a Lacrosse humidity sensor.""" @property def unit_of_measurement(self): """Return the unit of measurement.""" return '%' @property def state(self): """Return the state of the sensor.""" return self._humidity @property def icon(self): """Icon to use in the frontend.""" return 'mdi:water-percent' class LaCrosseBattery(LaCrosseSensor): """Implementation of a Lacrosse battery sensor.""" @property def state(self): """Return the state of the sensor.""" if self._low_battery is None: state = None elif self._low_battery is True: state = 'low' else: state = 'ok' return state @property def icon(self): """Icon to use in the frontend.""" if self._low_battery is None: icon = 'mdi:battery-unknown' elif self._low_battery is True: icon = 'mdi:battery-alert' else: icon = 'mdi:battery' return icon TYPE_CLASSES = { 'temperature': LaCrosseTemperature, 'humidity': LaCrosseHumidity, 'battery': LaCrosseBattery }
"""The tests for the demo light component.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components import light from tests.components.light import common ENTITY_LIGHT = 'light.bed_light' @pytest.fixture(autouse=True) def setup_comp(hass): """Set up demo component.""" hass.loop.run_until_complete(async_setup_component(hass, light.DOMAIN, { 'light': { 'platform': 'demo', }})) async def test_state_attributes(hass): """Test light state attributes.""" await common.async_turn_on( hass, ENTITY_LIGHT, xy_color=(.4, .4), brightness=25) state = hass.states.get(ENTITY_LIGHT) assert light.is_on(hass, ENTITY_LIGHT) assert (0.4, 0.4) == state.attributes.get(light.ATTR_XY_COLOR) assert 25 == state.attributes.get(light.ATTR_BRIGHTNESS) assert (255, 234, 164) == state.attributes.get(light.ATTR_RGB_COLOR) assert 'rainbow' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, rgb_color=(251, 253, 255), white_value=254) state = hass.states.get(ENTITY_LIGHT) assert 254 == state.attributes.get(light.ATTR_WHITE_VALUE) assert (250, 252, 255) == state.attributes.get(light.ATTR_RGB_COLOR) assert (0.319, 0.326) == state.attributes.get(light.ATTR_XY_COLOR) await common.async_turn_on( hass, ENTITY_LIGHT, color_temp=400, effect='none') state = hass.states.get(ENTITY_LIGHT) assert 400 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 153 == state.attributes.get(light.ATTR_MIN_MIREDS) assert 500 == state.attributes.get(light.ATTR_MAX_MIREDS) assert 'none' == state.attributes.get(light.ATTR_EFFECT) await common.async_turn_on( hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50) state = hass.states.get(ENTITY_LIGHT) assert 333 == state.attributes.get(light.ATTR_COLOR_TEMP) assert 127 == state.attributes.get(light.ATTR_BRIGHTNESS) async def test_turn_off(hass): """Test light turn off method.""" await hass.services.async_call('light', 'turn_on', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { 'entity_id': ENTITY_LIGHT }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT) async def test_turn_off_without_entity_id(hass): """Test light turn off all lights.""" await hass.services.async_call('light', 'turn_on', { }, blocking=True) assert light.is_on(hass, ENTITY_LIGHT) await hass.services.async_call('light', 'turn_off', { }, blocking=True) assert not light.is_on(hass, ENTITY_LIGHT)
jabesq/home-assistant
tests/components/demo/test_light.py
homeassistant/components/lacrosse/sensor.py
from __future__ import absolute_import from __future__ import unicode_literals import logging from compose.cli import colors from compose.cli.formatter import ConsoleWarningFormatter from tests import unittest MESSAGE = 'this is the message' def make_log_record(level, message=None): return logging.LogRecord('name', level, 'pathame', 0, message or MESSAGE, (), None) class ConsoleWarningFormatterTestCase(unittest.TestCase): def setUp(self): self.formatter = ConsoleWarningFormatter() def test_format_warn(self): output = self.formatter.format(make_log_record(logging.WARN)) expected = colors.yellow('WARNING') + ': ' assert output == expected + MESSAGE def test_format_error(self): output = self.formatter.format(make_log_record(logging.ERROR)) expected = colors.red('ERROR') + ': ' assert output == expected + MESSAGE def test_format_info(self): output = self.formatter.format(make_log_record(logging.INFO)) assert output == MESSAGE def test_format_unicode_info(self): message = b'\xec\xa0\x95\xec\x88\x98\xec\xa0\x95' output = self.formatter.format(make_log_record(logging.INFO, message)) print(output) assert output == message.decode('utf-8') def test_format_unicode_warn(self): message = b'\xec\xa0\x95\xec\x88\x98\xec\xa0\x95' output = self.formatter.format(make_log_record(logging.WARN, message)) expected = colors.yellow('WARNING') + ': ' assert output == '{0}{1}'.format(expected, message.decode('utf-8')) def test_format_unicode_error(self): message = b'\xec\xa0\x95\xec\x88\x98\xec\xa0\x95' output = self.formatter.format(make_log_record(logging.ERROR, message)) expected = colors.red('ERROR') + ': ' assert output == '{0}{1}'.format(expected, message.decode('utf-8'))
from __future__ import absolute_import from __future__ import unicode_literals import logging import pytest from compose import container from compose.cli.errors import UserError from compose.cli.formatter import ConsoleWarningFormatter from compose.cli.main import convergence_strategy_from_opts from compose.cli.main import filter_containers_to_service_names from compose.cli.main import setup_console_handler from compose.service import ConvergenceStrategy from tests import mock def mock_container(service, number): return mock.create_autospec( container.Container, service=service, number=number, name_without_project='{0}_{1}'.format(service, number)) @pytest.fixture def logging_handler(): stream = mock.Mock() stream.isatty.return_value = True return logging.StreamHandler(stream=stream) class TestCLIMainTestCase(object): def test_filter_containers_to_service_names(self): containers = [ mock_container('web', 1), mock_container('web', 2), mock_container('db', 1), mock_container('other', 1), mock_container('another', 1), ] service_names = ['web', 'db'] actual = filter_containers_to_service_names(containers, service_names) assert actual == containers[:3] def test_filter_containers_to_service_names_all(self): containers = [ mock_container('web', 1), mock_container('db', 1), mock_container('other', 1), ] service_names = [] actual = filter_containers_to_service_names(containers, service_names) assert actual == containers class TestSetupConsoleHandlerTestCase(object): def test_with_tty_verbose(self, logging_handler): setup_console_handler(logging_handler, True) assert type(logging_handler.formatter) == ConsoleWarningFormatter assert '%(name)s' in logging_handler.formatter._fmt assert '%(funcName)s' in logging_handler.formatter._fmt def test_with_tty_not_verbose(self, logging_handler): setup_console_handler(logging_handler, False) assert type(logging_handler.formatter) == ConsoleWarningFormatter assert '%(name)s' not in logging_handler.formatter._fmt assert '%(funcName)s' not in logging_handler.formatter._fmt def test_with_not_a_tty(self, logging_handler): logging_handler.stream.isatty.return_value = False setup_console_handler(logging_handler, False) assert type(logging_handler.formatter) == logging.Formatter class TestConvergeStrategyFromOptsTestCase(object): def test_invalid_opts(self): options = {'--force-recreate': True, '--no-recreate': True} with pytest.raises(UserError): convergence_strategy_from_opts(options) def test_always(self): options = {'--force-recreate': True, '--no-recreate': False} assert ( convergence_strategy_from_opts(options) == ConvergenceStrategy.always ) def test_never(self): options = {'--force-recreate': False, '--no-recreate': True} assert ( convergence_strategy_from_opts(options) == ConvergenceStrategy.never ) def test_changed(self): options = {'--force-recreate': False, '--no-recreate': False} assert ( convergence_strategy_from_opts(options) == ConvergenceStrategy.changed )
schmunk42/compose
tests/unit/cli/main_test.py
tests/unit/cli/formatter_test.py
from __future__ import absolute_import from __future__ import unicode_literals import sys if sys.version_info >= (2, 7): import unittest # NOQA else: import unittest2 as unittest # NOQA try: from unittest import mock except ImportError: import mock # NOQA
from __future__ import absolute_import from __future__ import unicode_literals import logging import pytest from compose import container from compose.cli.errors import UserError from compose.cli.formatter import ConsoleWarningFormatter from compose.cli.main import convergence_strategy_from_opts from compose.cli.main import filter_containers_to_service_names from compose.cli.main import setup_console_handler from compose.service import ConvergenceStrategy from tests import mock def mock_container(service, number): return mock.create_autospec( container.Container, service=service, number=number, name_without_project='{0}_{1}'.format(service, number)) @pytest.fixture def logging_handler(): stream = mock.Mock() stream.isatty.return_value = True return logging.StreamHandler(stream=stream) class TestCLIMainTestCase(object): def test_filter_containers_to_service_names(self): containers = [ mock_container('web', 1), mock_container('web', 2), mock_container('db', 1), mock_container('other', 1), mock_container('another', 1), ] service_names = ['web', 'db'] actual = filter_containers_to_service_names(containers, service_names) assert actual == containers[:3] def test_filter_containers_to_service_names_all(self): containers = [ mock_container('web', 1), mock_container('db', 1), mock_container('other', 1), ] service_names = [] actual = filter_containers_to_service_names(containers, service_names) assert actual == containers class TestSetupConsoleHandlerTestCase(object): def test_with_tty_verbose(self, logging_handler): setup_console_handler(logging_handler, True) assert type(logging_handler.formatter) == ConsoleWarningFormatter assert '%(name)s' in logging_handler.formatter._fmt assert '%(funcName)s' in logging_handler.formatter._fmt def test_with_tty_not_verbose(self, logging_handler): setup_console_handler(logging_handler, False) assert type(logging_handler.formatter) == ConsoleWarningFormatter assert '%(name)s' not in logging_handler.formatter._fmt assert '%(funcName)s' not in logging_handler.formatter._fmt def test_with_not_a_tty(self, logging_handler): logging_handler.stream.isatty.return_value = False setup_console_handler(logging_handler, False) assert type(logging_handler.formatter) == logging.Formatter class TestConvergeStrategyFromOptsTestCase(object): def test_invalid_opts(self): options = {'--force-recreate': True, '--no-recreate': True} with pytest.raises(UserError): convergence_strategy_from_opts(options) def test_always(self): options = {'--force-recreate': True, '--no-recreate': False} assert ( convergence_strategy_from_opts(options) == ConvergenceStrategy.always ) def test_never(self): options = {'--force-recreate': False, '--no-recreate': True} assert ( convergence_strategy_from_opts(options) == ConvergenceStrategy.never ) def test_changed(self): options = {'--force-recreate': False, '--no-recreate': False} assert ( convergence_strategy_from_opts(options) == ConvergenceStrategy.changed )
schmunk42/compose
tests/unit/cli/main_test.py
tests/__init__.py
# --------------------------------------------------------------------- # JSON normalization routines import copy from collections import defaultdict import numpy as np from pandas._libs.writers import convert_json_to_lines from pandas import compat, DataFrame def _convert_to_line_delimits(s): """Helper function that converts json lists to line delimited json.""" # Determine we have a JSON list to turn to lines otherwise just return the # json object, only lists can if not s[0] == '[' and s[-1] == ']': return s s = s[1:-1] return convert_json_to_lines(s) def nested_to_record(ds, prefix="", sep=".", level=0): """a simplified json_normalize converts a nested dict into a flat dict ("record"), unlike json_normalize, it does not attempt to extract a subset of the data. Parameters ---------- ds : dict or list of dicts prefix: the prefix, optional, default: "" sep : string, default '.' Nested records will generate names separated by sep, e.g., for sep='.', { 'foo' : { 'bar' : 0 } } -> foo.bar .. versionadded:: 0.20.0 level: the number of levels in the jason string, optional, default: 0 Returns ------- d - dict or list of dicts, matching `ds` Examples -------- IN[52]: nested_to_record(dict(flat1=1,dict1=dict(c=1,d=2), nested=dict(e=dict(c=1,d=2),d=2))) Out[52]: {'dict1.c': 1, 'dict1.d': 2, 'flat1': 1, 'nested.d': 2, 'nested.e.c': 1, 'nested.e.d': 2} """ singleton = False if isinstance(ds, dict): ds = [ds] singleton = True new_ds = [] for d in ds: new_d = copy.deepcopy(d) for k, v in d.items(): # each key gets renamed with prefix if not isinstance(k, compat.string_types): k = str(k) if level == 0: newkey = k else: newkey = prefix + sep + k # only dicts gets recurse-flattend # only at level>1 do we rename the rest of the keys if not isinstance(v, dict): if level != 0: # so we skip copying for top level, common case v = new_d.pop(k) new_d[newkey] = v continue else: v = new_d.pop(k) new_d.update(nested_to_record(v, newkey, sep, level + 1)) new_ds.append(new_d) if singleton: return new_ds[0] return new_ds def json_normalize(data, record_path=None, meta=None, meta_prefix=None, record_prefix=None, errors='raise', sep='.'): """ "Normalize" semi-structured JSON data into a flat table Parameters ---------- data : dict or list of dicts Unserialized JSON objects record_path : string or list of strings, default None Path in each object to list of records. If not passed, data will be assumed to be an array of records meta : list of paths (string or list of strings), default None Fields to use as metadata for each record in resulting table record_prefix : string, default None If True, prefix records with dotted (?) path, e.g. foo.bar.field if path to records is ['foo', 'bar'] meta_prefix : string, default None errors : {'raise', 'ignore'}, default 'raise' * 'ignore' : will ignore KeyError if keys listed in meta are not always present * 'raise' : will raise KeyError if keys listed in meta are not always present .. versionadded:: 0.20.0 sep : string, default '.' Nested records will generate names separated by sep, e.g., for sep='.', { 'foo' : { 'bar' : 0 } } -> foo.bar .. versionadded:: 0.20.0 Returns ------- frame : DataFrame Examples -------- >>> from pandas.io.json import json_normalize >>> data = [{'id': 1, 'name': {'first': 'Coleen', 'last': 'Volk'}}, ... {'name': {'given': 'Mose', 'family': 'Regner'}}, ... {'id': 2, 'name': 'Faye Raker'}] >>> json_normalize(data) id name name.family name.first name.given name.last 0 1.0 NaN NaN Coleen NaN Volk 1 NaN NaN Regner NaN Mose NaN 2 2.0 Faye Raker NaN NaN NaN NaN >>> data = [{'state': 'Florida', ... 'shortname': 'FL', ... 'info': { ... 'governor': 'Rick Scott' ... }, ... 'counties': [{'name': 'Dade', 'population': 12345}, ... {'name': 'Broward', 'population': 40000}, ... {'name': 'Palm Beach', 'population': 60000}]}, ... {'state': 'Ohio', ... 'shortname': 'OH', ... 'info': { ... 'governor': 'John Kasich' ... }, ... 'counties': [{'name': 'Summit', 'population': 1234}, ... {'name': 'Cuyahoga', 'population': 1337}]}] >>> result = json_normalize(data, 'counties', ['state', 'shortname', ... ['info', 'governor']]) >>> result name population info.governor state shortname 0 Dade 12345 Rick Scott Florida FL 1 Broward 40000 Rick Scott Florida FL 2 Palm Beach 60000 Rick Scott Florida FL 3 Summit 1234 John Kasich Ohio OH 4 Cuyahoga 1337 John Kasich Ohio OH >>> data = {'A': [1, 2]} >>> json_normalize(data, 'A', record_prefix='Prefix.') Prefix.0 0 1 1 2 """ def _pull_field(js, spec): result = js if isinstance(spec, list): for field in spec: result = result[field] else: result = result[spec] return result if isinstance(data, list) and not data: return DataFrame() # A bit of a hackjob if isinstance(data, dict): data = [data] if record_path is None: if any([[isinstance(x, dict) for x in compat.itervalues(y)] for y in data]): # naive normalization, this is idempotent for flat records # and potentially will inflate the data considerably for # deeply nested structures: # {VeryLong: { b: 1,c:2}} -> {VeryLong.b:1 ,VeryLong.c:@} # # TODO: handle record value which are lists, at least error # reasonably data = nested_to_record(data, sep=sep) return DataFrame(data) elif not isinstance(record_path, list): record_path = [record_path] if meta is None: meta = [] elif not isinstance(meta, list): meta = [meta] meta = [m if isinstance(m, list) else [m] for m in meta] # Disastrously inefficient for now records = [] lengths = [] meta_vals = defaultdict(list) if not isinstance(sep, compat.string_types): sep = str(sep) meta_keys = [sep.join(val) for val in meta] def _recursive_extract(data, path, seen_meta, level=0): if len(path) > 1: for obj in data: for val, key in zip(meta, meta_keys): if level + 1 == len(val): seen_meta[key] = _pull_field(obj, val[-1]) _recursive_extract(obj[path[0]], path[1:], seen_meta, level=level + 1) else: for obj in data: recs = _pull_field(obj, path[0]) # For repeating the metadata later lengths.append(len(recs)) for val, key in zip(meta, meta_keys): if level + 1 > len(val): meta_val = seen_meta[key] else: try: meta_val = _pull_field(obj, val[level:]) except KeyError as e: if errors == 'ignore': meta_val = np.nan else: raise \ KeyError("Try running with " "errors='ignore' as key " "{err} is not always present" .format(err=e)) meta_vals[key].append(meta_val) records.extend(recs) _recursive_extract(data, record_path, {}, level=0) result = DataFrame(records) if record_prefix is not None: result = result.rename( columns=lambda x: "{p}{c}".format(p=record_prefix, c=x)) # Data types, a problem for k, v in compat.iteritems(meta_vals): if meta_prefix is not None: k = meta_prefix + k if k in result: raise ValueError('Conflicting metadata name {name}, ' 'need distinguishing prefix '.format(name=k)) result[k] = np.array(v).repeat(lengths) return result
import numpy as np import pandas as pd from pandas import DataFrame, MultiIndex, Index, Series, isna, Timestamp from pandas.compat import lrange from pandas.util.testing import ( assert_frame_equal, assert_produces_warning, assert_series_equal) import pytest def test_first_last_nth(df): # tests for first / last / nth grouped = df.groupby('A') first = grouped.first() expected = df.loc[[1, 0], ['B', 'C', 'D']] expected.index = Index(['bar', 'foo'], name='A') expected = expected.sort_index() assert_frame_equal(first, expected) nth = grouped.nth(0) assert_frame_equal(nth, expected) last = grouped.last() expected = df.loc[[5, 7], ['B', 'C', 'D']] expected.index = Index(['bar', 'foo'], name='A') assert_frame_equal(last, expected) nth = grouped.nth(-1) assert_frame_equal(nth, expected) nth = grouped.nth(1) expected = df.loc[[2, 3], ['B', 'C', 'D']].copy() expected.index = Index(['foo', 'bar'], name='A') expected = expected.sort_index() assert_frame_equal(nth, expected) # it works! grouped['B'].first() grouped['B'].last() grouped['B'].nth(0) df.loc[df['A'] == 'foo', 'B'] = np.nan assert isna(grouped['B'].first()['foo']) assert isna(grouped['B'].last()['foo']) assert isna(grouped['B'].nth(0)['foo']) # v0.14.0 whatsnew df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B']) g = df.groupby('A') result = g.first() expected = df.iloc[[1, 2]].set_index('A') assert_frame_equal(result, expected) expected = df.iloc[[1, 2]].set_index('A') result = g.nth(0, dropna='any') assert_frame_equal(result, expected) def test_first_last_nth_dtypes(df_mixed_floats): df = df_mixed_floats.copy() df['E'] = True df['F'] = 1 # tests for first / last / nth grouped = df.groupby('A') first = grouped.first() expected = df.loc[[1, 0], ['B', 'C', 'D', 'E', 'F']] expected.index = Index(['bar', 'foo'], name='A') expected = expected.sort_index() assert_frame_equal(first, expected) last = grouped.last() expected = df.loc[[5, 7], ['B', 'C', 'D', 'E', 'F']] expected.index = Index(['bar', 'foo'], name='A') expected = expected.sort_index() assert_frame_equal(last, expected) nth = grouped.nth(1) expected = df.loc[[3, 2], ['B', 'C', 'D', 'E', 'F']] expected.index = Index(['bar', 'foo'], name='A') expected = expected.sort_index() assert_frame_equal(nth, expected) # GH 2763, first/last shifting dtypes idx = lrange(10) idx.append(9) s = Series(data=lrange(11), index=idx, name='IntCol') assert s.dtype == 'int64' f = s.groupby(level=0).first() assert f.dtype == 'int64' def test_nth(): df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B']) g = df.groupby('A') assert_frame_equal(g.nth(0), df.iloc[[0, 2]].set_index('A')) assert_frame_equal(g.nth(1), df.iloc[[1]].set_index('A')) assert_frame_equal(g.nth(2), df.loc[[]].set_index('A')) assert_frame_equal(g.nth(-1), df.iloc[[1, 2]].set_index('A')) assert_frame_equal(g.nth(-2), df.iloc[[0]].set_index('A')) assert_frame_equal(g.nth(-3), df.loc[[]].set_index('A')) assert_series_equal(g.B.nth(0), df.set_index('A').B.iloc[[0, 2]]) assert_series_equal(g.B.nth(1), df.set_index('A').B.iloc[[1]]) assert_frame_equal(g[['B']].nth(0), df.loc[[0, 2], ['A', 'B']].set_index('A')) exp = df.set_index('A') assert_frame_equal(g.nth(0, dropna='any'), exp.iloc[[1, 2]]) assert_frame_equal(g.nth(-1, dropna='any'), exp.iloc[[1, 2]]) exp['B'] = np.nan assert_frame_equal(g.nth(7, dropna='any'), exp.iloc[[1, 2]]) assert_frame_equal(g.nth(2, dropna='any'), exp.iloc[[1, 2]]) # out of bounds, regression from 0.13.1 # GH 6621 df = DataFrame({'color': {0: 'green', 1: 'green', 2: 'red', 3: 'red', 4: 'red'}, 'food': {0: 'ham', 1: 'eggs', 2: 'eggs', 3: 'ham', 4: 'pork'}, 'two': {0: 1.5456590000000001, 1: -0.070345000000000005, 2: -2.4004539999999999, 3: 0.46206000000000003, 4: 0.52350799999999997}, 'one': {0: 0.56573799999999996, 1: -0.9742360000000001, 2: 1.033801, 3: -0.78543499999999999, 4: 0.70422799999999997}}).set_index(['color', 'food']) result = df.groupby(level=0, as_index=False).nth(2) expected = df.iloc[[-1]] assert_frame_equal(result, expected) result = df.groupby(level=0, as_index=False).nth(3) expected = df.loc[[]] assert_frame_equal(result, expected) # GH 7559 # from the vbench df = DataFrame(np.random.randint(1, 10, (100, 2)), dtype='int64') s = df[1] g = df[0] expected = s.groupby(g).first() expected2 = s.groupby(g).apply(lambda x: x.iloc[0]) assert_series_equal(expected2, expected, check_names=False) assert expected.name == 1 assert expected2.name == 1 # validate first v = s[g == 1].iloc[0] assert expected.iloc[0] == v assert expected2.iloc[0] == v # this is NOT the same as .first (as sorted is default!) # as it keeps the order in the series (and not the group order) # related GH 7287 expected = s.groupby(g, sort=False).first() result = s.groupby(g, sort=False).nth(0, dropna='all') assert_series_equal(result, expected) # doc example df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B']) g = df.groupby('A') # PR 17493, related to issue 11038 # test Series.nth with True for dropna produces FutureWarning with assert_produces_warning(FutureWarning): result = g.B.nth(0, dropna=True) expected = g.B.first() assert_series_equal(result, expected) # test multiple nth values df = DataFrame([[1, np.nan], [1, 3], [1, 4], [5, 6], [5, 7]], columns=['A', 'B']) g = df.groupby('A') assert_frame_equal(g.nth(0), df.iloc[[0, 3]].set_index('A')) assert_frame_equal(g.nth([0]), df.iloc[[0, 3]].set_index('A')) assert_frame_equal(g.nth([0, 1]), df.iloc[[0, 1, 3, 4]].set_index('A')) assert_frame_equal( g.nth([0, -1]), df.iloc[[0, 2, 3, 4]].set_index('A')) assert_frame_equal( g.nth([0, 1, 2]), df.iloc[[0, 1, 2, 3, 4]].set_index('A')) assert_frame_equal( g.nth([0, 1, -1]), df.iloc[[0, 1, 2, 3, 4]].set_index('A')) assert_frame_equal(g.nth([2]), df.iloc[[2]].set_index('A')) assert_frame_equal(g.nth([3, 4]), df.loc[[]].set_index('A')) business_dates = pd.date_range(start='4/1/2014', end='6/30/2014', freq='B') df = DataFrame(1, index=business_dates, columns=['a', 'b']) # get the first, fourth and last two business days for each month key = [df.index.year, df.index.month] result = df.groupby(key, as_index=False).nth([0, 3, -2, -1]) expected_dates = pd.to_datetime( ['2014/4/1', '2014/4/4', '2014/4/29', '2014/4/30', '2014/5/1', '2014/5/6', '2014/5/29', '2014/5/30', '2014/6/2', '2014/6/5', '2014/6/27', '2014/6/30']) expected = DataFrame(1, columns=['a', 'b'], index=expected_dates) assert_frame_equal(result, expected) def test_nth_multi_index(three_group): # PR 9090, related to issue 8979 # test nth on MultiIndex, should match .first() grouped = three_group.groupby(['A', 'B']) result = grouped.nth(0) expected = grouped.first() assert_frame_equal(result, expected) @pytest.mark.parametrize('data, expected_first, expected_last', [ ({'id': ['A'], 'time': Timestamp('2012-02-01 14:00:00', tz='US/Central'), 'foo': [1]}, {'id': ['A'], 'time': Timestamp('2012-02-01 14:00:00', tz='US/Central'), 'foo': [1]}, {'id': ['A'], 'time': Timestamp('2012-02-01 14:00:00', tz='US/Central'), 'foo': [1]}), ({'id': ['A', 'B', 'A'], 'time': [Timestamp('2012-01-01 13:00:00', tz='America/New_York'), Timestamp('2012-02-01 14:00:00', tz='US/Central'), Timestamp('2012-03-01 12:00:00', tz='Europe/London')], 'foo': [1, 2, 3]}, {'id': ['A', 'B'], 'time': [Timestamp('2012-01-01 13:00:00', tz='America/New_York'), Timestamp('2012-02-01 14:00:00', tz='US/Central')], 'foo': [1, 2]}, {'id': ['A', 'B'], 'time': [Timestamp('2012-03-01 12:00:00', tz='Europe/London'), Timestamp('2012-02-01 14:00:00', tz='US/Central')], 'foo': [3, 2]}) ]) def test_first_last_tz(data, expected_first, expected_last): # GH15884 # Test that the timezone is retained when calling first # or last on groupby with as_index=False df = DataFrame(data) result = df.groupby('id', as_index=False).first() expected = DataFrame(expected_first) cols = ['id', 'time', 'foo'] assert_frame_equal(result[cols], expected[cols]) result = df.groupby('id', as_index=False)['time'].first() assert_frame_equal(result, expected[['id', 'time']]) result = df.groupby('id', as_index=False).last() expected = DataFrame(expected_last) cols = ['id', 'time', 'foo'] assert_frame_equal(result[cols], expected[cols]) result = df.groupby('id', as_index=False)['time'].last() assert_frame_equal(result, expected[['id', 'time']]) def test_nth_multi_index_as_expected(): # PR 9090, related to issue 8979 # test nth on MultiIndex three_group = DataFrame( {'A': ['foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar', 'foo', 'foo', 'foo'], 'B': ['one', 'one', 'one', 'two', 'one', 'one', 'one', 'two', 'two', 'two', 'one'], 'C': ['dull', 'dull', 'shiny', 'dull', 'dull', 'shiny', 'shiny', 'dull', 'shiny', 'shiny', 'shiny']}) grouped = three_group.groupby(['A', 'B']) result = grouped.nth(0) expected = DataFrame( {'C': ['dull', 'dull', 'dull', 'dull']}, index=MultiIndex.from_arrays([['bar', 'bar', 'foo', 'foo'], ['one', 'two', 'one', 'two']], names=['A', 'B'])) assert_frame_equal(result, expected) def test_groupby_head_tail(): df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B']) g_as = df.groupby('A', as_index=True) g_not_as = df.groupby('A', as_index=False) # as_index= False, much easier assert_frame_equal(df.loc[[0, 2]], g_not_as.head(1)) assert_frame_equal(df.loc[[1, 2]], g_not_as.tail(1)) empty_not_as = DataFrame(columns=df.columns, index=pd.Index([], dtype=df.index.dtype)) empty_not_as['A'] = empty_not_as['A'].astype(df.A.dtype) empty_not_as['B'] = empty_not_as['B'].astype(df.B.dtype) assert_frame_equal(empty_not_as, g_not_as.head(0)) assert_frame_equal(empty_not_as, g_not_as.tail(0)) assert_frame_equal(empty_not_as, g_not_as.head(-1)) assert_frame_equal(empty_not_as, g_not_as.tail(-1)) assert_frame_equal(df, g_not_as.head(7)) # contains all assert_frame_equal(df, g_not_as.tail(7)) # as_index=True, (used to be different) df_as = df assert_frame_equal(df_as.loc[[0, 2]], g_as.head(1)) assert_frame_equal(df_as.loc[[1, 2]], g_as.tail(1)) empty_as = DataFrame(index=df_as.index[:0], columns=df.columns) empty_as['A'] = empty_not_as['A'].astype(df.A.dtype) empty_as['B'] = empty_not_as['B'].astype(df.B.dtype) assert_frame_equal(empty_as, g_as.head(0)) assert_frame_equal(empty_as, g_as.tail(0)) assert_frame_equal(empty_as, g_as.head(-1)) assert_frame_equal(empty_as, g_as.tail(-1)) assert_frame_equal(df_as, g_as.head(7)) # contains all assert_frame_equal(df_as, g_as.tail(7)) # test with selection assert_frame_equal(g_as[[]].head(1), df_as.loc[[0, 2], []]) assert_frame_equal(g_as[['A']].head(1), df_as.loc[[0, 2], ['A']]) assert_frame_equal(g_as[['B']].head(1), df_as.loc[[0, 2], ['B']]) assert_frame_equal(g_as[['A', 'B']].head(1), df_as.loc[[0, 2]]) assert_frame_equal(g_not_as[[]].head(1), df_as.loc[[0, 2], []]) assert_frame_equal(g_not_as[['A']].head(1), df_as.loc[[0, 2], ['A']]) assert_frame_equal(g_not_as[['B']].head(1), df_as.loc[[0, 2], ['B']]) assert_frame_equal(g_not_as[['A', 'B']].head(1), df_as.loc[[0, 2]]) def test_group_selection_cache(): # GH 12839 nth, head, and tail should return same result consistently df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B']) expected = df.iloc[[0, 2]].set_index('A') g = df.groupby('A') result1 = g.head(n=2) result2 = g.nth(0) assert_frame_equal(result1, df) assert_frame_equal(result2, expected) g = df.groupby('A') result1 = g.tail(n=2) result2 = g.nth(0) assert_frame_equal(result1, df) assert_frame_equal(result2, expected) g = df.groupby('A') result1 = g.nth(0) result2 = g.head(n=2) assert_frame_equal(result1, expected) assert_frame_equal(result2, df) g = df.groupby('A') result1 = g.nth(0) result2 = g.tail(n=2) assert_frame_equal(result1, expected) assert_frame_equal(result2, df) def test_nth_empty(): # GH 16064 df = DataFrame(index=[0], columns=['a', 'b', 'c']) result = df.groupby('a').nth(10) expected = DataFrame(index=Index([], name='a'), columns=['b', 'c']) assert_frame_equal(result, expected) result = df.groupby(['a', 'b']).nth(10) expected = DataFrame(index=MultiIndex([[], []], [[], []], names=['a', 'b']), columns=['c']) assert_frame_equal(result, expected)
kdebrab/pandas
pandas/tests/groupby/test_nth.py
pandas/io/json/normalize.py
# -*- coding: utf-8 -*- import warnings import pandas as pd import pandas.util.testing as tm from pandas import MultiIndex, compat from pandas.compat import PY3, range, u def test_dtype_str(indices): dtype = indices.dtype_str assert isinstance(dtype, compat.string_types) assert dtype == str(indices.dtype) def test_format(idx): idx.format() idx[:0].format() def test_format_integer_names(): index = MultiIndex(levels=[[0, 1], [0, 1]], labels=[[0, 0, 1, 1], [0, 1, 0, 1]], names=[0, 1]) index.format(names=True) def test_format_sparse_config(idx): warn_filters = warnings.filters warnings.filterwarnings('ignore', category=FutureWarning, module=".*format") # GH1538 pd.set_option('display.multi_sparse', False) result = idx.format() assert result[1] == 'foo two' tm.reset_display_options() warnings.filters = warn_filters def test_format_sparse_display(): index = MultiIndex(levels=[[0, 1], [0, 1], [0, 1], [0]], labels=[[0, 0, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0]]) result = index.format() assert result[3] == '1 0 0 0' def test_repr_with_unicode_data(): with pd.core.config.option_context("display.encoding", 'UTF-8'): d = {"a": [u("\u05d0"), 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]} index = pd.DataFrame(d).set_index(["a", "b"]).index assert "\\u" not in repr(index) # we don't want unicode-escaped def test_repr_roundtrip(): mi = MultiIndex.from_product([list('ab'), range(3)], names=['first', 'second']) str(mi) if PY3: tm.assert_index_equal(eval(repr(mi)), mi, exact=True) else: result = eval(repr(mi)) # string coerces to unicode tm.assert_index_equal(result, mi, exact=False) assert mi.get_level_values('first').inferred_type == 'string' assert result.get_level_values('first').inferred_type == 'unicode' mi_u = MultiIndex.from_product( [list(u'ab'), range(3)], names=['first', 'second']) result = eval(repr(mi_u)) tm.assert_index_equal(result, mi_u, exact=True) # formatting if PY3: str(mi) else: compat.text_type(mi) # long format mi = MultiIndex.from_product([list('abcdefg'), range(10)], names=['first', 'second']) if PY3: tm.assert_index_equal(eval(repr(mi)), mi, exact=True) else: result = eval(repr(mi)) # string coerces to unicode tm.assert_index_equal(result, mi, exact=False) assert mi.get_level_values('first').inferred_type == 'string' assert result.get_level_values('first').inferred_type == 'unicode' result = eval(repr(mi_u)) tm.assert_index_equal(result, mi_u, exact=True) def test_str(): # tested elsewhere pass def test_unicode_string_with_unicode(): d = {"a": [u("\u05d0"), 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]} idx = pd.DataFrame(d).set_index(["a", "b"]).index if PY3: str(idx) else: compat.text_type(idx) def test_bytestring_with_unicode(): d = {"a": [u("\u05d0"), 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]} idx = pd.DataFrame(d).set_index(["a", "b"]).index if PY3: bytes(idx) else: str(idx) def test_repr_max_seq_item_setting(idx): # GH10182 idx = idx.repeat(50) with pd.option_context("display.max_seq_items", None): repr(idx) assert '...' not in str(idx)
import numpy as np import pandas as pd from pandas import DataFrame, MultiIndex, Index, Series, isna, Timestamp from pandas.compat import lrange from pandas.util.testing import ( assert_frame_equal, assert_produces_warning, assert_series_equal) import pytest def test_first_last_nth(df): # tests for first / last / nth grouped = df.groupby('A') first = grouped.first() expected = df.loc[[1, 0], ['B', 'C', 'D']] expected.index = Index(['bar', 'foo'], name='A') expected = expected.sort_index() assert_frame_equal(first, expected) nth = grouped.nth(0) assert_frame_equal(nth, expected) last = grouped.last() expected = df.loc[[5, 7], ['B', 'C', 'D']] expected.index = Index(['bar', 'foo'], name='A') assert_frame_equal(last, expected) nth = grouped.nth(-1) assert_frame_equal(nth, expected) nth = grouped.nth(1) expected = df.loc[[2, 3], ['B', 'C', 'D']].copy() expected.index = Index(['foo', 'bar'], name='A') expected = expected.sort_index() assert_frame_equal(nth, expected) # it works! grouped['B'].first() grouped['B'].last() grouped['B'].nth(0) df.loc[df['A'] == 'foo', 'B'] = np.nan assert isna(grouped['B'].first()['foo']) assert isna(grouped['B'].last()['foo']) assert isna(grouped['B'].nth(0)['foo']) # v0.14.0 whatsnew df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B']) g = df.groupby('A') result = g.first() expected = df.iloc[[1, 2]].set_index('A') assert_frame_equal(result, expected) expected = df.iloc[[1, 2]].set_index('A') result = g.nth(0, dropna='any') assert_frame_equal(result, expected) def test_first_last_nth_dtypes(df_mixed_floats): df = df_mixed_floats.copy() df['E'] = True df['F'] = 1 # tests for first / last / nth grouped = df.groupby('A') first = grouped.first() expected = df.loc[[1, 0], ['B', 'C', 'D', 'E', 'F']] expected.index = Index(['bar', 'foo'], name='A') expected = expected.sort_index() assert_frame_equal(first, expected) last = grouped.last() expected = df.loc[[5, 7], ['B', 'C', 'D', 'E', 'F']] expected.index = Index(['bar', 'foo'], name='A') expected = expected.sort_index() assert_frame_equal(last, expected) nth = grouped.nth(1) expected = df.loc[[3, 2], ['B', 'C', 'D', 'E', 'F']] expected.index = Index(['bar', 'foo'], name='A') expected = expected.sort_index() assert_frame_equal(nth, expected) # GH 2763, first/last shifting dtypes idx = lrange(10) idx.append(9) s = Series(data=lrange(11), index=idx, name='IntCol') assert s.dtype == 'int64' f = s.groupby(level=0).first() assert f.dtype == 'int64' def test_nth(): df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B']) g = df.groupby('A') assert_frame_equal(g.nth(0), df.iloc[[0, 2]].set_index('A')) assert_frame_equal(g.nth(1), df.iloc[[1]].set_index('A')) assert_frame_equal(g.nth(2), df.loc[[]].set_index('A')) assert_frame_equal(g.nth(-1), df.iloc[[1, 2]].set_index('A')) assert_frame_equal(g.nth(-2), df.iloc[[0]].set_index('A')) assert_frame_equal(g.nth(-3), df.loc[[]].set_index('A')) assert_series_equal(g.B.nth(0), df.set_index('A').B.iloc[[0, 2]]) assert_series_equal(g.B.nth(1), df.set_index('A').B.iloc[[1]]) assert_frame_equal(g[['B']].nth(0), df.loc[[0, 2], ['A', 'B']].set_index('A')) exp = df.set_index('A') assert_frame_equal(g.nth(0, dropna='any'), exp.iloc[[1, 2]]) assert_frame_equal(g.nth(-1, dropna='any'), exp.iloc[[1, 2]]) exp['B'] = np.nan assert_frame_equal(g.nth(7, dropna='any'), exp.iloc[[1, 2]]) assert_frame_equal(g.nth(2, dropna='any'), exp.iloc[[1, 2]]) # out of bounds, regression from 0.13.1 # GH 6621 df = DataFrame({'color': {0: 'green', 1: 'green', 2: 'red', 3: 'red', 4: 'red'}, 'food': {0: 'ham', 1: 'eggs', 2: 'eggs', 3: 'ham', 4: 'pork'}, 'two': {0: 1.5456590000000001, 1: -0.070345000000000005, 2: -2.4004539999999999, 3: 0.46206000000000003, 4: 0.52350799999999997}, 'one': {0: 0.56573799999999996, 1: -0.9742360000000001, 2: 1.033801, 3: -0.78543499999999999, 4: 0.70422799999999997}}).set_index(['color', 'food']) result = df.groupby(level=0, as_index=False).nth(2) expected = df.iloc[[-1]] assert_frame_equal(result, expected) result = df.groupby(level=0, as_index=False).nth(3) expected = df.loc[[]] assert_frame_equal(result, expected) # GH 7559 # from the vbench df = DataFrame(np.random.randint(1, 10, (100, 2)), dtype='int64') s = df[1] g = df[0] expected = s.groupby(g).first() expected2 = s.groupby(g).apply(lambda x: x.iloc[0]) assert_series_equal(expected2, expected, check_names=False) assert expected.name == 1 assert expected2.name == 1 # validate first v = s[g == 1].iloc[0] assert expected.iloc[0] == v assert expected2.iloc[0] == v # this is NOT the same as .first (as sorted is default!) # as it keeps the order in the series (and not the group order) # related GH 7287 expected = s.groupby(g, sort=False).first() result = s.groupby(g, sort=False).nth(0, dropna='all') assert_series_equal(result, expected) # doc example df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B']) g = df.groupby('A') # PR 17493, related to issue 11038 # test Series.nth with True for dropna produces FutureWarning with assert_produces_warning(FutureWarning): result = g.B.nth(0, dropna=True) expected = g.B.first() assert_series_equal(result, expected) # test multiple nth values df = DataFrame([[1, np.nan], [1, 3], [1, 4], [5, 6], [5, 7]], columns=['A', 'B']) g = df.groupby('A') assert_frame_equal(g.nth(0), df.iloc[[0, 3]].set_index('A')) assert_frame_equal(g.nth([0]), df.iloc[[0, 3]].set_index('A')) assert_frame_equal(g.nth([0, 1]), df.iloc[[0, 1, 3, 4]].set_index('A')) assert_frame_equal( g.nth([0, -1]), df.iloc[[0, 2, 3, 4]].set_index('A')) assert_frame_equal( g.nth([0, 1, 2]), df.iloc[[0, 1, 2, 3, 4]].set_index('A')) assert_frame_equal( g.nth([0, 1, -1]), df.iloc[[0, 1, 2, 3, 4]].set_index('A')) assert_frame_equal(g.nth([2]), df.iloc[[2]].set_index('A')) assert_frame_equal(g.nth([3, 4]), df.loc[[]].set_index('A')) business_dates = pd.date_range(start='4/1/2014', end='6/30/2014', freq='B') df = DataFrame(1, index=business_dates, columns=['a', 'b']) # get the first, fourth and last two business days for each month key = [df.index.year, df.index.month] result = df.groupby(key, as_index=False).nth([0, 3, -2, -1]) expected_dates = pd.to_datetime( ['2014/4/1', '2014/4/4', '2014/4/29', '2014/4/30', '2014/5/1', '2014/5/6', '2014/5/29', '2014/5/30', '2014/6/2', '2014/6/5', '2014/6/27', '2014/6/30']) expected = DataFrame(1, columns=['a', 'b'], index=expected_dates) assert_frame_equal(result, expected) def test_nth_multi_index(three_group): # PR 9090, related to issue 8979 # test nth on MultiIndex, should match .first() grouped = three_group.groupby(['A', 'B']) result = grouped.nth(0) expected = grouped.first() assert_frame_equal(result, expected) @pytest.mark.parametrize('data, expected_first, expected_last', [ ({'id': ['A'], 'time': Timestamp('2012-02-01 14:00:00', tz='US/Central'), 'foo': [1]}, {'id': ['A'], 'time': Timestamp('2012-02-01 14:00:00', tz='US/Central'), 'foo': [1]}, {'id': ['A'], 'time': Timestamp('2012-02-01 14:00:00', tz='US/Central'), 'foo': [1]}), ({'id': ['A', 'B', 'A'], 'time': [Timestamp('2012-01-01 13:00:00', tz='America/New_York'), Timestamp('2012-02-01 14:00:00', tz='US/Central'), Timestamp('2012-03-01 12:00:00', tz='Europe/London')], 'foo': [1, 2, 3]}, {'id': ['A', 'B'], 'time': [Timestamp('2012-01-01 13:00:00', tz='America/New_York'), Timestamp('2012-02-01 14:00:00', tz='US/Central')], 'foo': [1, 2]}, {'id': ['A', 'B'], 'time': [Timestamp('2012-03-01 12:00:00', tz='Europe/London'), Timestamp('2012-02-01 14:00:00', tz='US/Central')], 'foo': [3, 2]}) ]) def test_first_last_tz(data, expected_first, expected_last): # GH15884 # Test that the timezone is retained when calling first # or last on groupby with as_index=False df = DataFrame(data) result = df.groupby('id', as_index=False).first() expected = DataFrame(expected_first) cols = ['id', 'time', 'foo'] assert_frame_equal(result[cols], expected[cols]) result = df.groupby('id', as_index=False)['time'].first() assert_frame_equal(result, expected[['id', 'time']]) result = df.groupby('id', as_index=False).last() expected = DataFrame(expected_last) cols = ['id', 'time', 'foo'] assert_frame_equal(result[cols], expected[cols]) result = df.groupby('id', as_index=False)['time'].last() assert_frame_equal(result, expected[['id', 'time']]) def test_nth_multi_index_as_expected(): # PR 9090, related to issue 8979 # test nth on MultiIndex three_group = DataFrame( {'A': ['foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar', 'foo', 'foo', 'foo'], 'B': ['one', 'one', 'one', 'two', 'one', 'one', 'one', 'two', 'two', 'two', 'one'], 'C': ['dull', 'dull', 'shiny', 'dull', 'dull', 'shiny', 'shiny', 'dull', 'shiny', 'shiny', 'shiny']}) grouped = three_group.groupby(['A', 'B']) result = grouped.nth(0) expected = DataFrame( {'C': ['dull', 'dull', 'dull', 'dull']}, index=MultiIndex.from_arrays([['bar', 'bar', 'foo', 'foo'], ['one', 'two', 'one', 'two']], names=['A', 'B'])) assert_frame_equal(result, expected) def test_groupby_head_tail(): df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B']) g_as = df.groupby('A', as_index=True) g_not_as = df.groupby('A', as_index=False) # as_index= False, much easier assert_frame_equal(df.loc[[0, 2]], g_not_as.head(1)) assert_frame_equal(df.loc[[1, 2]], g_not_as.tail(1)) empty_not_as = DataFrame(columns=df.columns, index=pd.Index([], dtype=df.index.dtype)) empty_not_as['A'] = empty_not_as['A'].astype(df.A.dtype) empty_not_as['B'] = empty_not_as['B'].astype(df.B.dtype) assert_frame_equal(empty_not_as, g_not_as.head(0)) assert_frame_equal(empty_not_as, g_not_as.tail(0)) assert_frame_equal(empty_not_as, g_not_as.head(-1)) assert_frame_equal(empty_not_as, g_not_as.tail(-1)) assert_frame_equal(df, g_not_as.head(7)) # contains all assert_frame_equal(df, g_not_as.tail(7)) # as_index=True, (used to be different) df_as = df assert_frame_equal(df_as.loc[[0, 2]], g_as.head(1)) assert_frame_equal(df_as.loc[[1, 2]], g_as.tail(1)) empty_as = DataFrame(index=df_as.index[:0], columns=df.columns) empty_as['A'] = empty_not_as['A'].astype(df.A.dtype) empty_as['B'] = empty_not_as['B'].astype(df.B.dtype) assert_frame_equal(empty_as, g_as.head(0)) assert_frame_equal(empty_as, g_as.tail(0)) assert_frame_equal(empty_as, g_as.head(-1)) assert_frame_equal(empty_as, g_as.tail(-1)) assert_frame_equal(df_as, g_as.head(7)) # contains all assert_frame_equal(df_as, g_as.tail(7)) # test with selection assert_frame_equal(g_as[[]].head(1), df_as.loc[[0, 2], []]) assert_frame_equal(g_as[['A']].head(1), df_as.loc[[0, 2], ['A']]) assert_frame_equal(g_as[['B']].head(1), df_as.loc[[0, 2], ['B']]) assert_frame_equal(g_as[['A', 'B']].head(1), df_as.loc[[0, 2]]) assert_frame_equal(g_not_as[[]].head(1), df_as.loc[[0, 2], []]) assert_frame_equal(g_not_as[['A']].head(1), df_as.loc[[0, 2], ['A']]) assert_frame_equal(g_not_as[['B']].head(1), df_as.loc[[0, 2], ['B']]) assert_frame_equal(g_not_as[['A', 'B']].head(1), df_as.loc[[0, 2]]) def test_group_selection_cache(): # GH 12839 nth, head, and tail should return same result consistently df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B']) expected = df.iloc[[0, 2]].set_index('A') g = df.groupby('A') result1 = g.head(n=2) result2 = g.nth(0) assert_frame_equal(result1, df) assert_frame_equal(result2, expected) g = df.groupby('A') result1 = g.tail(n=2) result2 = g.nth(0) assert_frame_equal(result1, df) assert_frame_equal(result2, expected) g = df.groupby('A') result1 = g.nth(0) result2 = g.head(n=2) assert_frame_equal(result1, expected) assert_frame_equal(result2, df) g = df.groupby('A') result1 = g.nth(0) result2 = g.tail(n=2) assert_frame_equal(result1, expected) assert_frame_equal(result2, df) def test_nth_empty(): # GH 16064 df = DataFrame(index=[0], columns=['a', 'b', 'c']) result = df.groupby('a').nth(10) expected = DataFrame(index=Index([], name='a'), columns=['b', 'c']) assert_frame_equal(result, expected) result = df.groupby(['a', 'b']).nth(10) expected = DataFrame(index=MultiIndex([[], []], [[], []], names=['a', 'b']), columns=['c']) assert_frame_equal(result, expected)
kdebrab/pandas
pandas/tests/groupby/test_nth.py
pandas/tests/indexes/multi/test_format.py
# -*- coding: utf-8 -*- import attr from navmazing import NavigateToAttribute from navmazing import NavigateToSibling from widgetastic.widget import NoSuchElementException from widgetastic.widget import Text from widgetastic.widget import View from widgetastic_patternfly import BootstrapNav from widgetastic_patternfly import BreadCrumb from widgetastic_patternfly import Button from widgetastic_patternfly import Dropdown from cfme.base.ui import BaseLoggedInPage from cfme.common import Taggable from cfme.common import TagPageView from cfme.exceptions import ItemNotFound from cfme.modeling.base import BaseCollection from cfme.modeling.base import BaseEntity from cfme.utils.appliance.implementations.ui import CFMENavigateStep from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.appliance.implementations.ui import navigator from cfme.utils.log import logger from cfme.utils.providers import get_crud_by_name from cfme.utils.wait import wait_for from widgetastic_manageiq import Accordion from widgetastic_manageiq import BaseEntitiesView from widgetastic_manageiq import ItemsToolBarViewSelector from widgetastic_manageiq import ManageIQTree from widgetastic_manageiq import Search from widgetastic_manageiq import SummaryTable class VolumeSnapshotToolbar(View): """The toolbar on the Volume Snapshot page""" policy = Dropdown('Policy') download = Dropdown('Download') view_selector = View.nested(ItemsToolBarViewSelector) class VolumeSnapshotDetailsToolbar(View): """The toolbar on the Volume Snapshot detail page""" configuration = Dropdown('Configuration') policy = Dropdown('Policy') download = Button('Print or export summary') class VolumeSnapshotDetailsEntities(View): """The entities on the Volume Snapshot detail page""" breadcrumb = BreadCrumb() title = Text('.//div[@id="center_div" or @id="main-content"]//h1') properties = SummaryTable('Properties') relationships = SummaryTable('Relationships') smart_management = SummaryTable('Smart Management') class VolumeSnapshotDetailSidebar(View): """The accordion on the Volume Snapshot details page""" @View.nested class properties(Accordion): # noqa tree = ManageIQTree() @View.nested class relationships(Accordion): # noqa tree = ManageIQTree() class VolumeSnapshotView(BaseLoggedInPage): """A base view for all the Volume Snapshot pages""" @property def in_volume_snapshots(self): return ( self.logged_in_as_current_user and self.navigation.currently_selected == ['Storage', 'Block Storage', 'Volume Snapshots'] ) @property def is_displayed(self): return self.in_volume_snapshots class VolumeSnapshotAllView(VolumeSnapshotView): """The all Volume Snapshot page""" toolbar = View.nested(VolumeSnapshotToolbar) search = View.nested(Search) including_entities = View.include(BaseEntitiesView, use_parent=True) @property def is_displayed(self): return ( self.in_volume_snapshots and self.entities.title.text == 'Cloud Volume Snapshots') @View.nested class my_filters(Accordion): # noqa ACCORDION_NAME = "My Filters" navigation = BootstrapNav('.//div/ul') tree = ManageIQTree() class VolumeSnapshotDetailsView(VolumeSnapshotView): """The detail Volume Snapshot page""" @property def is_displayed(self): obj = self.context['object'] return ( self.in_volume_snapshots and self.entities.title.text == obj.expected_details_title and self.entities.breadcrumb.active_location == obj.expected_details_breadcrumb ) toolbar = View.nested(VolumeSnapshotDetailsToolbar) sidebar = View.nested(VolumeSnapshotDetailSidebar) entities = View.nested(VolumeSnapshotDetailsEntities) @attr.s class VolumeSnapshot(BaseEntity, Taggable): """ Model of an Storage Volume Snapshots in cfme Args: name: name of the snapshot provider: provider """ name = attr.ib() provider = attr.ib() def refresh(self): self.provider.refresh_provider_relationships() self.browser.refresh() @property def exists(self): """ check for snapshot exist on UI. Returns: :py:class:`bool` """ view = navigate_to(self.parent, 'All') return self.name in view.entities.all_entity_names @property def status(self): """ status of cloud volume snapshot. Returns: :py:class:`str` Status of volume snapshot. """ view = navigate_to(self.parent, 'All') view.toolbar.view_selector.select("List View") try: ent = view.entities.get_entity(name=self.name, surf_pages=True) return ent.data["status"] except ItemNotFound: return False @property def size(self): """ size of cloud volume snapshot. Returns: :py:class:`int` size of volume snapshot in GB. """ view = navigate_to(self, 'Details') return int(view.entities.properties.get_text_of('Size').split()[0]) @property def volume_name(self): """ volume name of snapshot. Returns: :py:class:`str` respective volume name. """ view = navigate_to(self, 'Details') return view.entities.relationships.get_text_of('Cloud Volume') @property def tenant_name(self): """ Tenant name of snapshot. Returns: :py:class:`str` respective tenant name for snapshot. """ view = navigate_to(self, 'Details') return view.entities.relationships.get_text_of('Cloud Tenants') def delete(self, wait=True): """Delete snapshot """ view = navigate_to(self, 'Details') view.toolbar.configuration.item_select('Delete Cloud Volume Snapshot') view.flash.assert_success_message('Delete initiated for 1 Cloud Volume Snapshot.') if wait: wait_for( lambda: not self.exists, message="Wait snapshot to disappear", delay=20, timeout=800, fail_func=self.refresh ) @attr.s class VolumeSnapshotCollection(BaseCollection): """Collection object for :py:class:`cfme.storage.volume_snapshots.VolumeSnapshot`""" ENTITY = VolumeSnapshot def all(self): """returning all Snapshot objects for respective storage manager type""" view = navigate_to(self, 'All') view.toolbar.view_selector.select("List View") snapshots = [] try: if 'provider' in self.filters: for item in view.entities.elements.read(): if self.filters.get('provider').name in item['Storage Manager']: snapshots.append(self.instantiate(name=item['Name'], provider=self.filters.get('provider'))) else: for item in view.entities.elements.read(): provider_name = item['Storage Manager'].split()[0] provider = get_crud_by_name(provider_name) snapshots.append(self.instantiate(name=item['Name'], provider=provider)) except NoSuchElementException: if snapshots: logger.error('VolumeSnapshotCollection: ' 'NoSuchElementException in the middle of entities read') else: logger.warning('The snapshot table is probably not present or empty') return snapshots @navigator.register(VolumeSnapshotCollection, 'All') class All(CFMENavigateStep): VIEW = VolumeSnapshotAllView prerequisite = NavigateToAttribute('appliance.server', 'LoggedIn') def step(self, *args, **kwargs): self.prerequisite_view.navigation.select('Storage', 'Block Storage', 'Volume Snapshots') @navigator.register(VolumeSnapshot, 'Details') class Details(CFMENavigateStep): VIEW = VolumeSnapshotDetailsView prerequisite = NavigateToAttribute('parent', 'All') def step(self, *args, **kwargs): try: self.prerequisite_view.entities.get_entity(name=self.obj.name, surf_pages=True).click() except ItemNotFound: raise ItemNotFound( 'Could not locate volume snapshot {}'.format(self.obj.name) ) @navigator.register(VolumeSnapshot, 'EditTagsFromDetails') class SnapshotDetailEditTag(CFMENavigateStep): """ This navigation destination help to Taggable""" VIEW = TagPageView prerequisite = NavigateToSibling('Details') def step(self, *args, **kwargs): self.prerequisite_view.toolbar.policy.item_select('Edit Tags')
import pytest from cfme import test_requirements pytestmark = [test_requirements.replication] @pytest.mark.manual def test_replication_powertoggle(): """ power toggle from global to remote Polarion: assignee: mnadeem casecomponent: Replication caseimportance: critical initialEstimate: 1/12h testSteps: 1. Have a VM created in the provider in the Remote region subscribed to Global. 2. Turn the VM off using the Global appliance. 3. Turn the VM on using the Global appliance. expectedResults: 1. 2. VM state changes to off in the Remote and Global appliance. 3. VM state changes to on in the Remote and Global appliance. . """ pass @pytest.mark.manual @pytest.mark.tier(2) def test_replication_appliance_add_single_subscription(): """ Add one remote subscription to global region Polarion: assignee: mnadeem casecomponent: Replication caseimportance: critical initialEstimate: 1/12h startsin: 5.7 testSteps: 1. Configure first appliance as Global. 2. Configure second appliance as Remote, subscribed to Global. expectedResults: 1. 2. No error. Appliance subscribed. """ pass @pytest.mark.manual @pytest.mark.tier(3) def test_replication_delete_remote_from_global(): """ Delete remote subscription from global region Polarion: assignee: mnadeem casecomponent: Replication caseimportance: critical initialEstimate: 1/5h testSteps: 1. Have A Remote subscribed to Global. 2. Remove the Remote subscription from Global. expectedResults: 1. 2. No error. Appliance unsubscribed. """ pass @pytest.mark.manual def test_replication_low_bandwidth(): """ ~5MB/s up/down Polarion: assignee: mnadeem casecomponent: Replication initialEstimate: 1/4h """ pass @pytest.mark.manual @pytest.mark.tier(3) def test_replication_re_add_deleted_remote(): """ Re-add deleted remote region Polarion: assignee: mnadeem casecomponent: Replication initialEstimate: 1/12h testSteps: 1. Have A Remote subscribed to Global. 2. Remove the Remote subscription from Global. 3. Add the Remote to Global again expectedResults: 1. 2. No error. Appliance subscribed. """ pass @pytest.mark.manual @pytest.mark.tier(3) def test_replication_central_admin_ansible_playbook_service_from_global(): """ Playbook service is ordered from the master region catalog. Polarion: assignee: izapolsk casecomponent: Replication subcomponent: Ansible caseimportance: medium initialEstimate: 1/3h """ pass @pytest.mark.manual @pytest.mark.tier(1) def test_replication_remote_to_global_by_ip_pglogical(): """ Test replication from remote region to global using any data type (provider,event,etc) Polarion: assignee: mnadeem casecomponent: Replication caseimportance: critical initialEstimate: 1/4h startsin: 5.6 testSteps: 1. Have A Remote subscribed to Global. 2. Create a provider in remote region. 3. Check the provider appeared in the Global. expectedResults: 1. 2. 3. Provider appeared in the Global. """ pass @pytest.mark.manual @pytest.mark.tier(1) def test_replication_appliance_set_type_global_ui(): """ Set appliance replication type to "Global" and add subscription in the UI Polarion: assignee: mnadeem casecomponent: Replication caseimportance: critical initialEstimate: 1/6h testtype: integration testSteps: 1. Have two appliances with same v2 keys and different regions 2. Set one as Global and the other as Remote and add subscribe the Remote to the Global expectedResults: 1. 2. No error, appliance subscribed. """ pass @pytest.mark.manual @pytest.mark.tier(2) def test_replication_appliance_add_multi_subscription(): """ add two or more subscriptions to global Polarion: assignee: mnadeem casecomponent: Replication initialEstimate: 1/4h startsin: 5.7 testSteps: 1. Have three appliances with same v2 keys and different regions 2. Set one as Global and the other two as Remote and add subscribe the Remotes to the Global expectedResults: 1. 2. appliances subscribed. """ pass @pytest.mark.manual def test_replication_network_dropped_packets(): """ 10% dropped packets Polarion: assignee: mnadeem casecomponent: Replication initialEstimate: 1/4h """ pass @pytest.mark.manual @pytest.mark.tier(1) def test_replication_global_region_dashboard(): """ Global dashboard show remote data Polarion: assignee: mnadeem casecomponent: Replication initialEstimate: 1/4h testSteps: 1. Have a VM created in the provider in the Remote region which is subscribed to Global. 2. Check the dashboard on the Global shows data from the Remote region. expectedResults: 1. 2. Dashboard on the Global displays data from the Remote region """ pass @pytest.mark.manual @pytest.mark.tier(1) def test_replication_global_to_remote_new_vm_from_template(): """ Create a new VM from template in remote region from global region Polarion: assignee: mnadeem casecomponent: Replication caseimportance: critical initialEstimate: 1/6h testSteps: 1. Configure first appliance as Global. 2. Configure second appliance as Remote, subscribed to Global. 3. Create a VM from template in Remote region using the Global appliance. expectedResults: 1. 2. 3. VM created in the Remote, no errors. """ pass @pytest.mark.manual @pytest.mark.tier(1) def test_replication_subscription_revalidation_pglogical(): """ Subscription validation passes for replication subscriptions which have been validated and successfully saved. Polarion: assignee: mnadeem casecomponent: Replication caseimportance: medium initialEstimate: 1/12h testSteps: 1. Attempt to validate the subscription expectedResults: 1. Validation succeeds as this subscription was successfully saved and is currently replicating """ pass
apagac/cfme_tests
cfme/tests/test_replication.py
cfme/storage/volume_snapshot.py
""" NOT TESTED YET """ import re from cfme.utils.conf import cfme_data from cfme.utils.log import logger from cfme.utils.template.base import log_wrap from cfme.utils.template.base import ProviderTemplateUpload from cfme.utils.template.base import TemplateUploadException class RHEVMTemplateUpload(ProviderTemplateUpload): provider_type = 'rhevm' log_name = 'RHEVM' image_pattern = re.compile( r'<a href="?\'?([^"\']*(?:(?:rhevm|ovirt)[^"\']*\.(?:qcow2|qc2))[^"\'>]*)') @log_wrap('add glance to rhevm provider') def add_glance_to_provider(self): """Add glance as an external provider if needed""" glance_data = cfme_data.template_upload.get(self.glance_key) if self.mgmt.does_glance_server_exist(self.glance_key): logger.info('RHEVM provider already has glance added, skipping step') else: self.mgmt.add_glance_server(name=self.glance_key, description=self.glance_key, url=glance_data.url, requires_authentication=False) return True @log_wrap("import template from Glance server") def import_template_from_glance(self): """Import the template from glance to local rhevm datastore, sucks.""" self.mgmt.import_glance_image( source_storage_domain_name=self.glance_key, target_cluster_name=self.provider_data.template_upload.cluster, source_template_name=self.image_name, target_template_name=self.temp_template_name, target_storage_domain_name=self.provider_data.template_upload.storage_domain) mgmt_network = self.provider_data.template_upload.get('management_network') rv_tmpl = self.mgmt.get_template(self.temp_template_name) if mgmt_network: # network devices, qcow template doesn't have any temp_nics = rv_tmpl.get_nics() nic_args = dict(network_name=mgmt_network, nic_name='eth0') if 'eth0' not in [n.name for n in temp_nics]: rv_tmpl.add_nic(**nic_args) else: rv_tmpl.update_nic(**nic_args) return True @log_wrap('Deploy template to vm - before templatizing') def deploy_vm_from_template(self): """Deploy a VM from the raw template with resource limits set from yaml""" stream_hardware = cfme_data.template_upload.hardware[self.stream] self.mgmt.get_template(self.temp_template_name).deploy( vm_name=self.temp_vm_name, cluster=self.provider_data.template_upload.cluster, storage_domain=self.provider_data.template_upload.storage_domain, cpu=stream_hardware.cores, sockets=stream_hardware.sockets, ram=int(stream_hardware.memory) * 2**30) # GB -> B # check, if the vm is really there if not self.mgmt.does_vm_exist(self.temp_vm_name): raise TemplateUploadException('Failed to deploy VM from imported template') return True @log_wrap('Add db disk to temp vm') def add_disk_to_vm(self): """Add a disk with specs from cfme_data.template_upload Generally for database disk """ temp_vm = self.mgmt.get_vm(self.temp_vm_name) if temp_vm.get_disks_count() > 1: logger.warning('%s Warning: found more than one disk in existing VM (%s).', self.provider_key, self.temp_vm_name) return rhevm_specs = cfme_data.template_upload.template_upload_rhevm disk_kwargs = dict(storage_domain=self.provider_data.template_upload.storage_domain, size=rhevm_specs.get('disk_size', 5000000000), interface=rhevm_specs.get('disk_interface', 'virtio'), format=rhevm_specs.get('disk_format', 'cow'), name=rhevm_specs.get('disk_name')) temp_vm.add_disk(**disk_kwargs) # check, if there are two disks if temp_vm.get_disks_count() < 2: raise TemplateUploadException('%s disk failed to add with specs: %r', self.provider_key, disk_kwargs) logger.info('%s:%s Successfully added disk', self.provider_key, self.temp_vm_name) return True @log_wrap('templatize temp vm with disk') def templatize_vm(self): """Templatizes temporary VM. Result is template with two disks. """ self.mgmt.get_vm(self.temp_vm_name).mark_as_template( template_name=self.template_name, cluster_name=self.provider_data.template_upload.cluster, storage_domain_name=self.provider_data.template_upload.get('template_domain', None), delete=False # leave vm in place in case it fails, for debug ) # check, if template is really there if not self.mgmt.does_template_exist(self.template_name): raise TemplateUploadException('%s templatizing %s to %s FAILED', self.provider_key, self.temp_vm_name, self.template_name) logger.info(":%s successfully templatized %s to %s", self.provider_key, self.temp_vm_name, self.template_name) return True @log_wrap('cleanup temp resources') def teardown(self): """Cleans up all the mess that the previous functions left behind.""" logger.info('%s Deleting temp_vm "%s"', self.provider_key, self.temp_vm_name) if self.mgmt.does_vm_exist(self.temp_vm_name): self.mgmt.get_vm(self.temp_vm_name).cleanup() logger.info('%s Deleting temp_template "%s"on storage domain', self.provider_key, self.temp_template_name) if self.mgmt.does_template_exist(self.temp_template_name): self.mgmt.get_template(self.temp_template_name).cleanup() return True def run(self): """call methods for individual steps of CFME templatization of qcow2 image from glance""" try: self.glance_upload() self.add_glance_to_provider() self.import_template_from_glance() self.deploy_vm_from_template() if self.stream == 'upstream': self.manageiq_cleanup() self.add_disk_to_vm() self.templatize_vm() return True except Exception: logger.exception('template creation failed for provider {}'.format( self.provider_data.name)) return False
import pytest from cfme import test_requirements pytestmark = [test_requirements.replication] @pytest.mark.manual def test_replication_powertoggle(): """ power toggle from global to remote Polarion: assignee: mnadeem casecomponent: Replication caseimportance: critical initialEstimate: 1/12h testSteps: 1. Have a VM created in the provider in the Remote region subscribed to Global. 2. Turn the VM off using the Global appliance. 3. Turn the VM on using the Global appliance. expectedResults: 1. 2. VM state changes to off in the Remote and Global appliance. 3. VM state changes to on in the Remote and Global appliance. . """ pass @pytest.mark.manual @pytest.mark.tier(2) def test_replication_appliance_add_single_subscription(): """ Add one remote subscription to global region Polarion: assignee: mnadeem casecomponent: Replication caseimportance: critical initialEstimate: 1/12h startsin: 5.7 testSteps: 1. Configure first appliance as Global. 2. Configure second appliance as Remote, subscribed to Global. expectedResults: 1. 2. No error. Appliance subscribed. """ pass @pytest.mark.manual @pytest.mark.tier(3) def test_replication_delete_remote_from_global(): """ Delete remote subscription from global region Polarion: assignee: mnadeem casecomponent: Replication caseimportance: critical initialEstimate: 1/5h testSteps: 1. Have A Remote subscribed to Global. 2. Remove the Remote subscription from Global. expectedResults: 1. 2. No error. Appliance unsubscribed. """ pass @pytest.mark.manual def test_replication_low_bandwidth(): """ ~5MB/s up/down Polarion: assignee: mnadeem casecomponent: Replication initialEstimate: 1/4h """ pass @pytest.mark.manual @pytest.mark.tier(3) def test_replication_re_add_deleted_remote(): """ Re-add deleted remote region Polarion: assignee: mnadeem casecomponent: Replication initialEstimate: 1/12h testSteps: 1. Have A Remote subscribed to Global. 2. Remove the Remote subscription from Global. 3. Add the Remote to Global again expectedResults: 1. 2. No error. Appliance subscribed. """ pass @pytest.mark.manual @pytest.mark.tier(3) def test_replication_central_admin_ansible_playbook_service_from_global(): """ Playbook service is ordered from the master region catalog. Polarion: assignee: izapolsk casecomponent: Replication subcomponent: Ansible caseimportance: medium initialEstimate: 1/3h """ pass @pytest.mark.manual @pytest.mark.tier(1) def test_replication_remote_to_global_by_ip_pglogical(): """ Test replication from remote region to global using any data type (provider,event,etc) Polarion: assignee: mnadeem casecomponent: Replication caseimportance: critical initialEstimate: 1/4h startsin: 5.6 testSteps: 1. Have A Remote subscribed to Global. 2. Create a provider in remote region. 3. Check the provider appeared in the Global. expectedResults: 1. 2. 3. Provider appeared in the Global. """ pass @pytest.mark.manual @pytest.mark.tier(1) def test_replication_appliance_set_type_global_ui(): """ Set appliance replication type to "Global" and add subscription in the UI Polarion: assignee: mnadeem casecomponent: Replication caseimportance: critical initialEstimate: 1/6h testtype: integration testSteps: 1. Have two appliances with same v2 keys and different regions 2. Set one as Global and the other as Remote and add subscribe the Remote to the Global expectedResults: 1. 2. No error, appliance subscribed. """ pass @pytest.mark.manual @pytest.mark.tier(2) def test_replication_appliance_add_multi_subscription(): """ add two or more subscriptions to global Polarion: assignee: mnadeem casecomponent: Replication initialEstimate: 1/4h startsin: 5.7 testSteps: 1. Have three appliances with same v2 keys and different regions 2. Set one as Global and the other two as Remote and add subscribe the Remotes to the Global expectedResults: 1. 2. appliances subscribed. """ pass @pytest.mark.manual def test_replication_network_dropped_packets(): """ 10% dropped packets Polarion: assignee: mnadeem casecomponent: Replication initialEstimate: 1/4h """ pass @pytest.mark.manual @pytest.mark.tier(1) def test_replication_global_region_dashboard(): """ Global dashboard show remote data Polarion: assignee: mnadeem casecomponent: Replication initialEstimate: 1/4h testSteps: 1. Have a VM created in the provider in the Remote region which is subscribed to Global. 2. Check the dashboard on the Global shows data from the Remote region. expectedResults: 1. 2. Dashboard on the Global displays data from the Remote region """ pass @pytest.mark.manual @pytest.mark.tier(1) def test_replication_global_to_remote_new_vm_from_template(): """ Create a new VM from template in remote region from global region Polarion: assignee: mnadeem casecomponent: Replication caseimportance: critical initialEstimate: 1/6h testSteps: 1. Configure first appliance as Global. 2. Configure second appliance as Remote, subscribed to Global. 3. Create a VM from template in Remote region using the Global appliance. expectedResults: 1. 2. 3. VM created in the Remote, no errors. """ pass @pytest.mark.manual @pytest.mark.tier(1) def test_replication_subscription_revalidation_pglogical(): """ Subscription validation passes for replication subscriptions which have been validated and successfully saved. Polarion: assignee: mnadeem casecomponent: Replication caseimportance: medium initialEstimate: 1/12h testSteps: 1. Attempt to validate the subscription expectedResults: 1. Validation succeeds as this subscription was successfully saved and is currently replicating """ pass
apagac/cfme_tests
cfme/tests/test_replication.py
cfme/utils/template/rhevm.py
"""Test the helper method for writing tests.""" import asyncio import functools as ft import json import logging import os import uuid import sys import threading from collections import OrderedDict from contextlib import contextmanager from datetime import timedelta from io import StringIO from unittest.mock import MagicMock, Mock, patch import homeassistant.util.dt as date_util import homeassistant.util.yaml.loader as yaml_loader import homeassistant.util.yaml.dumper as yaml_dumper from homeassistant import auth, config_entries, core as ha, loader from homeassistant.auth import ( models as auth_models, auth_store, providers as auth_providers, permissions as auth_permissions) from homeassistant.auth.permissions import system_policies from homeassistant.components import mqtt, recorder from homeassistant.config import async_process_component_config from homeassistant.const import ( ATTR_DISCOVERED, ATTR_SERVICE, DEVICE_DEFAULT_NAME, EVENT_HOMEASSISTANT_CLOSE, EVENT_PLATFORM_DISCOVERED, EVENT_STATE_CHANGED, EVENT_TIME_CHANGED, SERVER_PORT, STATE_ON, STATE_OFF) from homeassistant.helpers import ( area_registry, device_registry, entity, entity_platform, entity_registry, intent, restore_state, storage) from homeassistant.setup import async_setup_component, setup_component from homeassistant.util.unit_system import METRIC_SYSTEM from homeassistant.util.async_ import ( run_callback_threadsafe, run_coroutine_threadsafe) _TEST_INSTANCE_PORT = SERVER_PORT _LOGGER = logging.getLogger(__name__) INSTANCES = [] CLIENT_ID = 'https://example.com/app' CLIENT_REDIRECT_URI = 'https://example.com/app/callback' def threadsafe_callback_factory(func): """Create threadsafe functions out of callbacks. Callback needs to have `hass` as first argument. """ @ft.wraps(func) def threadsafe(*args, **kwargs): """Call func threadsafe.""" hass = args[0] return run_callback_threadsafe( hass.loop, ft.partial(func, *args, **kwargs)).result() return threadsafe def threadsafe_coroutine_factory(func): """Create threadsafe functions out of coroutine. Callback needs to have `hass` as first argument. """ @ft.wraps(func) def threadsafe(*args, **kwargs): """Call func threadsafe.""" hass = args[0] return run_coroutine_threadsafe( func(*args, **kwargs), hass.loop).result() return threadsafe def get_test_config_dir(*add_path): """Return a path to a test config dir.""" return os.path.join(os.path.dirname(__file__), 'testing_config', *add_path) def get_test_home_assistant(): """Return a Home Assistant object pointing at test config directory.""" if sys.platform == "win32": loop = asyncio.ProactorEventLoop() else: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) hass = loop.run_until_complete(async_test_home_assistant(loop)) stop_event = threading.Event() def run_loop(): """Run event loop.""" # pylint: disable=protected-access loop._thread_ident = threading.get_ident() loop.run_forever() stop_event.set() orig_stop = hass.stop def start_hass(*mocks): """Start hass.""" run_coroutine_threadsafe(hass.async_start(), loop).result() def stop_hass(): """Stop hass.""" orig_stop() stop_event.wait() loop.close() hass.start = start_hass hass.stop = stop_hass threading.Thread(name="LoopThread", target=run_loop, daemon=False).start() return hass # pylint: disable=protected-access async def async_test_home_assistant(loop): """Return a Home Assistant object pointing at test config dir.""" hass = ha.HomeAssistant(loop) store = auth_store.AuthStore(hass) hass.auth = auth.AuthManager(hass, store, {}, {}) ensure_auth_manager_loaded(hass.auth) INSTANCES.append(hass) orig_async_add_job = hass.async_add_job orig_async_add_executor_job = hass.async_add_executor_job orig_async_create_task = hass.async_create_task def async_add_job(target, *args): """Add job.""" if isinstance(target, Mock): return mock_coro(target(*args)) return orig_async_add_job(target, *args) def async_add_executor_job(target, *args): """Add executor job.""" if isinstance(target, Mock): return mock_coro(target(*args)) return orig_async_add_executor_job(target, *args) def async_create_task(coroutine): """Create task.""" if isinstance(coroutine, Mock): return mock_coro() return orig_async_create_task(coroutine) hass.async_add_job = async_add_job hass.async_add_executor_job = async_add_executor_job hass.async_create_task = async_create_task hass.config.location_name = 'test home' hass.config.config_dir = get_test_config_dir() hass.config.latitude = 32.87336 hass.config.longitude = -117.22743 hass.config.elevation = 0 hass.config.time_zone = date_util.get_time_zone('US/Pacific') hass.config.units = METRIC_SYSTEM hass.config.skip_pip = True hass.config_entries = config_entries.ConfigEntries(hass, {}) hass.config_entries._entries = [] hass.config_entries._store._async_ensure_stop_listener = lambda: None hass.state = ha.CoreState.running # Mock async_start orig_start = hass.async_start async def mock_async_start(): """Start the mocking.""" # We only mock time during tests and we want to track tasks with patch('homeassistant.core._async_create_timer'), \ patch.object(hass, 'async_stop_track_tasks'): await orig_start() hass.async_start = mock_async_start @ha.callback def clear_instance(event): """Clear global instance.""" INSTANCES.remove(hass) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_CLOSE, clear_instance) return hass def get_test_instance_port(): """Return unused port for running test instance. The socket that holds the default port does not get released when we stop HA in a different test case. Until I have figured out what is going on, let's run each test on a different port. """ global _TEST_INSTANCE_PORT _TEST_INSTANCE_PORT += 1 return _TEST_INSTANCE_PORT @ha.callback def async_mock_service(hass, domain, service, schema=None): """Set up a fake service & return a calls log list to this service.""" calls = [] @ha.callback def mock_service_log(call): # pylint: disable=unnecessary-lambda """Mock service call.""" calls.append(call) hass.services.async_register( domain, service, mock_service_log, schema=schema) return calls mock_service = threadsafe_callback_factory(async_mock_service) @ha.callback def async_mock_intent(hass, intent_typ): """Set up a fake intent handler.""" intents = [] class MockIntentHandler(intent.IntentHandler): intent_type = intent_typ @asyncio.coroutine def async_handle(self, intent): """Handle the intent.""" intents.append(intent) return intent.create_response() intent.async_register(hass, MockIntentHandler()) return intents @ha.callback def async_fire_mqtt_message(hass, topic, payload, qos=0, retain=False): """Fire the MQTT message.""" if isinstance(payload, str): payload = payload.encode('utf-8') msg = mqtt.Message(topic, payload, qos, retain) hass.data['mqtt']._mqtt_handle_message(msg) fire_mqtt_message = threadsafe_callback_factory(async_fire_mqtt_message) @ha.callback def async_fire_time_changed(hass, time): """Fire a time changes event.""" hass.bus.async_fire(EVENT_TIME_CHANGED, {'now': date_util.as_utc(time)}) fire_time_changed = threadsafe_callback_factory(async_fire_time_changed) def fire_service_discovered(hass, service, info): """Fire the MQTT message.""" hass.bus.fire(EVENT_PLATFORM_DISCOVERED, { ATTR_SERVICE: service, ATTR_DISCOVERED: info }) @ha.callback def async_fire_service_discovered(hass, service, info): """Fire the MQTT message.""" hass.bus.async_fire(EVENT_PLATFORM_DISCOVERED, { ATTR_SERVICE: service, ATTR_DISCOVERED: info }) def load_fixture(filename): """Load a fixture.""" path = os.path.join(os.path.dirname(__file__), 'fixtures', filename) with open(path, encoding='utf-8') as fptr: return fptr.read() 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, } if old_state: event_data['old_state'] = old_state hass.bus.fire(EVENT_STATE_CHANGED, event_data, context=new_state.context) async def async_mock_mqtt_component(hass, config=None): """Mock the MQTT component.""" if config is None: config = {mqtt.CONF_BROKER: 'mock-broker'} with patch('paho.mqtt.client.Client') as mock_client: mock_client().connect.return_value = 0 mock_client().subscribe.return_value = (0, 0) mock_client().unsubscribe.return_value = (0, 0) mock_client().publish.return_value = (0, 0) result = await async_setup_component(hass, mqtt.DOMAIN, { mqtt.DOMAIN: config }) assert result await hass.async_block_till_done() hass.data['mqtt'] = MagicMock(spec_set=hass.data['mqtt'], wraps=hass.data['mqtt']) return hass.data['mqtt'] mock_mqtt_component = threadsafe_coroutine_factory(async_mock_mqtt_component) @ha.callback def mock_component(hass, component): """Mock a component is setup.""" if component in hass.config.components: AssertionError("Component {} is already setup".format(component)) hass.config.components.add(component) def mock_registry(hass, mock_entries=None): """Mock the Entity Registry.""" registry = entity_registry.EntityRegistry(hass) registry.entities = mock_entries or OrderedDict() hass.data[entity_registry.DATA_REGISTRY] = registry return registry def mock_area_registry(hass, mock_entries=None): """Mock the Area Registry.""" registry = area_registry.AreaRegistry(hass) registry.areas = mock_entries or OrderedDict() hass.data[area_registry.DATA_REGISTRY] = registry return registry def mock_device_registry(hass, mock_entries=None): """Mock the Device Registry.""" registry = device_registry.DeviceRegistry(hass) registry.devices = mock_entries or OrderedDict() hass.data[device_registry.DATA_REGISTRY] = registry return registry class MockGroup(auth_models.Group): """Mock a group in Home Assistant.""" def __init__(self, id=None, name='Mock Group', policy=system_policies.ADMIN_POLICY): """Mock a group.""" kwargs = { 'name': name, 'policy': policy, } if id is not None: kwargs['id'] = id super().__init__(**kwargs) def add_to_hass(self, hass): """Test helper to add entry to hass.""" return self.add_to_auth_manager(hass.auth) def add_to_auth_manager(self, auth_mgr): """Test helper to add entry to hass.""" ensure_auth_manager_loaded(auth_mgr) auth_mgr._store._groups[self.id] = self return self class MockUser(auth_models.User): """Mock a user in Home Assistant.""" def __init__(self, id=None, is_owner=False, is_active=True, name='Mock User', system_generated=False, groups=None): """Initialize mock user.""" kwargs = { 'is_owner': is_owner, 'is_active': is_active, 'name': name, 'system_generated': system_generated, 'groups': groups or [], 'perm_lookup': None, } if id is not None: kwargs['id'] = id super().__init__(**kwargs) def add_to_hass(self, hass): """Test helper to add entry to hass.""" return self.add_to_auth_manager(hass.auth) def add_to_auth_manager(self, auth_mgr): """Test helper to add entry to hass.""" ensure_auth_manager_loaded(auth_mgr) auth_mgr._store._users[self.id] = self return self def mock_policy(self, policy): """Mock a policy for a user.""" self._permissions = auth_permissions.PolicyPermissions( policy, self.perm_lookup) async def register_auth_provider(hass, config): """Register an auth provider.""" provider = await auth_providers.auth_provider_from_config( hass, hass.auth._store, config) assert provider is not None, 'Invalid config specified' key = (provider.type, provider.id) providers = hass.auth._providers if key in providers: raise ValueError('Provider already registered') providers[key] = provider return provider @ha.callback def ensure_auth_manager_loaded(auth_mgr): """Ensure an auth manager is considered loaded.""" store = auth_mgr._store if store._users is None: store._set_defaults() class MockModule: """Representation of a fake module.""" # pylint: disable=invalid-name def __init__(self, domain=None, dependencies=None, setup=None, requirements=None, config_schema=None, platform_schema=None, platform_schema_base=None, async_setup=None, async_setup_entry=None, async_unload_entry=None, async_migrate_entry=None, async_remove_entry=None, partial_manifest=None): """Initialize the mock module.""" self.__name__ = 'homeassistant.components.{}'.format(domain) self.__file__ = 'homeassistant/components/{}'.format(domain) self.DOMAIN = domain self.DEPENDENCIES = dependencies or [] self.REQUIREMENTS = requirements or [] # Overlay to be used when generating manifest from this module self._partial_manifest = partial_manifest if config_schema is not None: self.CONFIG_SCHEMA = config_schema if platform_schema is not None: self.PLATFORM_SCHEMA = platform_schema if platform_schema_base is not None: self.PLATFORM_SCHEMA_BASE = platform_schema_base if setup is not None: # We run this in executor, wrap it in function self.setup = lambda *args: setup(*args) if async_setup is not None: self.async_setup = async_setup if setup is None and async_setup is None: self.async_setup = mock_coro_func(True) if async_setup_entry is not None: self.async_setup_entry = async_setup_entry if async_unload_entry is not None: self.async_unload_entry = async_unload_entry if async_migrate_entry is not None: self.async_migrate_entry = async_migrate_entry if async_remove_entry is not None: self.async_remove_entry = async_remove_entry def mock_manifest(self): """Generate a mock manifest to represent this module.""" return { **loader.manifest_from_legacy_module(self.DOMAIN, self), **(self._partial_manifest or {}) } class MockPlatform: """Provide a fake platform.""" __name__ = 'homeassistant.components.light.bla' __file__ = 'homeassistant/components/blah/light' # pylint: disable=invalid-name def __init__(self, setup_platform=None, dependencies=None, platform_schema=None, async_setup_platform=None, async_setup_entry=None, scan_interval=None): """Initialize the platform.""" self.DEPENDENCIES = dependencies or [] if platform_schema is not None: self.PLATFORM_SCHEMA = platform_schema if scan_interval is not None: self.SCAN_INTERVAL = scan_interval if setup_platform is not None: # We run this in executor, wrap it in function self.setup_platform = lambda *args: setup_platform(*args) if async_setup_platform is not None: self.async_setup_platform = async_setup_platform if async_setup_entry is not None: self.async_setup_entry = async_setup_entry if setup_platform is None and async_setup_platform is None: self.async_setup_platform = mock_coro_func() class MockEntityPlatform(entity_platform.EntityPlatform): """Mock class with some mock defaults.""" def __init__( self, hass, logger=None, domain='test_domain', platform_name='test_platform', platform=None, scan_interval=timedelta(seconds=15), entity_namespace=None, async_entities_added_callback=lambda: None ): """Initialize a mock entity platform.""" if logger is None: logger = logging.getLogger('homeassistant.helpers.entity_platform') # Otherwise the constructor will blow up. if (isinstance(platform, Mock) and isinstance(platform.PARALLEL_UPDATES, Mock)): platform.PARALLEL_UPDATES = 0 super().__init__( hass=hass, logger=logger, domain=domain, platform_name=platform_name, platform=platform, scan_interval=scan_interval, entity_namespace=entity_namespace, async_entities_added_callback=async_entities_added_callback, ) class MockToggleDevice(entity.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 = [] @property def name(self): """Return the name of the device if any.""" self.calls.append(('name', {})) return self._name @property def state(self): """Return the name of the device if any.""" self.calls.append(('state', {})) return self._state @property def is_on(self): """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.""" self.calls.append(('turn_on', kwargs)) self._state = STATE_ON def turn_off(self, **kwargs): """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 if method is None: return self.calls[-1] try: return next(call for call in reversed(self.calls) if call[0] == method) except StopIteration: return None class MockConfigEntry(config_entries.ConfigEntry): """Helper for creating config entries that adds some defaults.""" def __init__(self, *, domain='test', data=None, version=1, entry_id=None, source=config_entries.SOURCE_USER, title='Mock Title', state=None, options={}, connection_class=config_entries.CONN_CLASS_UNKNOWN): """Initialize a mock config entry.""" kwargs = { 'entry_id': entry_id or uuid.uuid4().hex, 'domain': domain, 'data': data or {}, 'options': options, 'version': version, 'title': title, 'connection_class': connection_class, } if source is not None: kwargs['source'] = source if state is not None: kwargs['state'] = state super().__init__(**kwargs) def add_to_hass(self, hass): """Test helper to add entry to hass.""" hass.config_entries._entries.append(self) def add_to_manager(self, manager): """Test helper to add entry to entry manager.""" manager._entries.append(self) def patch_yaml_files(files_dict, endswith=True): """Patch load_yaml with a dictionary of yaml files.""" # match using endswith, start search with longest string matchlist = sorted(list(files_dict.keys()), key=len) if endswith else [] def mock_open_f(fname, **_): """Mock open() in the yaml module, used by load_yaml.""" # Return the mocked file on full match if fname in files_dict: _LOGGER.debug("patch_yaml_files match %s", fname) res = StringIO(files_dict[fname]) setattr(res, 'name', fname) return res # Match using endswith for ends in matchlist: if fname.endswith(ends): _LOGGER.debug("patch_yaml_files end match %s: %s", ends, fname) res = StringIO(files_dict[ends]) setattr(res, 'name', fname) return res # Fallback for hass.components (i.e. services.yaml) if 'homeassistant/components' in fname: _LOGGER.debug("patch_yaml_files using real file: %s", fname) return open(fname, encoding='utf-8') # Not found raise FileNotFoundError("File not found: {}".format(fname)) return patch.object(yaml_loader, 'open', mock_open_f, create=True) return patch.object(yaml_dumper, 'open', mock_open_f, create=True) def mock_coro(return_value=None, exception=None): """Return a coro that returns a value or raise an exception.""" return mock_coro_func(return_value, exception)() def mock_coro_func(return_value=None, exception=None): """Return a method to create a coro function that returns a value.""" @asyncio.coroutine def coro(*args, **kwargs): """Fake coroutine.""" if exception: raise exception return return_value return coro @contextmanager def assert_setup_component(count, domain=None): """Collect valid configuration from setup_component. - count: The amount of valid platforms that should be setup - domain: The domain to count is optional. It can be automatically determined most of the time Use as a context manager around setup.setup_component with assert_setup_component(0) as result_config: setup_component(hass, domain, start_config) # using result_config is optional """ config = {} async def mock_psc(hass, config_input, integration): """Mock the prepare_setup_component to capture config.""" domain_input = integration.domain res = await async_process_component_config( hass, config_input, integration) config[domain_input] = None if res is None else res.get(domain_input) _LOGGER.debug("Configuration for %s, Validated: %s, Original %s", domain_input, config[domain_input], config_input.get(domain_input)) return res assert isinstance(config, dict) with patch('homeassistant.config.async_process_component_config', mock_psc): yield config if domain is None: assert len(config) == 1, ('assert_setup_component requires DOMAIN: {}' .format(list(config.keys()))) domain = list(config.keys())[0] res = config.get(domain) res_len = 0 if res is None else len(res) assert res_len == count, 'setup_component failed, expected {} got {}: {}' \ .format(count, res_len, res) def init_recorder_component(hass, add_config=None): """Initialize the recorder.""" config = dict(add_config) if add_config else {} config[recorder.CONF_DB_URL] = 'sqlite://' # In memory DB with patch('homeassistant.components.recorder.migration.migrate_schema'): assert setup_component(hass, recorder.DOMAIN, {recorder.DOMAIN: config}) assert recorder.DOMAIN in hass.config.components _LOGGER.info("In-memory recorder successfully started") def mock_restore_cache(hass, states): """Mock the DATA_RESTORE_CACHE.""" key = restore_state.DATA_RESTORE_STATE_TASK data = restore_state.RestoreStateData(hass) now = date_util.utcnow() data.last_states = { state.entity_id: restore_state.StoredState(state, now) for state in states} _LOGGER.debug('Restore cache: %s', data.last_states) assert len(data.last_states) == len(states), \ "Duplicate entity_id? {}".format(states) async def get_restore_state_data() -> restore_state.RestoreStateData: return data # Patch the singleton task in hass.data to return our new RestoreStateData hass.data[key] = hass.async_create_task(get_restore_state_data()) class MockDependency: """Decorator to mock install a dependency.""" def __init__(self, root, *args): """Initialize decorator.""" self.root = root self.submodules = args def __enter__(self): """Start mocking.""" def resolve(mock, path): """Resolve a mock.""" if not path: return mock return resolve(getattr(mock, path[0]), path[1:]) base = MagicMock() to_mock = { "{}.{}".format(self.root, tom): resolve(base, tom.split('.')) for tom in self.submodules } to_mock[self.root] = base self.patcher = patch.dict('sys.modules', to_mock) self.patcher.start() return base def __exit__(self, *exc): """Stop mocking.""" self.patcher.stop() return False def __call__(self, func): """Apply decorator.""" def run_mocked(*args, **kwargs): """Run with mocked dependencies.""" with self as base: args = list(args) + [base] func(*args, **kwargs) return run_mocked class MockEntity(entity.Entity): """Mock Entity class.""" def __init__(self, **values): """Initialize an entity.""" self._values = values if 'entity_id' in values: self.entity_id = values['entity_id'] @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') @property def available(self): """Return True if entity is available.""" return self._handle('available') @property def device_info(self): """Info how it links to a device.""" return self._handle('device_info') def _handle(self, attr): """Return attribute value.""" if attr in self._values: return self._values[attr] return getattr(super(), attr) @contextmanager def mock_storage(data=None): """Mock storage. Data is a dict {'key': {'version': version, 'data': data}} Written data will be converted to JSON to ensure JSON parsing works. """ if data is None: data = {} orig_load = storage.Store._async_load async def mock_async_load(store): """Mock version of load.""" if store._data is None: # No data to load if store.key not in data: return None mock_data = data.get(store.key) if 'data' not in mock_data or 'version' not in mock_data: _LOGGER.error('Mock data needs "version" and "data"') raise ValueError('Mock data needs "version" and "data"') store._data = mock_data # Route through original load so that we trigger migration loaded = await orig_load(store) _LOGGER.info('Loading data for %s: %s', store.key, loaded) return loaded def mock_write_data(store, path, data_to_write): """Mock version of write data.""" _LOGGER.info('Writing data to %s: %s', store.key, data_to_write) # To ensure that the data can be serialized data[store.key] = json.loads(json.dumps( data_to_write, cls=store._encoder)) with patch('homeassistant.helpers.storage.Store._async_load', side_effect=mock_async_load, autospec=True), \ patch('homeassistant.helpers.storage.Store._write_data', side_effect=mock_write_data, autospec=True): yield data async def flush_store(store): """Make sure all delayed writes of a store are written.""" if store._data is None: return await store._async_handle_write_data() async def get_system_health_info(hass, domain): """Get system health info.""" return await hass.data['system_health']['info'][domain](hass) def mock_integration(hass, module): """Mock an integration.""" integration = loader.Integration( hass, 'homeassistant.components.{}'.format(module.DOMAIN), None, module.mock_manifest()) _LOGGER.info("Adding mock integration: %s", module.DOMAIN) hass.data.setdefault( loader.DATA_INTEGRATIONS, {} )[module.DOMAIN] = integration hass.data.setdefault(loader.DATA_COMPONENTS, {})[module.DOMAIN] = module def mock_entity_platform(hass, platform_path, module): """Mock a entity platform. platform_path is in form light.hue. Will create platform hue.light. """ domain, platform_name = platform_path.split('.') integration_cache = hass.data.setdefault(loader.DATA_COMPONENTS, {}) module_cache = hass.data.setdefault(loader.DATA_COMPONENTS, {}) if platform_name not in integration_cache: mock_integration(hass, MockModule(platform_name)) _LOGGER.info("Adding mock integration platform: %s", platform_path) module_cache["{}.{}".format(platform_name, domain)] = module def async_capture_events(hass, event_name): """Create a helper that captures events.""" events = [] @ha.callback def capture_events(event): events.append(event) hass.bus.async_listen(event_name, capture_events) return events
"""Test Hue bridge.""" from unittest.mock import Mock, patch import pytest from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.components.hue import bridge, errors from tests.common import mock_coro async def test_bridge_setup(): """Test a successful setup.""" hass = Mock() entry = Mock() api = Mock() entry.data = {'host': '1.2.3.4', 'username': 'mock-username'} hue_bridge = bridge.HueBridge(hass, entry, False, False) with patch.object(bridge, 'get_bridge', return_value=mock_coro(api)): assert await hue_bridge.async_setup() is True assert hue_bridge.api is api forward_entries = set( c[1][1] for c in hass.config_entries.async_forward_entry_setup.mock_calls ) assert len(hass.config_entries.async_forward_entry_setup.mock_calls) == 3 assert forward_entries == set(['light', 'binary_sensor', 'sensor']) async def test_bridge_setup_invalid_username(): """Test we start config flow if username is no longer whitelisted.""" hass = Mock() entry = Mock() entry.data = {'host': '1.2.3.4', 'username': 'mock-username'} hue_bridge = bridge.HueBridge(hass, entry, False, False) with patch.object(bridge, 'get_bridge', side_effect=errors.AuthenticationRequired): assert await hue_bridge.async_setup() is False assert len(hass.async_create_task.mock_calls) == 1 assert len(hass.config_entries.flow.async_init.mock_calls) == 1 assert hass.config_entries.flow.async_init.mock_calls[0][2]['data'] == { 'host': '1.2.3.4' } async def test_bridge_setup_timeout(hass): """Test we retry to connect if we cannot connect.""" hass = Mock() entry = Mock() entry.data = {'host': '1.2.3.4', 'username': 'mock-username'} hue_bridge = bridge.HueBridge(hass, entry, False, False) with patch.object( bridge, 'get_bridge', side_effect=errors.CannotConnect ), pytest.raises(ConfigEntryNotReady): await hue_bridge.async_setup() async def test_reset_if_entry_had_wrong_auth(): """Test calling reset when the entry contained wrong auth.""" hass = Mock() entry = Mock() entry.data = {'host': '1.2.3.4', 'username': 'mock-username'} hue_bridge = bridge.HueBridge(hass, entry, False, False) with patch.object(bridge, 'get_bridge', side_effect=errors.AuthenticationRequired): assert await hue_bridge.async_setup() is False assert len(hass.async_create_task.mock_calls) == 1 assert await hue_bridge.async_reset() async def test_reset_unloads_entry_if_setup(): """Test calling reset while the entry has been setup.""" hass = Mock() entry = Mock() entry.data = {'host': '1.2.3.4', 'username': 'mock-username'} hue_bridge = bridge.HueBridge(hass, entry, False, False) with patch.object(bridge, 'get_bridge', return_value=mock_coro(Mock())): assert await hue_bridge.async_setup() is True assert len(hass.services.async_register.mock_calls) == 1 assert len(hass.config_entries.async_forward_entry_setup.mock_calls) == 3 hass.config_entries.async_forward_entry_unload.return_value = \ mock_coro(True) assert await hue_bridge.async_reset() assert len(hass.config_entries.async_forward_entry_unload.mock_calls) == 3 assert len(hass.services.async_remove.mock_calls) == 1
aequitas/home-assistant
tests/components/hue/test_bridge.py
tests/common.py
import argparse import os from logging import debug from teuthology import misc from teuthology.orchestra import cluster from teuthology.orchestra.run import quote from teuthology.orchestra.daemon.group import DaemonGroup import subprocess class FakeRemote(object): pass def test_pid(): ctx = argparse.Namespace() ctx.daemons = DaemonGroup(use_systemd=True) remote = FakeRemote() ps_ef_output_path = os.path.join( os.path.dirname(__file__), "files/daemon-systemdstate-pid-ps-ef.output" ) # patching ps -ef command output using a file def sh(args): args[0:2] = ["cat", ps_ef_output_path] debug(args) return subprocess.getoutput(quote(args)) remote.sh = sh remote.init_system = 'systemd' remote.shortname = 'host1' ctx.cluster = cluster.Cluster( remotes=[ (remote, ['rgw.0', 'mon.a', 'mgr.a', 'mds.a', 'osd.0']) ], ) for remote, roles in ctx.cluster.remotes.items(): for role in roles: _, rol, id_ = misc.split_role(role) if any(rol.startswith(x) for x in ['mon', 'mgr', 'mds']): ctx.daemons.register_daemon(remote, rol, remote.shortname) else: ctx.daemons.register_daemon(remote, rol, id_) for _, daemons in ctx.daemons.daemons.items(): for daemon in daemons.values(): pid = daemon.pid debug(pid) assert pid
import pytest import docopt from unittest.mock import patch, call, Mock from teuthology import run from scripts import run as scripts_run class TestRun(object): """ Tests for teuthology.run """ @patch("teuthology.log.setLevel") @patch("teuthology.setup_log_file") @patch("os.mkdir") def test_set_up_logging(self, m_mkdir, m_setup_log_file, m_setLevel): run.set_up_logging(True, "path/to/archive") m_mkdir.assert_called_with("path/to/archive") m_setup_log_file.assert_called_with("path/to/archive/teuthology.log") assert m_setLevel.called # because of how we import things, mock merge_configs from run - where it's used # see: http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch @patch("teuthology.run.merge_configs") def test_setup_config(self, m_merge_configs): config = {"job_id": 1, "foo": "bar"} m_merge_configs.return_value = config result = run.setup_config(["some/config.yaml"]) assert m_merge_configs.called assert result["job_id"] == "1" assert result["foo"] == "bar" @patch("teuthology.run.merge_configs") def test_setup_config_targets_ok(self, m_merge_configs): config = {"targets": list(range(4)), "roles": list(range(2))} m_merge_configs.return_value = config result = run.setup_config(["some/config.yaml"]) assert result["targets"] == [0, 1, 2, 3] assert result["roles"] == [0, 1] @patch("teuthology.run.merge_configs") def test_setup_config_targets_invalid(self, m_merge_configs): config = {"targets": range(2), "roles": range(4)} m_merge_configs.return_value = config with pytest.raises(AssertionError): run.setup_config(["some/config.yaml"]) @patch("teuthology.run.open") def test_write_initial_metadata(self, m_open): config = {"job_id": "123", "foo": "bar"} run.write_initial_metadata( "some/archive/dir", config, "the_name", "the_description", "the_owner", ) expected = [ call('some/archive/dir/pid', 'w'), call('some/archive/dir/owner', 'w'), call('some/archive/dir/orig.config.yaml', 'w'), call('some/archive/dir/info.yaml', 'w') ] assert m_open.call_args_list == expected def test_get_machine_type(self): result = run.get_machine_type(None, {"machine-type": "the_machine_type"}) assert result == "the_machine_type" def test_get_summary(self): result = run.get_summary("the_owner", "the_description") assert result == {"owner": "the_owner", "description": "the_description", "success": True} result = run.get_summary("the_owner", None) assert result == {"owner": "the_owner", "success": True} def test_validate_tasks_invalid(self): config = {"tasks": [{"kernel": "can't be here"}]} with pytest.raises(AssertionError) as excinfo: run.validate_tasks(config) assert excinfo.value.args[0].startswith("kernel installation") def test_validate_task_no_tasks(self): result = run.validate_tasks({}) assert result == [] def test_validate_tasks_valid(self): expected = [{"foo": "bar"}, {"bar": "foo"}] result = run.validate_tasks({"tasks": expected}) assert result == expected def test_validate_tasks_is_list(self): with pytest.raises(AssertionError) as excinfo: run.validate_tasks({"tasks": {"foo": "bar"}}) assert excinfo.value.args[0].startswith("Expected list") def test_get_initial_tasks_invalid(self): with pytest.raises(AssertionError) as excinfo: run.get_initial_tasks(True, {"targets": "can't be here", "roles": "roles" }, "machine_type") assert excinfo.value.args[0].startswith("You cannot") def test_get_inital_tasks(self): config = {"roles": range(2), "kernel": "the_kernel", "use_existing_cluster": False} result = run.get_initial_tasks(True, config, "machine_type") assert {"internal.lock_machines": (2, "machine_type")} in result assert {"kernel": "the_kernel"} in result # added because use_existing_cluster == False assert {'internal.vm_setup': None} in result assert {'internal.buildpackages_prep': None} in result @patch("teuthology.run.fetch_qa_suite") def test_fetch_tasks_if_needed(self, m_fetch_qa_suite): config = {"suite_path": "/some/suite/path", "suite_branch": "feature_branch", "suite_sha1": "commit"} m_fetch_qa_suite.return_value = "/some/other/suite/path" result = run.fetch_tasks_if_needed(config) m_fetch_qa_suite.assert_called_with("feature_branch", commit="commit") assert result == "/some/other/suite/path" @patch("teuthology.run.get_status") @patch("teuthology.run.nuke") @patch("yaml.safe_dump") @patch("teuthology.report.try_push_job_info") @patch("teuthology.run.email_results") @patch("teuthology.run.open") @patch("sys.exit") def test_report_outcome(self, m_sys_exit, m_open, m_email_results, m_try_push_job_info, m_safe_dump, m_nuke, m_get_status): m_get_status.return_value = "fail" fake_ctx = Mock() summary = {"failure_reason": "reasons"} summary_dump = "failure_reason: reasons\n" config = {"nuke-on-error": True, "email-on-error": True} config_dump = "nuke-on-error: true\nemail-on-error: true\n" m_safe_dump.side_effect = [None, summary_dump, config_dump] run.report_outcome(config, "the/archive/path", summary, fake_ctx) assert m_nuke.called m_try_push_job_info.assert_called_with(config, summary) m_open.assert_called_with("the/archive/path/summary.yaml", "w") assert m_email_results.called assert m_open.called assert m_sys_exit.called @patch("teuthology.run.set_up_logging") @patch("teuthology.run.setup_config") @patch("teuthology.run.get_user") @patch("teuthology.run.write_initial_metadata") @patch("teuthology.report.try_push_job_info") @patch("teuthology.run.get_machine_type") @patch("teuthology.run.get_summary") @patch("yaml.safe_dump") @patch("teuthology.run.validate_tasks") @patch("teuthology.run.get_initial_tasks") @patch("teuthology.run.fetch_tasks_if_needed") @patch("teuthology.run.run_tasks") @patch("teuthology.run.report_outcome") def test_main(self, m_report_outcome, m_run_tasks, m_fetch_tasks_if_needed, m_get_initial_tasks, m_validate_tasks, m_safe_dump, m_get_summary, m_get_machine_type, m_try_push_job_info, m_write_initial_metadata, m_get_user, m_setup_config, m_set_up_logging): """ This really should be an integration test of some sort. """ config = {"job_id": 1} m_setup_config.return_value = config m_get_machine_type.return_value = "machine_type" doc = scripts_run.__doc__ args = docopt.docopt(doc, [ "--verbose", "--archive", "some/archive/dir", "--description", "the_description", "--lock", "--os-type", "os_type", "--os-version", "os_version", "--block", "--name", "the_name", "--suite-path", "some/suite/dir", "path/to/config.yml", ]) m_get_user.return_value = "the_owner" m_get_summary.return_value = dict(success=True, owner="the_owner", description="the_description") m_validate_tasks.return_value = ['task3'] m_get_initial_tasks.return_value = ['task1', 'task2'] m_fetch_tasks_if_needed.return_value = "some/suite/dir" run.main(args) m_set_up_logging.assert_called_with(True, "some/archive/dir") m_setup_config.assert_called_with(["path/to/config.yml"]) m_write_initial_metadata.assert_called_with( "some/archive/dir", config, "the_name", "the_description", "the_owner" ) m_try_push_job_info.assert_called_with(config, dict(status='running')) m_get_machine_type.assert_called_with(None, config) m_get_summary.assert_called_with("the_owner", "the_description") m_get_initial_tasks.assert_called_with(True, config, "machine_type") m_fetch_tasks_if_needed.assert_called_with(config) assert m_report_outcome.called args, kwargs = m_run_tasks.call_args fake_ctx = kwargs["ctx"]._conf # fields that must be in ctx for the tasks to behave expected_ctx = ["verbose", "archive", "description", "owner", "lock", "machine_type", "os_type", "os_version", "block", "name", "suite_path", "config", "summary"] for key in expected_ctx: assert key in fake_ctx assert isinstance(fake_ctx["config"], dict) assert isinstance(fake_ctx["summary"], dict) assert "tasks" in fake_ctx["config"] # ensures that values missing in args are added with the correct value assert fake_ctx["owner"] == "the_owner" assert fake_ctx["machine_type"] == "machine_type" # ensures os_type and os_version are property overwritten assert fake_ctx["config"]["os_type"] == "os_type" assert fake_ctx["config"]["os_version"] == "os_version" def test_get_teuthology_command(self): doc = scripts_run.__doc__ args = docopt.docopt(doc, [ "--archive", "some/archive/dir", "--description", "the_description", "--lock", "--block", "--name", "the_name", "--suite-path", "some/suite/dir", "path/to/config.yml", "path/to/config2.yaml", ]) result = run.get_teuthology_command(args) result = result.split() expected = [ "teuthology", "path/to/config.yml", "path/to/config2.yaml", "--suite-path", "some/suite/dir", "--lock", "--description", "the_description", "--name", "the_name", "--block", "--archive", "some/archive/dir", ] assert len(result) == len(expected) for arg in expected: assert arg in result
SUSE/teuthology
teuthology/test/test_run.py
teuthology/orchestra/test/test_systemd.py
""" Print task A task that logs whatever is given to it as an argument. Can be used like any other task (under sequential, etc...).j For example, the following would cause the strings "String" and "Another string" to appear in the teuthology.log before and after the chef task runs, respectively. tasks: - print: "String" - chef: null - print: "Another String" """ import logging log = logging.getLogger(__name__) def task(ctx, config): """ Print out config argument in teuthology log/output """ log.info('{config}'.format(config=config))
import pytest import docopt from unittest.mock import patch, call, Mock from teuthology import run from scripts import run as scripts_run class TestRun(object): """ Tests for teuthology.run """ @patch("teuthology.log.setLevel") @patch("teuthology.setup_log_file") @patch("os.mkdir") def test_set_up_logging(self, m_mkdir, m_setup_log_file, m_setLevel): run.set_up_logging(True, "path/to/archive") m_mkdir.assert_called_with("path/to/archive") m_setup_log_file.assert_called_with("path/to/archive/teuthology.log") assert m_setLevel.called # because of how we import things, mock merge_configs from run - where it's used # see: http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch @patch("teuthology.run.merge_configs") def test_setup_config(self, m_merge_configs): config = {"job_id": 1, "foo": "bar"} m_merge_configs.return_value = config result = run.setup_config(["some/config.yaml"]) assert m_merge_configs.called assert result["job_id"] == "1" assert result["foo"] == "bar" @patch("teuthology.run.merge_configs") def test_setup_config_targets_ok(self, m_merge_configs): config = {"targets": list(range(4)), "roles": list(range(2))} m_merge_configs.return_value = config result = run.setup_config(["some/config.yaml"]) assert result["targets"] == [0, 1, 2, 3] assert result["roles"] == [0, 1] @patch("teuthology.run.merge_configs") def test_setup_config_targets_invalid(self, m_merge_configs): config = {"targets": range(2), "roles": range(4)} m_merge_configs.return_value = config with pytest.raises(AssertionError): run.setup_config(["some/config.yaml"]) @patch("teuthology.run.open") def test_write_initial_metadata(self, m_open): config = {"job_id": "123", "foo": "bar"} run.write_initial_metadata( "some/archive/dir", config, "the_name", "the_description", "the_owner", ) expected = [ call('some/archive/dir/pid', 'w'), call('some/archive/dir/owner', 'w'), call('some/archive/dir/orig.config.yaml', 'w'), call('some/archive/dir/info.yaml', 'w') ] assert m_open.call_args_list == expected def test_get_machine_type(self): result = run.get_machine_type(None, {"machine-type": "the_machine_type"}) assert result == "the_machine_type" def test_get_summary(self): result = run.get_summary("the_owner", "the_description") assert result == {"owner": "the_owner", "description": "the_description", "success": True} result = run.get_summary("the_owner", None) assert result == {"owner": "the_owner", "success": True} def test_validate_tasks_invalid(self): config = {"tasks": [{"kernel": "can't be here"}]} with pytest.raises(AssertionError) as excinfo: run.validate_tasks(config) assert excinfo.value.args[0].startswith("kernel installation") def test_validate_task_no_tasks(self): result = run.validate_tasks({}) assert result == [] def test_validate_tasks_valid(self): expected = [{"foo": "bar"}, {"bar": "foo"}] result = run.validate_tasks({"tasks": expected}) assert result == expected def test_validate_tasks_is_list(self): with pytest.raises(AssertionError) as excinfo: run.validate_tasks({"tasks": {"foo": "bar"}}) assert excinfo.value.args[0].startswith("Expected list") def test_get_initial_tasks_invalid(self): with pytest.raises(AssertionError) as excinfo: run.get_initial_tasks(True, {"targets": "can't be here", "roles": "roles" }, "machine_type") assert excinfo.value.args[0].startswith("You cannot") def test_get_inital_tasks(self): config = {"roles": range(2), "kernel": "the_kernel", "use_existing_cluster": False} result = run.get_initial_tasks(True, config, "machine_type") assert {"internal.lock_machines": (2, "machine_type")} in result assert {"kernel": "the_kernel"} in result # added because use_existing_cluster == False assert {'internal.vm_setup': None} in result assert {'internal.buildpackages_prep': None} in result @patch("teuthology.run.fetch_qa_suite") def test_fetch_tasks_if_needed(self, m_fetch_qa_suite): config = {"suite_path": "/some/suite/path", "suite_branch": "feature_branch", "suite_sha1": "commit"} m_fetch_qa_suite.return_value = "/some/other/suite/path" result = run.fetch_tasks_if_needed(config) m_fetch_qa_suite.assert_called_with("feature_branch", commit="commit") assert result == "/some/other/suite/path" @patch("teuthology.run.get_status") @patch("teuthology.run.nuke") @patch("yaml.safe_dump") @patch("teuthology.report.try_push_job_info") @patch("teuthology.run.email_results") @patch("teuthology.run.open") @patch("sys.exit") def test_report_outcome(self, m_sys_exit, m_open, m_email_results, m_try_push_job_info, m_safe_dump, m_nuke, m_get_status): m_get_status.return_value = "fail" fake_ctx = Mock() summary = {"failure_reason": "reasons"} summary_dump = "failure_reason: reasons\n" config = {"nuke-on-error": True, "email-on-error": True} config_dump = "nuke-on-error: true\nemail-on-error: true\n" m_safe_dump.side_effect = [None, summary_dump, config_dump] run.report_outcome(config, "the/archive/path", summary, fake_ctx) assert m_nuke.called m_try_push_job_info.assert_called_with(config, summary) m_open.assert_called_with("the/archive/path/summary.yaml", "w") assert m_email_results.called assert m_open.called assert m_sys_exit.called @patch("teuthology.run.set_up_logging") @patch("teuthology.run.setup_config") @patch("teuthology.run.get_user") @patch("teuthology.run.write_initial_metadata") @patch("teuthology.report.try_push_job_info") @patch("teuthology.run.get_machine_type") @patch("teuthology.run.get_summary") @patch("yaml.safe_dump") @patch("teuthology.run.validate_tasks") @patch("teuthology.run.get_initial_tasks") @patch("teuthology.run.fetch_tasks_if_needed") @patch("teuthology.run.run_tasks") @patch("teuthology.run.report_outcome") def test_main(self, m_report_outcome, m_run_tasks, m_fetch_tasks_if_needed, m_get_initial_tasks, m_validate_tasks, m_safe_dump, m_get_summary, m_get_machine_type, m_try_push_job_info, m_write_initial_metadata, m_get_user, m_setup_config, m_set_up_logging): """ This really should be an integration test of some sort. """ config = {"job_id": 1} m_setup_config.return_value = config m_get_machine_type.return_value = "machine_type" doc = scripts_run.__doc__ args = docopt.docopt(doc, [ "--verbose", "--archive", "some/archive/dir", "--description", "the_description", "--lock", "--os-type", "os_type", "--os-version", "os_version", "--block", "--name", "the_name", "--suite-path", "some/suite/dir", "path/to/config.yml", ]) m_get_user.return_value = "the_owner" m_get_summary.return_value = dict(success=True, owner="the_owner", description="the_description") m_validate_tasks.return_value = ['task3'] m_get_initial_tasks.return_value = ['task1', 'task2'] m_fetch_tasks_if_needed.return_value = "some/suite/dir" run.main(args) m_set_up_logging.assert_called_with(True, "some/archive/dir") m_setup_config.assert_called_with(["path/to/config.yml"]) m_write_initial_metadata.assert_called_with( "some/archive/dir", config, "the_name", "the_description", "the_owner" ) m_try_push_job_info.assert_called_with(config, dict(status='running')) m_get_machine_type.assert_called_with(None, config) m_get_summary.assert_called_with("the_owner", "the_description") m_get_initial_tasks.assert_called_with(True, config, "machine_type") m_fetch_tasks_if_needed.assert_called_with(config) assert m_report_outcome.called args, kwargs = m_run_tasks.call_args fake_ctx = kwargs["ctx"]._conf # fields that must be in ctx for the tasks to behave expected_ctx = ["verbose", "archive", "description", "owner", "lock", "machine_type", "os_type", "os_version", "block", "name", "suite_path", "config", "summary"] for key in expected_ctx: assert key in fake_ctx assert isinstance(fake_ctx["config"], dict) assert isinstance(fake_ctx["summary"], dict) assert "tasks" in fake_ctx["config"] # ensures that values missing in args are added with the correct value assert fake_ctx["owner"] == "the_owner" assert fake_ctx["machine_type"] == "machine_type" # ensures os_type and os_version are property overwritten assert fake_ctx["config"]["os_type"] == "os_type" assert fake_ctx["config"]["os_version"] == "os_version" def test_get_teuthology_command(self): doc = scripts_run.__doc__ args = docopt.docopt(doc, [ "--archive", "some/archive/dir", "--description", "the_description", "--lock", "--block", "--name", "the_name", "--suite-path", "some/suite/dir", "path/to/config.yml", "path/to/config2.yaml", ]) result = run.get_teuthology_command(args) result = result.split() expected = [ "teuthology", "path/to/config.yml", "path/to/config2.yaml", "--suite-path", "some/suite/dir", "--lock", "--description", "the_description", "--name", "the_name", "--block", "--archive", "some/archive/dir", ] assert len(result) == len(expected) for arg in expected: assert arg in result
SUSE/teuthology
teuthology/test/test_run.py
teuthology/task/print.py
"""Helper methods to handle the time in Home Assistant.""" import datetime as dt import re from typing import Any, Dict, List, Optional, Union, cast import ciso8601 import pytz import pytz.exceptions as pytzexceptions import pytz.tzinfo as pytzinfo from homeassistant.const import MATCH_ALL DATE_STR_FORMAT = "%Y-%m-%d" NATIVE_UTC = dt.timezone.utc UTC = pytz.utc DEFAULT_TIME_ZONE: dt.tzinfo = pytz.utc # Copyright (c) Django Software Foundation and individual contributors. # All rights reserved. # https://github.com/django/django/blob/master/LICENSE DATETIME_RE = re.compile( r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})" r"[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})" r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?" r"(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$" ) def set_default_time_zone(time_zone: dt.tzinfo) -> None: """Set a default time zone to be used when none is specified. Async friendly. """ global DEFAULT_TIME_ZONE # pylint: disable=global-statement # NOTE: Remove in the future in favour of typing assert isinstance(time_zone, dt.tzinfo) DEFAULT_TIME_ZONE = time_zone def get_time_zone(time_zone_str: str) -> Optional[dt.tzinfo]: """Get time zone from string. Return None if unable to determine. Async friendly. """ try: return pytz.timezone(time_zone_str) except pytzexceptions.UnknownTimeZoneError: return None def utcnow() -> dt.datetime: """Get now in UTC time.""" return dt.datetime.now(NATIVE_UTC) def now(time_zone: Optional[dt.tzinfo] = None) -> dt.datetime: """Get now in specified time zone.""" return dt.datetime.now(time_zone or DEFAULT_TIME_ZONE) def as_utc(dattim: dt.datetime) -> dt.datetime: """Return a datetime as UTC time. Assumes datetime without tzinfo to be in the DEFAULT_TIME_ZONE. """ if dattim.tzinfo == UTC: return dattim if dattim.tzinfo is None: dattim = DEFAULT_TIME_ZONE.localize(dattim) # type: ignore return dattim.astimezone(UTC) def as_timestamp(dt_value: dt.datetime) -> float: """Convert a date/time into a unix time (seconds since 1970).""" if hasattr(dt_value, "timestamp"): parsed_dt: Optional[dt.datetime] = dt_value else: parsed_dt = parse_datetime(str(dt_value)) if parsed_dt is None: raise ValueError("not a valid date/time.") return parsed_dt.timestamp() def as_local(dattim: dt.datetime) -> dt.datetime: """Convert a UTC datetime object to local time zone.""" if dattim.tzinfo == DEFAULT_TIME_ZONE: return dattim if dattim.tzinfo is None: dattim = UTC.localize(dattim) return dattim.astimezone(DEFAULT_TIME_ZONE) def utc_from_timestamp(timestamp: float) -> dt.datetime: """Return a UTC time from a timestamp.""" return UTC.localize(dt.datetime.utcfromtimestamp(timestamp)) def start_of_local_day( dt_or_d: Union[dt.date, dt.datetime, None] = None ) -> dt.datetime: """Return local datetime object of start of day from date or datetime.""" if dt_or_d is None: date: dt.date = now().date() elif isinstance(dt_or_d, dt.datetime): date = dt_or_d.date() else: date = dt_or_d return DEFAULT_TIME_ZONE.localize( # type: ignore dt.datetime.combine(date, dt.time()) ) # Copyright (c) Django Software Foundation and individual contributors. # All rights reserved. # https://github.com/django/django/blob/master/LICENSE def parse_datetime(dt_str: str) -> Optional[dt.datetime]: """Parse a string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raises ValueError if the input is well formatted but not a valid datetime. Returns None if the input isn't well formatted. """ try: return ciso8601.parse_datetime(dt_str) except (ValueError, IndexError): pass match = DATETIME_RE.match(dt_str) if not match: return None kws: Dict[str, Any] = match.groupdict() if kws["microsecond"]: kws["microsecond"] = kws["microsecond"].ljust(6, "0") tzinfo_str = kws.pop("tzinfo") tzinfo: Optional[dt.tzinfo] = None if tzinfo_str == "Z": tzinfo = UTC elif tzinfo_str is not None: offset_mins = int(tzinfo_str[-2:]) if len(tzinfo_str) > 3 else 0 offset_hours = int(tzinfo_str[1:3]) offset = dt.timedelta(hours=offset_hours, minutes=offset_mins) if tzinfo_str[0] == "-": offset = -offset tzinfo = dt.timezone(offset) kws = {k: int(v) for k, v in kws.items() if v is not None} kws["tzinfo"] = tzinfo return dt.datetime(**kws) def parse_date(dt_str: str) -> Optional[dt.date]: """Convert a date string to a date object.""" try: return dt.datetime.strptime(dt_str, DATE_STR_FORMAT).date() except ValueError: # If dt_str did not match our format return None def parse_time(time_str: str) -> Optional[dt.time]: """Parse a time string (00:20:00) into Time object. Return None if invalid. """ parts = str(time_str).split(":") if len(parts) < 2: return None try: hour = int(parts[0]) minute = int(parts[1]) second = int(parts[2]) if len(parts) > 2 else 0 return dt.time(hour, minute, second) except ValueError: # ValueError if value cannot be converted to an int or not in range return None def get_age(date: dt.datetime) -> str: """ Take a datetime and return its "age" as a string. The age can be in second, minute, hour, day, month or year. Only the biggest unit is considered, e.g. if it's 2 days and 3 hours, "2 days" will be returned. Make sure date is not in the future, or else it won't work. """ def formatn(number: int, unit: str) -> str: """Add "unit" if it's plural.""" if number == 1: return f"1 {unit}" return f"{number:d} {unit}s" delta = (now() - date).total_seconds() rounded_delta = round(delta) units = ["second", "minute", "hour", "day", "month"] factors = [60, 60, 24, 30, 12] selected_unit = "year" for i, next_factor in enumerate(factors): if rounded_delta < next_factor: selected_unit = units[i] break delta /= next_factor rounded_delta = round(delta) return formatn(rounded_delta, selected_unit) def parse_time_expression(parameter: Any, min_value: int, max_value: int) -> List[int]: """Parse the time expression part and return a list of times to match.""" if parameter is None or parameter == MATCH_ALL: res = list(range(min_value, max_value + 1)) elif isinstance(parameter, str): if parameter.startswith("/"): parameter = int(parameter[1:]) res = [x for x in range(min_value, max_value + 1) if x % parameter == 0] else: res = [int(parameter)] elif not hasattr(parameter, "__iter__"): res = [int(parameter)] else: res = list(sorted(int(x) for x in parameter)) for val in res: if val < min_value or val > max_value: raise ValueError( f"Time expression '{parameter}': parameter {val} out of range " f"({min_value} to {max_value})" ) return res def find_next_time_expression_time( now: dt.datetime, # pylint: disable=redefined-outer-name seconds: List[int], minutes: List[int], hours: List[int], ) -> dt.datetime: """Find the next datetime from now for which the time expression matches. The algorithm looks at each time unit separately and tries to find the next one that matches for each. If any of them would roll over, all time units below that are reset to the first matching value. Timezones are also handled (the tzinfo of the now object is used), including daylight saving time. """ if not seconds or not minutes or not hours: raise ValueError("Cannot find a next time: Time expression never matches!") def _lower_bound(arr: List[int], cmp: int) -> Optional[int]: """Return the first value in arr greater or equal to cmp. Return None if no such value exists. """ left = 0 right = len(arr) while left < right: mid = (left + right) // 2 if arr[mid] < cmp: left = mid + 1 else: right = mid if left == len(arr): return None return arr[left] result = now.replace(microsecond=0) # Match next second next_second = _lower_bound(seconds, result.second) if next_second is None: # No second to match in this minute. Roll-over to next minute. next_second = seconds[0] result += dt.timedelta(minutes=1) result = result.replace(second=next_second) # Match next minute next_minute = _lower_bound(minutes, result.minute) if next_minute != result.minute: # We're in the next minute. Seconds needs to be reset. result = result.replace(second=seconds[0]) if next_minute is None: # No minute to match in this hour. Roll-over to next hour. next_minute = minutes[0] result += dt.timedelta(hours=1) result = result.replace(minute=next_minute) # Match next hour next_hour = _lower_bound(hours, result.hour) if next_hour != result.hour: # We're in the next hour. Seconds+minutes needs to be reset. result = result.replace(second=seconds[0], minute=minutes[0]) if next_hour is None: # No minute to match in this day. Roll-over to next day. next_hour = hours[0] result += dt.timedelta(days=1) result = result.replace(hour=next_hour) if result.tzinfo is None: return result # Now we need to handle timezones. We will make this datetime object # "naive" first and then re-convert it to the target timezone. # This is so that we can call pytz's localize and handle DST changes. tzinfo: pytzinfo.DstTzInfo = UTC if result.tzinfo == NATIVE_UTC else result.tzinfo result = result.replace(tzinfo=None) try: result = tzinfo.localize(result, is_dst=None) except pytzexceptions.AmbiguousTimeError: # This happens when we're leaving daylight saving time and local # clocks are rolled back. In this case, we want to trigger # on both the DST and non-DST time. So when "now" is in the DST # use the DST-on time, and if not, use the DST-off time. use_dst = bool(now.dst()) result = tzinfo.localize(result, is_dst=use_dst) except pytzexceptions.NonExistentTimeError: # This happens when we're entering daylight saving time and local # clocks are rolled forward, thus there are local times that do # not exist. In this case, we want to trigger on the next time # that *does* exist. # In the worst case, this will run through all the seconds in the # time shift, but that's max 3600 operations for once per year result = result.replace(tzinfo=tzinfo) + dt.timedelta(seconds=1) return find_next_time_expression_time(result, seconds, minutes, hours) result_dst = cast(dt.timedelta, result.dst()) now_dst = cast(dt.timedelta, now.dst()) or dt.timedelta(0) if result_dst >= now_dst: return result # Another edge-case when leaving DST: # When now is in DST and ambiguous *and* the next trigger time we *should* # trigger is ambiguous and outside DST, the excepts above won't catch it. # For example: if triggering on 2:30 and now is 28.10.2018 2:30 (in DST) # we should trigger next on 28.10.2018 2:30 (out of DST), but our # algorithm above would produce 29.10.2018 2:30 (out of DST) # Step 1: Check if now is ambiguous try: tzinfo.localize(now.replace(tzinfo=None), is_dst=None) return result except pytzexceptions.AmbiguousTimeError: pass # Step 2: Check if result of (now - DST) is ambiguous. check = now - now_dst check_result = find_next_time_expression_time(check, seconds, minutes, hours) try: tzinfo.localize(check_result.replace(tzinfo=None), is_dst=None) return result except pytzexceptions.AmbiguousTimeError: pass # OK, edge case does apply. We must override the DST to DST-off check_result = tzinfo.localize(check_result.replace(tzinfo=None), is_dst=False) return check_result
"""The tests for the Recorder component.""" from datetime import datetime import pytest import pytz from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from homeassistant.components.recorder.models import ( Base, Events, RecorderRuns, States, process_timestamp, process_timestamp_to_utc_isoformat, ) from homeassistant.const import EVENT_STATE_CHANGED import homeassistant.core as ha from homeassistant.exceptions import InvalidEntityFormatError from homeassistant.util import dt import homeassistant.util.dt as dt_util def test_from_event_to_db_event(): """Test converting event to db event.""" event = ha.Event("test_event", {"some_data": 15}) assert event == Events.from_event(event).to_native() def test_from_event_to_db_state(): """Test converting event to db state.""" state = ha.State("sensor.temperature", "18") event = ha.Event( EVENT_STATE_CHANGED, {"entity_id": "sensor.temperature", "old_state": None, "new_state": state}, context=state.context, ) # We don't restore context unless we need it by joining the # events table on the event_id for state_changed events state.context = ha.Context(id=None) assert state == States.from_event(event).to_native() def test_from_event_to_delete_state(): """Test converting deleting state event to db state.""" event = ha.Event( EVENT_STATE_CHANGED, { "entity_id": "sensor.temperature", "old_state": ha.State("sensor.temperature", "18"), "new_state": None, }, ) db_state = States.from_event(event) assert db_state.entity_id == "sensor.temperature" assert db_state.domain == "sensor" assert db_state.state == "" assert db_state.last_changed == event.time_fired assert db_state.last_updated == event.time_fired def test_entity_ids(): """Test if entity ids helper method works.""" engine = create_engine("sqlite://") Base.metadata.create_all(engine) session_factory = sessionmaker(bind=engine) session = scoped_session(session_factory) session.query(Events).delete() session.query(States).delete() session.query(RecorderRuns).delete() run = RecorderRuns( start=datetime(2016, 7, 9, 11, 0, 0, tzinfo=dt.UTC), end=datetime(2016, 7, 9, 23, 0, 0, tzinfo=dt.UTC), closed_incorrect=False, created=datetime(2016, 7, 9, 11, 0, 0, tzinfo=dt.UTC), ) session.add(run) session.commit() before_run = datetime(2016, 7, 9, 8, 0, 0, tzinfo=dt.UTC) in_run = datetime(2016, 7, 9, 13, 0, 0, tzinfo=dt.UTC) in_run2 = datetime(2016, 7, 9, 15, 0, 0, tzinfo=dt.UTC) in_run3 = datetime(2016, 7, 9, 18, 0, 0, tzinfo=dt.UTC) after_run = datetime(2016, 7, 9, 23, 30, 0, tzinfo=dt.UTC) assert run.to_native() == run assert run.entity_ids() == [] session.add( States( entity_id="sensor.temperature", state="20", last_changed=before_run, last_updated=before_run, ) ) session.add( States( entity_id="sensor.sound", state="10", last_changed=after_run, last_updated=after_run, ) ) session.add( States( entity_id="sensor.humidity", state="76", last_changed=in_run, last_updated=in_run, ) ) session.add( States( entity_id="sensor.lux", state="5", last_changed=in_run3, last_updated=in_run3, ) ) assert sorted(run.entity_ids()) == ["sensor.humidity", "sensor.lux"] assert run.entity_ids(in_run2) == ["sensor.humidity"] def test_states_from_native_invalid_entity_id(): """Test loading a state from an invalid entity ID.""" state = States() state.entity_id = "test.invalid__id" state.attributes = "{}" with pytest.raises(InvalidEntityFormatError): state = state.to_native() state = state.to_native(validate_entity_id=False) assert state.entity_id == "test.invalid__id" async def test_process_timestamp(): """Test processing time stamp to UTC.""" datetime_with_tzinfo = datetime(2016, 7, 9, 11, 0, 0, tzinfo=dt.UTC) datetime_without_tzinfo = datetime(2016, 7, 9, 11, 0, 0) est = pytz.timezone("US/Eastern") datetime_est_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=est) nst = pytz.timezone("Canada/Newfoundland") datetime_nst_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=nst) hst = pytz.timezone("US/Hawaii") datetime_hst_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=hst) assert process_timestamp(datetime_with_tzinfo) == datetime( 2016, 7, 9, 11, 0, 0, tzinfo=dt.UTC ) assert process_timestamp(datetime_without_tzinfo) == datetime( 2016, 7, 9, 11, 0, 0, tzinfo=dt.UTC ) assert process_timestamp(datetime_est_timezone) == datetime( 2016, 7, 9, 15, 56, tzinfo=dt.UTC ) assert process_timestamp(datetime_nst_timezone) == datetime( 2016, 7, 9, 14, 31, tzinfo=dt.UTC ) assert process_timestamp(datetime_hst_timezone) == datetime( 2016, 7, 9, 21, 31, tzinfo=dt.UTC ) assert process_timestamp(None) is None async def test_process_timestamp_to_utc_isoformat(): """Test processing time stamp to UTC isoformat.""" datetime_with_tzinfo = datetime(2016, 7, 9, 11, 0, 0, tzinfo=dt.UTC) datetime_without_tzinfo = datetime(2016, 7, 9, 11, 0, 0) est = pytz.timezone("US/Eastern") datetime_est_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=est) est = pytz.timezone("US/Eastern") datetime_est_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=est) nst = pytz.timezone("Canada/Newfoundland") datetime_nst_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=nst) hst = pytz.timezone("US/Hawaii") datetime_hst_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=hst) assert ( process_timestamp_to_utc_isoformat(datetime_with_tzinfo) == "2016-07-09T11:00:00+00:00" ) assert ( process_timestamp_to_utc_isoformat(datetime_without_tzinfo) == "2016-07-09T11:00:00+00:00" ) assert ( process_timestamp_to_utc_isoformat(datetime_est_timezone) == "2016-07-09T15:56:00+00:00" ) assert ( process_timestamp_to_utc_isoformat(datetime_nst_timezone) == "2016-07-09T14:31:00+00:00" ) assert ( process_timestamp_to_utc_isoformat(datetime_hst_timezone) == "2016-07-09T21:31:00+00:00" ) assert process_timestamp_to_utc_isoformat(None) is None async def test_event_to_db_model(): """Test we can round trip Event conversion.""" event = ha.Event( "state_changed", {"some": "attr"}, ha.EventOrigin.local, dt_util.utcnow() ) native = Events.from_event(event).to_native() assert native == event native = Events.from_event(event, event_data="{}").to_native() event.data = {} assert native == event
partofthething/home-assistant
tests/components/recorder/test_models.py
homeassistant/util/dt.py
"""Component to integrate the Home Assistant cloud.""" from hass_nabucasa import Cloud import voluptuous as vol from homeassistant.components.alexa import const as alexa_const from homeassistant.components.google_assistant import const as ga_c from homeassistant.const import ( CONF_DESCRIPTION, CONF_MODE, CONF_NAME, CONF_REGION, EVENT_HOMEASSISTANT_STOP, ) from homeassistant.core import callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import config_validation as cv, entityfilter from homeassistant.loader import bind_hass from homeassistant.util.aiohttp import MockRequest from . import account_link, http_api from .client import CloudClient from .const import ( CONF_ACCOUNT_LINK_URL, CONF_ACME_DIRECTORY_SERVER, CONF_ALEXA, CONF_ALEXA_ACCESS_TOKEN_URL, CONF_ALIASES, CONF_CLOUDHOOK_CREATE_URL, CONF_COGNITO_CLIENT_ID, CONF_ENTITY_CONFIG, CONF_FILTER, CONF_GOOGLE_ACTIONS, CONF_GOOGLE_ACTIONS_REPORT_STATE_URL, CONF_RELAYER, CONF_REMOTE_API_URL, CONF_SUBSCRIPTION_INFO_URL, CONF_USER_POOL_ID, CONF_VOICE_API_URL, DOMAIN, MODE_DEV, MODE_PROD, ) from .prefs import CloudPreferences DEFAULT_MODE = MODE_PROD SERVICE_REMOTE_CONNECT = "remote_connect" SERVICE_REMOTE_DISCONNECT = "remote_disconnect" ALEXA_ENTITY_SCHEMA = vol.Schema( { vol.Optional(CONF_DESCRIPTION): cv.string, vol.Optional(alexa_const.CONF_DISPLAY_CATEGORIES): cv.string, vol.Optional(CONF_NAME): cv.string, } ) GOOGLE_ENTITY_SCHEMA = vol.Schema( { vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_ALIASES): vol.All(cv.ensure_list, [cv.string]), vol.Optional(ga_c.CONF_ROOM_HINT): cv.string, } ) ASSISTANT_SCHEMA = vol.Schema( {vol.Optional(CONF_FILTER, default=dict): entityfilter.FILTER_SCHEMA} ) ALEXA_SCHEMA = ASSISTANT_SCHEMA.extend( {vol.Optional(CONF_ENTITY_CONFIG): {cv.entity_id: ALEXA_ENTITY_SCHEMA}} ) GACTIONS_SCHEMA = ASSISTANT_SCHEMA.extend( {vol.Optional(CONF_ENTITY_CONFIG): {cv.entity_id: GOOGLE_ENTITY_SCHEMA}} ) # pylint: disable=no-value-for-parameter CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Optional(CONF_MODE, default=DEFAULT_MODE): vol.In( [MODE_DEV, MODE_PROD] ), vol.Optional(CONF_COGNITO_CLIENT_ID): str, vol.Optional(CONF_USER_POOL_ID): str, vol.Optional(CONF_REGION): str, vol.Optional(CONF_RELAYER): str, vol.Optional(CONF_SUBSCRIPTION_INFO_URL): vol.Url(), vol.Optional(CONF_CLOUDHOOK_CREATE_URL): vol.Url(), vol.Optional(CONF_REMOTE_API_URL): vol.Url(), vol.Optional(CONF_ACME_DIRECTORY_SERVER): vol.Url(), vol.Optional(CONF_ALEXA): ALEXA_SCHEMA, vol.Optional(CONF_GOOGLE_ACTIONS): GACTIONS_SCHEMA, vol.Optional(CONF_ALEXA_ACCESS_TOKEN_URL): vol.Url(), vol.Optional(CONF_GOOGLE_ACTIONS_REPORT_STATE_URL): vol.Url(), vol.Optional(CONF_ACCOUNT_LINK_URL): vol.Url(), vol.Optional(CONF_VOICE_API_URL): vol.Url(), } ) }, extra=vol.ALLOW_EXTRA, ) class CloudNotAvailable(HomeAssistantError): """Raised when an action requires the cloud but it's not available.""" @bind_hass @callback def async_is_logged_in(hass) -> bool: """Test if user is logged in.""" return DOMAIN in hass.data and hass.data[DOMAIN].is_logged_in @bind_hass @callback def async_active_subscription(hass) -> bool: """Test if user has an active subscription.""" return async_is_logged_in(hass) and not hass.data[DOMAIN].subscription_expired @bind_hass async def async_create_cloudhook(hass, webhook_id: str) -> str: """Create a cloudhook.""" if not async_is_logged_in(hass): raise CloudNotAvailable hook = await hass.data[DOMAIN].cloudhooks.async_create(webhook_id, True) return hook["cloudhook_url"] @bind_hass async def async_delete_cloudhook(hass, webhook_id: str) -> None: """Delete a cloudhook.""" if DOMAIN not in hass.data: raise CloudNotAvailable await hass.data[DOMAIN].cloudhooks.async_delete(webhook_id) @bind_hass @callback def async_remote_ui_url(hass) -> str: """Get the remote UI URL.""" if not async_is_logged_in(hass): raise CloudNotAvailable if not hass.data[DOMAIN].client.prefs.remote_enabled: raise CloudNotAvailable if not hass.data[DOMAIN].remote.instance_domain: raise CloudNotAvailable return f"https://{hass.data[DOMAIN].remote.instance_domain}" def is_cloudhook_request(request): """Test if a request came from a cloudhook. Async friendly. """ return isinstance(request, MockRequest) async def async_setup(hass, config): """Initialize the Home Assistant cloud.""" # Process configs if DOMAIN in config: kwargs = dict(config[DOMAIN]) else: kwargs = {CONF_MODE: DEFAULT_MODE} # Alexa/Google custom config alexa_conf = kwargs.pop(CONF_ALEXA, None) or ALEXA_SCHEMA({}) google_conf = kwargs.pop(CONF_GOOGLE_ACTIONS, None) or GACTIONS_SCHEMA({}) # Cloud settings prefs = CloudPreferences(hass) await prefs.async_initialize() # Initialize Cloud websession = hass.helpers.aiohttp_client.async_get_clientsession() client = CloudClient(hass, prefs, websession, alexa_conf, google_conf) cloud = hass.data[DOMAIN] = Cloud(client, **kwargs) async def _shutdown(event): """Shutdown event.""" await cloud.stop() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _shutdown) async def _service_handler(service): """Handle service for cloud.""" if service.service == SERVICE_REMOTE_CONNECT: await cloud.remote.connect() await prefs.async_update(remote_enabled=True) elif service.service == SERVICE_REMOTE_DISCONNECT: await cloud.remote.disconnect() await prefs.async_update(remote_enabled=False) hass.helpers.service.async_register_admin_service( DOMAIN, SERVICE_REMOTE_CONNECT, _service_handler ) hass.helpers.service.async_register_admin_service( DOMAIN, SERVICE_REMOTE_DISCONNECT, _service_handler ) loaded = False async def _on_connect(): """Discover RemoteUI binary sensor.""" nonlocal loaded # Prevent multiple discovery if loaded: return loaded = True await hass.helpers.discovery.async_load_platform( "binary_sensor", DOMAIN, {}, config ) await hass.helpers.discovery.async_load_platform("stt", DOMAIN, {}, config) await hass.helpers.discovery.async_load_platform("tts", DOMAIN, {}, config) cloud.iot.register_on_connect(_on_connect) await cloud.start() await http_api.async_setup(hass) account_link.async_setup(hass) return True
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/cloud/__init__.py
"""Support for hydrological data from the Fed. Office for the Environment.""" from datetime import timedelta import logging from swisshydrodata import SwissHydroData import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ATTR_ATTRIBUTION, CONF_MONITORED_CONDITIONS import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTRIBUTION = "Data provided by the Swiss Federal Office for the Environment FOEN" ATTR_DELTA_24H = "delta-24h" ATTR_MAX_1H = "max-1h" ATTR_MAX_24H = "max-24h" ATTR_MEAN_1H = "mean-1h" ATTR_MEAN_24H = "mean-24h" ATTR_MIN_1H = "min-1h" ATTR_MIN_24H = "min-24h" ATTR_PREVIOUS_24H = "previous-24h" ATTR_STATION = "station" ATTR_STATION_UPDATE = "station_update" ATTR_WATER_BODY = "water_body" ATTR_WATER_BODY_TYPE = "water_body_type" CONF_STATION = "station" MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60) SENSOR_DISCHARGE = "discharge" SENSOR_LEVEL = "level" SENSOR_TEMPERATURE = "temperature" CONDITIONS = { SENSOR_DISCHARGE: "mdi:waves", SENSOR_LEVEL: "mdi:zodiac-aquarius", SENSOR_TEMPERATURE: "mdi:oil-temperature", } CONDITION_DETAILS = [ ATTR_DELTA_24H, ATTR_MAX_1H, ATTR_MAX_24H, ATTR_MEAN_1H, ATTR_MEAN_24H, ATTR_MIN_1H, ATTR_MIN_24H, ATTR_PREVIOUS_24H, ] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_STATION): vol.Coerce(int), vol.Optional(CONF_MONITORED_CONDITIONS, default=[SENSOR_TEMPERATURE]): vol.All( cv.ensure_list, [vol.In(CONDITIONS)] ), } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Swiss hydrological sensor.""" station = config.get(CONF_STATION) monitored_conditions = config.get(CONF_MONITORED_CONDITIONS) hydro_data = HydrologicalData(station) hydro_data.update() if hydro_data.data is None: _LOGGER.error("The station doesn't exists: %s", station) return entities = [] for condition in monitored_conditions: entities.append(SwissHydrologicalDataSensor(hydro_data, station, condition)) add_entities(entities, True) class SwissHydrologicalDataSensor(SensorEntity): """Implementation of a Swiss hydrological sensor.""" def __init__(self, hydro_data, station, condition): """Initialize the Swiss hydrological sensor.""" self.hydro_data = hydro_data self._condition = condition self._data = self._state = self._unit_of_measurement = None self._icon = CONDITIONS[condition] self._station = station @property def name(self): """Return the name of the sensor.""" return "{} {}".format(self._data["water-body-name"], self._condition) @property def unique_id(self) -> str: """Return a unique, friendly identifier for this entity.""" return f"{self._station}_{self._condition}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" if self._state is not None: return self.hydro_data.data["parameters"][self._condition]["unit"] return None @property def state(self): """Return the state of the sensor.""" if isinstance(self._state, (int, float)): return round(self._state, 2) return None @property def extra_state_attributes(self): """Return the device state attributes.""" attrs = {} if not self._data: attrs[ATTR_ATTRIBUTION] = ATTRIBUTION return attrs attrs[ATTR_WATER_BODY_TYPE] = self._data["water-body-type"] attrs[ATTR_STATION] = self._data["name"] attrs[ATTR_STATION_UPDATE] = self._data["parameters"][self._condition][ "datetime" ] attrs[ATTR_ATTRIBUTION] = ATTRIBUTION for entry in CONDITION_DETAILS: attrs[entry.replace("-", "_")] = self._data["parameters"][self._condition][ entry ] return attrs @property def icon(self): """Icon to use in the frontend.""" return self._icon def update(self): """Get the latest data and update the state.""" self.hydro_data.update() self._data = self.hydro_data.data if self._data is None: self._state = None else: self._state = self._data["parameters"][self._condition]["value"] class HydrologicalData: """The Class for handling the data retrieval.""" def __init__(self, station): """Initialize the data object.""" self.station = station self.data = None @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Get the latest data.""" shd = SwissHydroData() self.data = shd.get_station(self.station)
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/swiss_hydrological_data/sensor.py
"""Support for MQTT vacuums.""" import functools import voluptuous as vol from homeassistant.components.vacuum import DOMAIN from homeassistant.helpers.reload import async_setup_reload_service from .. import DOMAIN as MQTT_DOMAIN, PLATFORMS from ..mixins import async_setup_entry_helper from .schema import CONF_SCHEMA, LEGACY, MQTT_VACUUM_SCHEMA, STATE from .schema_legacy import PLATFORM_SCHEMA_LEGACY, async_setup_entity_legacy from .schema_state import PLATFORM_SCHEMA_STATE, async_setup_entity_state def validate_mqtt_vacuum(value): """Validate MQTT vacuum schema.""" schemas = {LEGACY: PLATFORM_SCHEMA_LEGACY, STATE: PLATFORM_SCHEMA_STATE} return schemas[value[CONF_SCHEMA]](value) PLATFORM_SCHEMA = vol.All( MQTT_VACUUM_SCHEMA.extend({}, extra=vol.ALLOW_EXTRA), validate_mqtt_vacuum ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up MQTT vacuum through configuration.yaml.""" await async_setup_reload_service(hass, MQTT_DOMAIN, PLATFORMS) await _async_setup_entity(async_add_entities, config) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up MQTT vacuum dynamically through MQTT discovery.""" setup = functools.partial( _async_setup_entity, async_add_entities, config_entry=config_entry ) await async_setup_entry_helper(hass, DOMAIN, setup, PLATFORM_SCHEMA) async def _async_setup_entity( async_add_entities, config, config_entry=None, discovery_data=None ): """Set up the MQTT vacuum.""" setup_entity = {LEGACY: async_setup_entity_legacy, STATE: async_setup_entity_state} await setup_entity[config[CONF_SCHEMA]]( config, async_add_entities, config_entry, discovery_data )
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/mqtt/vacuum/__init__.py
"""Models for permissions.""" from __future__ import annotations from typing import TYPE_CHECKING import attr if TYPE_CHECKING: from homeassistant.helpers import ( device_registry as dev_reg, entity_registry as ent_reg, ) @attr.s(slots=True) class PermissionLookup: """Class to hold data for permission lookups.""" entity_registry: ent_reg.EntityRegistry = attr.ib() device_registry: dev_reg.DeviceRegistry = attr.ib()
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/auth/permissions/models.py
"""Reproduce an Input select state.""" from __future__ import annotations import asyncio import logging from types import MappingProxyType from typing import Any, Iterable from homeassistant.const import ATTR_ENTITY_ID from homeassistant.core import Context, HomeAssistant, State from . import ( ATTR_OPTION, ATTR_OPTIONS, DOMAIN, SERVICE_SELECT_OPTION, SERVICE_SET_OPTIONS, ) ATTR_GROUP = [ATTR_OPTION, ATTR_OPTIONS] _LOGGER = logging.getLogger(__name__) async def _async_reproduce_state( hass: HomeAssistant, state: State, *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None: """Reproduce a single state.""" cur_state = hass.states.get(state.entity_id) # Return if we can't find entity if cur_state is None: _LOGGER.warning("Unable to find entity %s", state.entity_id) return # Return if we are already at the right state. if cur_state.state == state.state and all( check_attr_equal(cur_state.attributes, state.attributes, attr) for attr in ATTR_GROUP ): return # Set service data service_data = {ATTR_ENTITY_ID: state.entity_id} # If options are specified, call SERVICE_SET_OPTIONS if ATTR_OPTIONS in state.attributes: service = SERVICE_SET_OPTIONS service_data[ATTR_OPTIONS] = state.attributes[ATTR_OPTIONS] await hass.services.async_call( DOMAIN, service, service_data, context=context, blocking=True ) # Remove ATTR_OPTIONS from service_data so we can reuse service_data in next call del service_data[ATTR_OPTIONS] # Call SERVICE_SELECT_OPTION service = SERVICE_SELECT_OPTION service_data[ATTR_OPTION] = state.state await hass.services.async_call( DOMAIN, service, service_data, context=context, blocking=True ) async def async_reproduce_states( hass: HomeAssistant, states: Iterable[State], *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None: """Reproduce Input select states.""" # Reproduce states in parallel. await asyncio.gather( *( _async_reproduce_state( hass, state, context=context, reproduce_options=reproduce_options ) for state in states ) ) def check_attr_equal( attr1: MappingProxyType, attr2: MappingProxyType, attr_str: str ) -> bool: """Return true if the given attributes are equal.""" return attr1.get(attr_str) == attr2.get(attr_str)
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/input_select/reproduce_state.py