Merge remote-tracking branch 'upstream/dev' into igd

This commit is contained in:
Steven Looman committed 2018-08-24 15:25:07 +02:00
commit e73f31d829
485 files changed
+6059 -3434

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Tests for the multi-factor auth modules."""
@@ -0,0 +1,127 @@
"""Test the example module auth module."""
from homeassistant import auth, data_entry_flow
from homeassistant.auth.mfa_modules import auth_mfa_module_from_config
from homeassistant.auth.models import Credentials
from tests.common import MockUser
async def test_validate(hass):
"""Test validating pin."""
auth_module = await auth_mfa_module_from_config(hass, {
'type': 'insecure_example',
'data': [{'user_id': 'test-user', 'pin': '123456'}]
})
result = await auth_module.async_validation(
'test-user', {'pin': '123456'})
assert result is True
result = await auth_module.async_validation(
'test-user', {'pin': 'invalid'})
assert result is False
result = await auth_module.async_validation(
'invalid-user', {'pin': '123456'})
assert result is False
async def test_setup_user(hass):
"""Test setup user."""
auth_module = await auth_mfa_module_from_config(hass, {
'type': 'insecure_example',
'data': []
})
await auth_module.async_setup_user(
'test-user', {'pin': '123456'})
assert len(auth_module._data) == 1
result = await auth_module.async_validation(
'test-user', {'pin': '123456'})
assert result is True
async def test_depose_user(hass):
"""Test despose user."""
auth_module = await auth_mfa_module_from_config(hass, {
'type': 'insecure_example',
'data': [{'user_id': 'test-user', 'pin': '123456'}]
})
assert len(auth_module._data) == 1
await auth_module.async_depose_user('test-user')
assert len(auth_module._data) == 0
async def test_is_user_setup(hass):
"""Test is user setup."""
auth_module = await auth_mfa_module_from_config(hass, {
'type': 'insecure_example',
'data': [{'user_id': 'test-user', 'pin': '123456'}]
})
assert await auth_module.async_is_user_setup('test-user') is True
assert await auth_module.async_is_user_setup('invalid-user') is False
async def test_login(hass):
"""Test login flow with auth module."""
hass.auth = await auth.auth_manager_from_config(hass, [{
'type': 'insecure_example',
'users': [{'username': 'test-user', 'password': 'test-pass'}],
}], [{
'type': 'insecure_example',
'data': [{'user_id': 'mock-user', 'pin': '123456'}]
}])
user = MockUser(
id='mock-user',
is_owner=False,
is_active=False,
name='Paulus',
).add_to_auth_manager(hass.auth)
await hass.auth.async_link_user(user, Credentials(
id='mock-id',
auth_provider_type='insecure_example',
auth_provider_id=None,
data={'username': 'test-user'},
is_new=False,
))
provider = hass.auth.auth_providers[0]
result = await hass.auth.login_flow.async_init(
(provider.type, provider.id))
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
result = await hass.auth.login_flow.async_configure(
result['flow_id'], {
'username': 'incorrect-user',
'password': 'test-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_auth'
result = await hass.auth.login_flow.async_configure(
result['flow_id'], {
'username': 'test-user',
'password': 'incorrect-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_auth'
result = await hass.auth.login_flow.async_configure(
result['flow_id'], {
'username': 'test-user',
'password': 'test-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'mfa'
assert result['data_schema'].schema.get('pin') == str
result = await hass.auth.login_flow.async_configure(
result['flow_id'], {'pin': 'invalid-code'})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_auth'
result = await hass.auth.login_flow.async_configure(
result['flow_id'], {'pin': '123456'})
assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result['data'].id == 'mock-user'
+8 -6
View File
@@ -4,7 +4,7 @@ from unittest.mock import Mock
import pytest
from homeassistant import data_entry_flow
from homeassistant.auth import auth_manager_from_config
from homeassistant.auth import auth_manager_from_config, auth_store
from homeassistant.auth.providers import (
auth_provider_from_config, homeassistant as hass_auth)
@@ -24,7 +24,7 @@ async def test_adding_user(data, hass):
async def test_adding_user_duplicate_username(data, hass):
"""Test adding a user."""
"""Test adding a user with duplicate username."""
data.add_auth('test-user', 'test-pass')
with pytest.raises(hass_auth.InvalidUser):
data.add_auth('test-user', 'other-pass')
@@ -37,7 +37,7 @@ async def test_validating_password_invalid_user(data, hass):
async def test_validating_password_invalid_password(data, hass):
"""Test validating an invalid user."""
"""Test validating an invalid password."""
data.add_auth('test-user', 'test-pass')
with pytest.raises(hass_auth.InvalidAuth):
@@ -67,8 +67,9 @@ async def test_login_flow_validates(data, hass):
data.add_auth('test-user', 'test-pass')
await data.async_save()
provider = hass_auth.HassAuthProvider(hass, None, {})
flow = hass_auth.LoginFlow(provider)
provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass),
{'type': 'homeassistant'})
flow = await provider.async_login_flow({})
result = await flow.async_step_init()
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
@@ -91,6 +92,7 @@ async def test_login_flow_validates(data, hass):
'password': 'test-pass',
})
assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result['data']['username'] == 'test-user'
async def test_saving_loading(data, hass):
@@ -122,7 +124,7 @@ async def test_new_users_populate_values(hass, data):
manager = await auth_manager_from_config(hass, [{
'type': 'homeassistant'
}])
}], [])
provider = manager.auth_providers[0]
credentials = await provider.async_get_or_create_credentials({
'username': 'hello'
@@ -40,7 +40,7 @@ def manager(hass, store, provider):
"""Mock manager."""
return AuthManager(hass, store, {
(provider.type, provider.id): provider
})
}, {})
async def test_create_new_credential(manager, provider):
@@ -3,7 +3,7 @@ from unittest.mock import Mock
import pytest
from homeassistant import auth
from homeassistant import auth, data_entry_flow
from homeassistant.auth import auth_store
from homeassistant.auth.providers import legacy_api_password
@@ -27,7 +27,7 @@ def manager(hass, store, provider):
"""Mock manager."""
return auth.AuthManager(hass, store, {
(provider.type, provider.id): provider
})
}, {})
async def test_create_new_credential(manager, provider):
@@ -51,17 +51,6 @@ async def test_only_one_credentials(manager, provider):
assert credentials2.is_new is False
async def test_verify_not_load(hass, provider):
"""Test we raise if http module not load."""
with pytest.raises(ValueError):
provider.async_validate_login('test-password')
hass.http = Mock(api_password=None)
with pytest.raises(ValueError):
provider.async_validate_login('test-password')
hass.http = Mock(api_password='test-password')
provider.async_validate_login('test-password')
async def test_verify_login(hass, provider):
"""Test login using legacy api password auth provider."""
hass.http = Mock(api_password='test-password')
@@ -69,3 +58,45 @@ async def test_verify_login(hass, provider):
hass.http = Mock(api_password='test-password')
with pytest.raises(legacy_api_password.InvalidAuthError):
provider.async_validate_login('invalid-password')
async def test_login_flow_abort(hass, manager):
"""Test wrong config."""
for http in (
None,
Mock(api_password=None),
Mock(api_password=''),
):
hass.http = http
result = await manager.login_flow.async_init(
handler=('legacy_api_password', None)
)
assert result['type'] == data_entry_flow.RESULT_TYPE_ABORT
assert result['reason'] == 'no_api_password_set'
async def test_login_flow_works(hass, manager):
"""Test wrong config."""
hass.http = Mock(api_password='hello')
result = await manager.login_flow.async_init(
handler=('legacy_api_password', None)
)
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
result = await manager.login_flow.async_configure(
flow_id=result['flow_id'],
user_input={
'password': 'not-hello'
}
)
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_auth'
result = await manager.login_flow.async_configure(
flow_id=result['flow_id'],
user_input={
'password': 'hello'
}
)
assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
@@ -28,7 +28,7 @@ def manager(hass, store, provider):
"""Mock manager."""
return auth.AuthManager(hass, store, {
(provider.type, provider.id): provider
})
}, {})
async def test_trusted_networks_credentials(manager, provider):
@@ -72,7 +72,7 @@ async def test_login_flow(manager, provider):
user = await manager.async_create_user("test-user")
# trusted network didn't loaded
flow = await provider.async_credential_flow({'ip_address': '127.0.0.1'})
flow = await provider.async_login_flow({'ip_address': '127.0.0.1'})
step = await flow.async_step_init()
assert step['step_id'] == 'init'
assert step['errors']['base'] == 'invalid_auth'
@@ -80,13 +80,13 @@ async def test_login_flow(manager, provider):
provider.hass.http = Mock(trusted_networks=['192.168.0.1'])
# not from trusted network
flow = await provider.async_credential_flow({'ip_address': '127.0.0.1'})
flow = await provider.async_login_flow({'ip_address': '127.0.0.1'})
step = await flow.async_step_init()
assert step['step_id'] == 'init'
assert step['errors']['base'] == 'invalid_auth'
# from trusted network, list users
flow = await provider.async_credential_flow({'ip_address': '192.168.0.1'})
flow = await provider.async_login_flow({'ip_address': '192.168.0.1'})
step = await flow.async_step_init()
assert step['step_id'] == 'init'
+374 -20
View File
@@ -7,6 +7,7 @@ import pytest
from homeassistant import auth, data_entry_flow
from homeassistant.auth import (
models as auth_models, auth_store, const as auth_const)
from homeassistant.auth.mfa_modules import SESSION_EXPIRATION
from homeassistant.util import dt as dt_util
from tests.common import (
MockUser, ensure_auth_manager_loaded, flush_store, CLIENT_ID)
@@ -40,7 +41,7 @@ async def test_auth_manager_from_config_validates_config_and_id(mock_hass):
'type': 'insecure_example',
'id': 'another',
'users': [],
}])
}], [])
providers = [{
'name': provider.name,
@@ -58,7 +59,65 @@ async def test_auth_manager_from_config_validates_config_and_id(mock_hass):
}]
async def test_create_new_user(hass, hass_storage):
async def test_auth_manager_from_config_auth_modules(mock_hass):
"""Test get auth modules."""
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': [],
}, {
'name': 'Duplicate ID',
'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."""
manager = await auth.auth_manager_from_config(hass, [{
'type': 'insecure_example',
@@ -67,7 +126,7 @@ async def test_create_new_user(hass, hass_storage):
'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
@@ -77,8 +136,7 @@ async def test_create_new_user(hass, hass_storage):
'password': 'test-pass',
})
assert step['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
credentials = step['result']
user = await manager.async_get_or_create_user(credentials)
user = step['result']
assert user is not None
assert user.is_owner is False
assert user.name == 'Test Name'
@@ -93,7 +151,8 @@ async def test_login_as_existing_user(mock_hass):
'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
@@ -134,9 +193,8 @@ async def test_login_as_existing_user(mock_hass):
'password': 'test-pass',
})
assert step['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
credentials = step['result']
user = await manager.async_get_or_create_user(credentials)
user = step['result']
assert user is not None
assert user.id == 'mock-user'
assert user.is_owner is False
@@ -159,23 +217,25 @@ async def test_linking_user_to_two_auth_providers(hass, hass_storage):
'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',
})
user = await manager.async_get_or_create_user(step['result'])
user = step['result']
assert user is not None
step = await manager.login_flow.async_init(('insecure_example',
'another-provider'))
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',
})
await manager.async_link_user(user, step['result'])
new_credential = step['result']
await manager.async_link_user(user, new_credential)
assert len(user.credentials) == 2
@@ -190,14 +250,14 @@ async def test_saving_loading(hass, hass_storage):
'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',
})
user = await manager.async_get_or_create_user(step['result'])
user = step['result']
await manager.async_activate_user(user)
await manager.async_create_refresh_token(user, CLIENT_ID)
@@ -211,7 +271,7 @@ async def test_saving_loading(hass, hass_storage):
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, [])
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
@@ -236,7 +296,7 @@ async def test_cannot_retrieve_expired_access_token(hass):
async def test_generating_system_user(hass):
"""Test that we can add a system user."""
manager = await auth.auth_manager_from_config(hass, [])
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
@@ -246,7 +306,7 @@ async def test_generating_system_user(hass):
async def test_refresh_token_requires_client_for_user(hass):
"""Test that we can add a system user."""
manager = await auth.auth_manager_from_config(hass, [])
manager = await auth.auth_manager_from_config(hass, [], [])
user = MockUser().add_to_auth_manager(manager)
assert user.system_generated is False
@@ -260,7 +320,7 @@ async def test_refresh_token_requires_client_for_user(hass):
async def test_refresh_token_not_requires_client_for_system_user(hass):
"""Test that we can add a system user."""
manager = await auth.auth_manager_from_config(hass, [])
manager = await auth.auth_manager_from_config(hass, [], [])
user = await manager.async_create_system_user('Hass.io')
assert user.system_generated is True
@@ -274,10 +334,304 @@ async def test_refresh_token_not_requires_client_for_system_user(hass):
async def test_cannot_deactive_owner(mock_hass):
"""Test that we cannot deactive the owner."""
manager = await auth.auth_manager_from_config(mock_hass, [])
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_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 auth error
assert step['type'] == data_entry_flow.RESULT_TYPE_FORM
assert step['step_id'] == 'mfa'
assert step['errors'] == {'base': 'invalid_auth'}
step = await manager.login_flow.async_configure(step['flow_id'], {
'pin': 'test-pin',
})
# Finally passed, get user
assert step['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
user = step['result']
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_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 user
assert step['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
user = step['result']
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_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() + SESSION_EXPIRATION):
step = await manager.login_flow.async_configure(step['flow_id'], {
'pin': 'test-pin',
})
# Invalid auth due session timeout
assert step['type'] == data_entry_flow.RESULT_TYPE_FORM
assert step['step_id'] == 'mfa'
assert step['errors']['base'] == 'login_expired'
# The second try will fail as well
step = await manager.login_flow.async_configure(step['flow_id'], {
'pin': 'test-pin',
})
assert step['type'] == data_entry_flow.RESULT_TYPE_FORM
assert step['step_id'] == 'mfa'
assert step['errors']['base'] == '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',
})
user = step['result']
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')
+27 -6
View File
@@ -118,19 +118,35 @@ def async_test_home_assistant(loop):
hass = ha.HomeAssistant(loop)
hass.config.async_load = Mock()
store = auth_store.AuthStore(hass)
hass.auth = auth.AuthManager(hass, store, {})
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 a magic mock."""
"""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()
@@ -307,7 +323,12 @@ def mock_registry(hass, mock_entries=None):
"""Mock the Entity Registry."""
registry = entity_registry.EntityRegistry(hass)
registry.entities = mock_entries or {}
hass.data[entity_registry.DATA_REGISTRY] = registry
async def _get_reg():
return registry
hass.data[entity_registry.DATA_REGISTRY] = \
hass.loop.create_task(_get_reg())
return registry
@@ -321,7 +342,7 @@ class MockUser(auth_models.User):
'is_owner': is_owner,
'is_active': is_active,
'name': name,
'system_generated': system_generated
'system_generated': system_generated,
}
if id is not None:
kwargs['id'] = id
@@ -339,7 +360,7 @@ class MockUser(auth_models.User):
async def register_auth_provider(hass, config):
"""Helper to register an auth provider."""
"""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'
@@ -728,7 +749,7 @@ class MockEntity(entity.Entity):
return self._handle('available')
def _handle(self, attr):
"""Helper for the attributes."""
"""Return attribute value."""
if attr in self._values:
return self._values[attr]
return getattr(super(), attr)
@@ -22,7 +22,7 @@ class TestAlarmControlPanelManual(unittest.TestCase):
"""Test the manual alarm module."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self): # pylint: disable=invalid-name
@@ -21,7 +21,7 @@ class TestAlarmControlPanelManualMqtt(unittest.TestCase):
"""Test the manual_mqtt alarm module."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_publish = mock_mqtt_component(self.hass)
@@ -21,7 +21,7 @@ class TestAlarmControlPanelMQTT(unittest.TestCase):
# pylint: disable=invalid-name
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_publish = mock_mqtt_component(self.hass)
+75 -9
View File
@@ -5,9 +5,10 @@ from uuid import uuid4
import pytest
from homeassistant.core import Context, callback
from homeassistant.const import (
TEMP_FAHRENHEIT, STATE_LOCKED, STATE_UNLOCKED,
STATE_UNKNOWN)
TEMP_CELSIUS, TEMP_FAHRENHEIT, STATE_LOCKED,
STATE_UNLOCKED, STATE_UNKNOWN)
from homeassistant.setup import async_setup_component
from homeassistant.components import alexa
from homeassistant.components.alexa import smart_home
@@ -18,6 +19,17 @@ from tests.common import async_mock_service
DEFAULT_CONFIG = smart_home.Config(should_expose=lambda entity_id: True)
@pytest.fixture
def events(hass):
"""Fixture that catches alexa events."""
events = []
hass.bus.async_listen(
smart_home.EVENT_ALEXA_SMART_HOME,
callback(lambda e: events.append(e))
)
yield events
def get_new_request(namespace, name, endpoint=None):
"""Generate a new API message."""
raw_msg = {
@@ -145,7 +157,7 @@ def assert_endpoint_capabilities(endpoint, *interfaces):
@asyncio.coroutine
def test_switch(hass):
def test_switch(hass, events):
"""Test switch discovery."""
device = ('switch.test', 'on', {'friendly_name': "Test switch"})
appliance = yield from discovery_test(device, hass)
@@ -695,6 +707,7 @@ def test_unknown_sensor(hass):
async def test_thermostat(hass):
"""Test thermostat discovery."""
hass.config.units.temperature_unit = TEMP_FAHRENHEIT
device = (
'climate.test_thermostat',
'cool',
@@ -709,7 +722,6 @@ async def test_thermostat(hass):
'operation_list': ['heat', 'cool', 'auto', 'off'],
'min_temp': 50,
'max_temp': 90,
'unit_of_measurement': TEMP_FAHRENHEIT,
}
)
appliance = await discovery_test(device, hass)
@@ -826,6 +838,7 @@ async def test_thermostat(hass):
payload={'thermostatMode': {'value': 'INVALID'}}
)
assert msg['event']['payload']['type'] == 'UNSUPPORTED_THERMOSTAT_MODE'
hass.config.units.temperature_unit = TEMP_CELSIUS
@asyncio.coroutine
@@ -963,23 +976,26 @@ def assert_request_calls_service(
response_type='Response',
payload=None):
"""Assert an API request calls a hass service."""
context = Context()
request = get_new_request(namespace, name, endpoint)
if payload:
request['directive']['payload'] = payload
domain, service_name = service.split('.')
call = async_mock_service(hass, domain, service_name)
calls = async_mock_service(hass, domain, service_name)
msg = yield from smart_home.async_handle_message(
hass, DEFAULT_CONFIG, request)
hass, DEFAULT_CONFIG, request, context)
yield from hass.async_block_till_done()
assert len(call) == 1
assert len(calls) == 1
call = calls[0]
assert 'event' in msg
assert call[0].data['entity_id'] == endpoint.replace('#', '.')
assert call.data['entity_id'] == endpoint.replace('#', '.')
assert msg['event']['header']['name'] == response_type
assert call.context == context
return call[0], msg
return call, msg
@asyncio.coroutine
@@ -1372,3 +1388,53 @@ def test_api_select_input(hass, domain, payload, source_list, idx):
hass,
payload={'input': payload})
assert call.data['source'] == source_list[idx]
async def test_logging_request(hass, events):
"""Test that we log requests."""
context = Context()
request = get_new_request('Alexa.Discovery', 'Discover')
await smart_home.async_handle_message(
hass, DEFAULT_CONFIG, request, context)
# To trigger event listener
await hass.async_block_till_done()
assert len(events) == 1
event = events[0]
assert event.data['request'] == {
'namespace': 'Alexa.Discovery',
'name': 'Discover',
}
assert event.data['response'] == {
'namespace': 'Alexa.Discovery',
'name': 'Discover.Response'
}
assert event.context == context
async def test_logging_request_with_entity(hass, events):
"""Test that we log requests."""
context = Context()
request = get_new_request('Alexa.PowerController', 'TurnOn', 'switch#xy')
await smart_home.async_handle_message(
hass, DEFAULT_CONFIG, request, context)
# To trigger event listener
await hass.async_block_till_done()
assert len(events) == 1
event = events[0]
assert event.data['request'] == {
'namespace': 'Alexa.PowerController',
'name': 'TurnOn',
'entity_id': 'switch.xy'
}
# Entity doesn't exist
assert event.data['response'] == {
'namespace': 'Alexa',
'name': 'ErrorResponse'
}
assert event.context == context
+6 -3
View File
@@ -15,11 +15,14 @@ BASE_CONFIG = [{
}]
}]
EMPTY_CONFIG = []
async def async_setup_auth(hass, aiohttp_client, provider_configs=BASE_CONFIG,
setup_api=False):
"""Helper to setup authentication and create a HTTP client."""
hass.auth = await auth.auth_manager_from_config(hass, provider_configs)
module_configs=EMPTY_CONFIG, setup_api=False):
"""Set up authentication and create an HTTP client."""
hass.auth = await auth.auth_manager_from_config(
hass, provider_configs, module_configs)
ensure_auth_manager_loaded(hass.auth)
await async_setup_component(hass, 'auth', {
'http': {
+23 -6
View File
@@ -1,4 +1,5 @@
"""Tests for the client validator."""
import asyncio
from unittest.mock import patch
import pytest
@@ -6,6 +7,18 @@ import pytest
from homeassistant.components.auth import indieauth
from tests.common import mock_coro
from tests.test_util.aiohttp import AiohttpClientMocker
@pytest.fixture
def mock_session():
"""Mock aiohttp.ClientSession."""
mocker = AiohttpClientMocker()
with patch('aiohttp.ClientSession',
side_effect=lambda *args, **kwargs:
mocker.create_session(asyncio.get_event_loop())):
yield mocker
def test_client_id_scheme():
@@ -120,9 +133,9 @@ async def test_verify_redirect_uri():
)
async def test_find_link_tag(hass, aioclient_mock):
async def test_find_link_tag(hass, mock_session):
"""Test finding link tag."""
aioclient_mock.get("http://127.0.0.1:8000", text="""
mock_session.get("http://127.0.0.1:8000", text="""
<!doctype html>
<html>
<head>
@@ -142,11 +155,15 @@ async def test_find_link_tag(hass, aioclient_mock):
]
async def test_find_link_tag_max_size(hass, aioclient_mock):
async def test_find_link_tag_max_size(hass, mock_session):
"""Test finding link tag."""
text = ("0" * 1024 * 10) + '<link rel="redirect_uri" href="/beer">'
aioclient_mock.get("http://127.0.0.1:8000", text=text)
text = ''.join([
'<link rel="redirect_uri" href="/wine">',
("0" * 1024 * 10),
'<link rel="redirect_uri" href="/beer">',
])
mock_session.get("http://127.0.0.1:8000", text=text)
redirect_uris = await indieauth.fetch_redirect_uris(
hass, "http://127.0.0.1:8000")
assert redirect_uris == []
assert redirect_uris == ["http://127.0.0.1:8000/wine"]
+53 -9
View File
@@ -3,13 +3,14 @@ from datetime import timedelta
from unittest.mock import patch
from homeassistant.auth.models import Credentials
from homeassistant.components.auth import RESULT_TYPE_USER
from homeassistant.setup import async_setup_component
from homeassistant.util.dt import utcnow
from homeassistant.components import auth
from . import async_setup_auth
from tests.common import CLIENT_ID, CLIENT_REDIRECT_URI
from tests.common import CLIENT_ID, CLIENT_REDIRECT_URI, MockUser
async def test_login_new_user_and_trying_refresh_token(hass, aiohttp_client):
@@ -74,26 +75,26 @@ async def test_login_new_user_and_trying_refresh_token(hass, aiohttp_client):
assert resp.status == 200
def test_credential_store_expiration():
"""Test that the credential store will not return expired tokens."""
store, retrieve = auth._create_cred_store()
def test_auth_code_store_expiration():
"""Test that the auth code store will not return expired tokens."""
store, retrieve = auth._create_auth_code_store()
client_id = 'bla'
credentials = 'creds'
user = MockUser(id='mock_user')
now = utcnow()
with patch('homeassistant.util.dt.utcnow', return_value=now):
code = store(client_id, credentials)
code = store(client_id, user)
with patch('homeassistant.util.dt.utcnow',
return_value=now + timedelta(minutes=10)):
assert retrieve(client_id, code) is None
assert retrieve(client_id, RESULT_TYPE_USER, code) is None
with patch('homeassistant.util.dt.utcnow', return_value=now):
code = store(client_id, credentials)
code = store(client_id, user)
with patch('homeassistant.util.dt.utcnow',
return_value=now + timedelta(minutes=9, seconds=59)):
assert retrieve(client_id, code) == credentials
assert retrieve(client_id, RESULT_TYPE_USER, code) == user
async def test_ws_current_user(hass, hass_ws_client, hass_access_token):
@@ -223,3 +224,46 @@ async def test_refresh_token_different_client_id(hass, aiohttp_client):
await hass.auth.async_validate_access_token(tokens['access_token'])
is not None
)
async def test_revoking_refresh_token(hass, aiohttp_client):
"""Test that we can revoke refresh tokens."""
client = await async_setup_auth(hass, aiohttp_client)
user = await hass.auth.async_create_user('Test User')
refresh_token = await hass.auth.async_create_refresh_token(user, CLIENT_ID)
# Test that we can create an access token
resp = await client.post('/auth/token', data={
'client_id': CLIENT_ID,
'grant_type': 'refresh_token',
'refresh_token': refresh_token.token,
})
assert resp.status == 200
tokens = await resp.json()
assert (
await hass.auth.async_validate_access_token(tokens['access_token'])
is not None
)
# Revoke refresh token
resp = await client.post('/auth/token', data={
'token': refresh_token.token,
'action': 'revoke',
})
assert resp.status == 200
# Old access token should be no longer valid
assert (
await hass.auth.async_validate_access_token(tokens['access_token'])
is None
)
# Test that we no longer can create an access token
resp = await client.post('/auth/token', data={
'client_id': CLIENT_ID,
'grant_type': 'refresh_token',
'refresh_token': refresh_token.token,
})
assert resp.status == 400
+2 -1
View File
@@ -5,7 +5,7 @@ from tests.common import CLIENT_ID, CLIENT_REDIRECT_URI
async def async_get_code(hass, aiohttp_client):
"""Helper for link user tests that returns authorization code."""
"""Return authorization code for link user tests."""
config = [{
'name': 'Example',
'type': 'insecure_example',
@@ -34,6 +34,7 @@ async def async_get_code(hass, aiohttp_client):
'client_id': CLIENT_ID,
'handler': ['insecure_example', '2nd auth'],
'redirect_uri': CLIENT_REDIRECT_URI,
'type': 'link_user',
})
assert resp.status == 200
step = await resp.json()
+2 -2
View File
@@ -13,14 +13,14 @@ class TestAutomationEvent(unittest.TestCase):
"""Test the event automation."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_component(self.hass, 'group')
self.calls = []
@callback
def record_call(service):
"""Helper for recording the call."""
"""Record the call."""
self.calls.append(service)
self.hass.services.register('test', 'automation', record_call)
+1 -1
View File
@@ -22,7 +22,7 @@ class TestAutomation(unittest.TestCase):
"""Test the event automation."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.calls = mock_service(self.hass, 'test', 'automation')
+1 -1
View File
@@ -23,7 +23,7 @@ class TestLiteJetTrigger(unittest.TestCase):
@mock.patch('pylitejet.LiteJet')
def setup_method(self, method, mock_pylitejet):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.start()
+2 -2
View File
@@ -14,7 +14,7 @@ class TestAutomationMQTT(unittest.TestCase):
"""Test the event automation."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_component(self.hass, 'group')
mock_mqtt_component(self.hass)
@@ -22,7 +22,7 @@ class TestAutomationMQTT(unittest.TestCase):
@callback
def record_call(service):
"""Helper to record calls."""
"""Record calls."""
self.calls.append(service)
self.hass.services.register('test', 'automation', record_call)
@@ -18,14 +18,14 @@ class TestAutomationNumericState(unittest.TestCase):
"""Test the event automation."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_component(self.hass, 'group')
self.calls = []
@callback
def record_call(service):
"""Helper to record calls."""
"""Record calls."""
self.calls.append(service)
self.hass.services.register('test', 'automation', record_call)
+1 -1
View File
@@ -19,7 +19,7 @@ class TestAutomationState(unittest.TestCase):
"""Test the event automation."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_component(self.hass, 'group')
self.hass.states.set('test.entity', 'hello')
+1 -1
View File
@@ -19,7 +19,7 @@ class TestAutomationSun(unittest.TestCase):
"""Test the sun automation."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_component(self.hass, 'group')
setup_component(self.hass, sun.DOMAIN, {
+2 -2
View File
@@ -14,7 +14,7 @@ class TestAutomationTemplate(unittest.TestCase):
"""Test the event automation."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_component(self.hass, 'group')
self.hass.states.set('test.entity', 'hello')
@@ -22,7 +22,7 @@ class TestAutomationTemplate(unittest.TestCase):
@callback
def record_call(service):
"""Helper to record calls."""
"""Record calls."""
self.calls.append(service)
self.hass.services.register('test', 'automation', record_call)
+2 -2
View File
@@ -18,14 +18,14 @@ class TestAutomationTime(unittest.TestCase):
"""Test the event automation."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_component(self.hass, 'group')
self.calls = []
@callback
def record_call(service):
"""Helper to record calls."""
"""Record calls."""
self.calls.append(service)
self.hass.services.register('test', 'automation', record_call)
+2 -2
View File
@@ -13,7 +13,7 @@ class TestAutomationZone(unittest.TestCase):
"""Test the event automation."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_component(self.hass, 'group')
assert setup_component(self.hass, zone.DOMAIN, {
@@ -29,7 +29,7 @@ class TestAutomationZone(unittest.TestCase):
@callback
def record_call(service):
"""Helper to record calls."""
"""Record calls."""
self.calls.append(service)
self.hass.services.register('test', 'automation', record_call)
@@ -12,7 +12,7 @@ class TestCommandSensorBinarySensor(unittest.TestCase):
"""Test the Command line Binary sensor."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self):
@@ -11,7 +11,7 @@ class TestFFmpegNoiseSetup:
"""Test class for ffmpeg."""
def setup_method(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.config = {
@@ -29,7 +29,7 @@ class TestFFmpegNoiseSetup:
self.hass.stop()
def test_setup_component(self):
"""Setup ffmpeg component."""
"""Set up ffmpeg component."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor', self.config)
@@ -38,7 +38,7 @@ class TestFFmpegNoiseSetup:
@patch('haffmpeg.SensorNoise.open_sensor', return_value=mock_coro())
def test_setup_component_start(self, mock_start):
"""Setup ffmpeg component."""
"""Set up ffmpeg component."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor', self.config)
@@ -53,7 +53,7 @@ class TestFFmpegNoiseSetup:
@patch('haffmpeg.SensorNoise')
def test_setup_component_start_callback(self, mock_ffmpeg):
"""Setup ffmpeg component."""
"""Set up ffmpeg component."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor', self.config)
@@ -76,7 +76,7 @@ class TestFFmpegMotionSetup:
"""Test class for ffmpeg."""
def setup_method(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.config = {
@@ -94,7 +94,7 @@ class TestFFmpegMotionSetup:
self.hass.stop()
def test_setup_component(self):
"""Setup ffmpeg component."""
"""Set up ffmpeg component."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor', self.config)
@@ -103,7 +103,7 @@ class TestFFmpegMotionSetup:
@patch('haffmpeg.SensorMotion.open_sensor', return_value=mock_coro())
def test_setup_component_start(self, mock_start):
"""Setup ffmpeg component."""
"""Set up ffmpeg component."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor', self.config)
@@ -118,7 +118,7 @@ class TestFFmpegMotionSetup:
@patch('haffmpeg.SensorMotion')
def test_setup_component_start_callback(self, mock_ffmpeg):
"""Setup ffmpeg component."""
"""Set up ffmpeg component."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor', self.config)
+1 -1
View File
@@ -16,7 +16,7 @@ class TestSensorMQTT(unittest.TestCase):
"""Test the MQTT sensor."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_mqtt_component(self.hass)
+1 -1
View File
@@ -21,7 +21,7 @@ class TestNX584SensorSetup(unittest.TestCase):
"""Test the NX584 sensor platform."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self._mock_client = mock.patch.object(nx584_client, 'Client')
self._mock_client.start()
+2 -2
View File
@@ -19,7 +19,7 @@ class TestRestBinarySensorSetup(unittest.TestCase):
"""Tests for setting up the REST binary sensor platform."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self):
@@ -121,7 +121,7 @@ class TestRestBinarySensor(unittest.TestCase):
"""Tests for REST binary sensor platform."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.rest = Mock('RestData')
self.rest.update = Mock('RestData.update',
+1 -1
View File
@@ -13,7 +13,7 @@ class TestTCPBinarySensor(unittest.TestCase):
"""Test the TCP Binary Sensor."""
def setup_method(self, method):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def teardown_method(self, method):
@@ -23,7 +23,7 @@ class TestBinarySensorTemplate(unittest.TestCase):
# pylint: disable=invalid-name
def setup_method(self, method):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def teardown_method(self, method):
@@ -16,7 +16,7 @@ class TestWorkdaySetup:
"""Test class for workday sensor."""
def setup_method(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
# Set valid default config for test
@@ -97,7 +97,7 @@ class TestWorkdaySetup:
self.hass.stop()
def test_setup_component_province(self):
"""Setup workday component."""
"""Set up workday component."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor',
self.config_province)
@@ -145,7 +145,7 @@ class TestWorkdaySetup:
assert entity.state == 'off'
def test_setup_component_noprovince(self):
"""Setup workday component."""
"""Set up workday component."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor',
self.config_noprovince)
@@ -191,7 +191,7 @@ class TestWorkdaySetup:
assert entity.state == 'on'
def test_setup_component_invalidprovince(self):
"""Setup workday component."""
"""Set up workday component."""
with assert_setup_component(1, 'binary_sensor'):
setup_component(self.hass, 'binary_sensor',
self.config_invalidprovince)
+1 -1
View File
@@ -25,7 +25,7 @@ class TestComponentsGoogleCalendar(unittest.TestCase):
# pylint: disable=invalid-name
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.http = Mock()
+45
View File
@@ -1,5 +1,6 @@
"""The tests for generic camera component."""
import asyncio
from unittest import mock
from homeassistant.setup import async_setup_component
@@ -32,6 +33,50 @@ def test_fetching_url(aioclient_mock, hass, aiohttp_client):
assert aioclient_mock.call_count == 2
@asyncio.coroutine
def test_fetching_without_verify_ssl(aioclient_mock, hass, aiohttp_client):
"""Test that it fetches the given url when ssl verify is off."""
aioclient_mock.get('https://example.com', text='hello world')
yield from async_setup_component(hass, 'camera', {
'camera': {
'name': 'config_test',
'platform': 'generic',
'still_image_url': 'https://example.com',
'username': 'user',
'password': 'pass',
'verify_ssl': 'false',
}})
client = yield from aiohttp_client(hass.http.app)
resp = yield from client.get('/api/camera_proxy/camera.config_test')
assert resp.status == 200
@asyncio.coroutine
def test_fetching_url_with_verify_ssl(aioclient_mock, hass, aiohttp_client):
"""Test that it fetches the given url when ssl verify is explicitly on."""
aioclient_mock.get('https://example.com', text='hello world')
yield from async_setup_component(hass, 'camera', {
'camera': {
'name': 'config_test',
'platform': 'generic',
'still_image_url': 'https://example.com',
'username': 'user',
'password': 'pass',
'verify_ssl': 'true',
}})
client = yield from aiohttp_client(hass.http.app)
resp = yield from client.get('/api/camera_proxy/camera.config_test')
assert resp.status == 200
@asyncio.coroutine
def test_limit_refetch(aioclient_mock, hass, aiohttp_client):
"""Test that it fetches the given url."""
+3 -3
View File
@@ -34,7 +34,7 @@ class TestSetupCamera:
"""Test class for setup camera."""
def setup_method(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def teardown_method(self):
@@ -42,7 +42,7 @@ class TestSetupCamera:
self.hass.stop()
def test_setup_component(self):
"""Setup demo platform on camera component."""
"""Set up demo platform on camera component."""
config = {
camera.DOMAIN: {
'platform': 'demo'
@@ -57,7 +57,7 @@ class TestGetImage:
"""Test class for camera."""
def setup_method(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
setup_component(
+2 -2
View File
@@ -30,7 +30,7 @@ async def test_bad_posting(aioclient_mock, hass, aiohttp_client):
assert resp.status == 400
async def test_posting_url(aioclient_mock, hass, aiohttp_client):
async def test_posting_url(hass, aiohttp_client):
"""Test that posting to api endpoint works."""
await async_setup_component(hass, 'camera', {
'camera': {
@@ -38,7 +38,7 @@ async def test_posting_url(aioclient_mock, hass, aiohttp_client):
'name': 'config_test',
}})
client = await async_setup_auth(hass, aiohttp_client)
client = await aiohttp_client(hass.http.app)
files = {'image': io.BytesIO(b'fake')}
# initial state
+4 -4
View File
@@ -17,7 +17,7 @@ class TestUVCSetup(unittest.TestCase):
"""Test the UVC camera platform."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self):
@@ -134,7 +134,7 @@ class TestUVCSetup(unittest.TestCase):
@mock.patch.object(uvc, 'UnifiVideoCamera')
@mock.patch('uvcclient.nvr.UVCRemote')
def setup_nvr_errors_during_indexing(self, error, mock_remote, mock_uvc):
"""Setup test for NVR errors during indexing."""
"""Set up test for NVR errors during indexing."""
config = {
'platform': 'uvc',
'nvr': 'foo',
@@ -163,7 +163,7 @@ class TestUVCSetup(unittest.TestCase):
@mock.patch('uvcclient.nvr.UVCRemote.__init__')
def setup_nvr_errors_during_initialization(self, error, mock_remote,
mock_uvc):
"""Setup test for NVR errors during initialization."""
"""Set up test for NVR errors during initialization."""
config = {
'platform': 'uvc',
'nvr': 'foo',
@@ -195,7 +195,7 @@ class TestUVC(unittest.TestCase):
"""Test class for UVC."""
def setup_method(self, method):
"""Setup the mock camera."""
"""Set up the mock camera."""
self.nvr = mock.MagicMock()
self.uuid = 'uuid'
self.name = 'name'
+1 -1
View File
@@ -19,7 +19,7 @@ class TestDemoClimate(unittest.TestCase):
"""Test the demo climate hvac."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.config.units = METRIC_SYSTEM
self.assertTrue(setup_component(self.hass, climate.DOMAIN, {
@@ -9,7 +9,6 @@ import homeassistant.core as ha
from homeassistant.core import callback, CoreState, State
from homeassistant.setup import setup_component, async_setup_component
from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_ON,
@@ -42,7 +41,7 @@ class TestSetupClimateGenericThermostat(unittest.TestCase):
"""Test the Generic thermostat with custom config."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self): # pylint: disable=invalid-name
@@ -79,7 +78,7 @@ class TestGenericThermostatHeaterSwitching(unittest.TestCase):
"""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.config.units = METRIC_SYSTEM
self.assertTrue(run_coroutine_threadsafe(
@@ -141,18 +140,16 @@ class TestGenericThermostatHeaterSwitching(unittest.TestCase):
self.assertEqual(STATE_ON,
self.hass.states.get(heater_switch).state)
def _setup_sensor(self, temp, unit=TEMP_CELSIUS):
"""Setup the test sensor."""
self.hass.states.set(ENT_SENSOR, temp, {
ATTR_UNIT_OF_MEASUREMENT: unit
})
def _setup_sensor(self, temp):
"""Set up the test sensor."""
self.hass.states.set(ENT_SENSOR, temp)
class TestClimateGenericThermostat(unittest.TestCase):
"""Test the Generic thermostat."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.config.units = METRIC_SYSTEM
assert setup_component(self.hass, climate.DOMAIN, {'climate': {
@@ -222,30 +219,15 @@ class TestClimateGenericThermostat(unittest.TestCase):
state = self.hass.states.get(ENTITY)
self.assertEqual(23, state.attributes.get('temperature'))
def test_sensor_bad_unit(self):
"""Test sensor that have bad unit."""
state = self.hass.states.get(ENTITY)
temp = state.attributes.get('current_temperature')
unit = state.attributes.get('unit_of_measurement')
self._setup_sensor(22.0, unit='bad_unit')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY)
self.assertEqual(unit, state.attributes.get('unit_of_measurement'))
self.assertEqual(temp, state.attributes.get('current_temperature'))
def test_sensor_bad_value(self):
"""Test sensor that have None as state."""
state = self.hass.states.get(ENTITY)
temp = state.attributes.get('current_temperature')
unit = state.attributes.get('unit_of_measurement')
self._setup_sensor(None)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY)
self.assertEqual(unit, state.attributes.get('unit_of_measurement'))
self.assertEqual(temp, state.attributes.get('current_temperature'))
def test_set_target_temp_heater_on(self):
@@ -367,14 +349,12 @@ class TestClimateGenericThermostat(unittest.TestCase):
self.assertEqual(SERVICE_TURN_ON, call.service)
self.assertEqual(ENT_SWITCH, call.data['entity_id'])
def _setup_sensor(self, temp, unit=TEMP_CELSIUS):
"""Setup the test sensor."""
self.hass.states.set(ENT_SENSOR, temp, {
ATTR_UNIT_OF_MEASUREMENT: unit
})
def _setup_sensor(self, temp):
"""Set up the test sensor."""
self.hass.states.set(ENT_SENSOR, temp)
def _setup_switch(self, is_on):
"""Setup the test switch."""
"""Set up the test switch."""
self.hass.states.set(ENT_SWITCH, STATE_ON if is_on else STATE_OFF)
self.calls = []
@@ -391,7 +371,7 @@ class TestClimateGenericThermostatACMode(unittest.TestCase):
"""Test the Generic thermostat."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.config.temperature_unit = TEMP_CELSIUS
assert setup_component(self.hass, climate.DOMAIN, {'climate': {
@@ -532,14 +512,12 @@ class TestClimateGenericThermostatACMode(unittest.TestCase):
self.hass.block_till_done()
self.assertEqual(0, len(self.calls))
def _setup_sensor(self, temp, unit=TEMP_CELSIUS):
"""Setup the test sensor."""
self.hass.states.set(ENT_SENSOR, temp, {
ATTR_UNIT_OF_MEASUREMENT: unit
})
def _setup_sensor(self, temp):
"""Set up the test sensor."""
self.hass.states.set(ENT_SENSOR, temp)
def _setup_switch(self, is_on):
"""Setup the test switch."""
"""Set up the test switch."""
self.hass.states.set(ENT_SWITCH, STATE_ON if is_on else STATE_OFF)
self.calls = []
@@ -556,7 +534,7 @@ class TestClimateGenericThermostatACModeMinCycle(unittest.TestCase):
"""Test the Generic Thermostat."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.config.temperature_unit = TEMP_CELSIUS
assert setup_component(self.hass, climate.DOMAIN, {'climate': {
@@ -626,14 +604,12 @@ class TestClimateGenericThermostatACModeMinCycle(unittest.TestCase):
self.assertEqual(SERVICE_TURN_OFF, call.service)
self.assertEqual(ENT_SWITCH, call.data['entity_id'])
def _setup_sensor(self, temp, unit=TEMP_CELSIUS):
"""Setup the test sensor."""
self.hass.states.set(ENT_SENSOR, temp, {
ATTR_UNIT_OF_MEASUREMENT: unit
})
def _setup_sensor(self, temp):
"""Set up the test sensor."""
self.hass.states.set(ENT_SENSOR, temp)
def _setup_switch(self, is_on):
"""Setup the test switch."""
"""Set up the test switch."""
self.hass.states.set(ENT_SWITCH, STATE_ON if is_on else STATE_OFF)
self.calls = []
@@ -650,7 +626,7 @@ class TestClimateGenericThermostatMinCycle(unittest.TestCase):
"""Test the Generic thermostat."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.config.temperature_unit = TEMP_CELSIUS
assert setup_component(self.hass, climate.DOMAIN, {'climate': {
@@ -719,14 +695,12 @@ class TestClimateGenericThermostatMinCycle(unittest.TestCase):
self.assertEqual(SERVICE_TURN_OFF, call.service)
self.assertEqual(ENT_SWITCH, call.data['entity_id'])
def _setup_sensor(self, temp, unit=TEMP_CELSIUS):
"""Setup the test sensor."""
self.hass.states.set(ENT_SENSOR, temp, {
ATTR_UNIT_OF_MEASUREMENT: unit
})
def _setup_sensor(self, temp):
"""Set up the test sensor."""
self.hass.states.set(ENT_SENSOR, temp)
def _setup_switch(self, is_on):
"""Setup the test switch."""
"""Set up the test switch."""
self.hass.states.set(ENT_SWITCH, STATE_ON if is_on else STATE_OFF)
self.calls = []
@@ -743,7 +717,7 @@ class TestClimateGenericThermostatACKeepAlive(unittest.TestCase):
"""Test the Generic Thermostat."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.config.temperature_unit = TEMP_CELSIUS
assert setup_component(self.hass, climate.DOMAIN, {'climate': {
@@ -812,14 +786,12 @@ class TestClimateGenericThermostatACKeepAlive(unittest.TestCase):
"""Send a time changed event."""
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: now})
def _setup_sensor(self, temp, unit=TEMP_CELSIUS):
"""Setup the test sensor."""
self.hass.states.set(ENT_SENSOR, temp, {
ATTR_UNIT_OF_MEASUREMENT: unit
})
def _setup_sensor(self, temp):
"""Set up the test sensor."""
self.hass.states.set(ENT_SENSOR, temp)
def _setup_switch(self, is_on):
"""Setup the test switch."""
"""Set up the test switch."""
self.hass.states.set(ENT_SWITCH, STATE_ON if is_on else STATE_OFF)
self.calls = []
@@ -836,7 +808,7 @@ class TestClimateGenericThermostatKeepAlive(unittest.TestCase):
"""Test the Generic Thermostat."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.config.temperature_unit = TEMP_CELSIUS
assert setup_component(self.hass, climate.DOMAIN, {'climate': {
@@ -904,14 +876,12 @@ class TestClimateGenericThermostatKeepAlive(unittest.TestCase):
"""Send a time changed event."""
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: now})
def _setup_sensor(self, temp, unit=TEMP_CELSIUS):
"""Setup the test sensor."""
self.hass.states.set(ENT_SENSOR, temp, {
ATTR_UNIT_OF_MEASUREMENT: unit
})
def _setup_sensor(self, temp):
"""Set up the test sensor."""
self.hass.states.set(ENT_SENSOR, temp)
def _setup_switch(self, is_on):
"""Setup the test switch."""
"""Set up the test switch."""
self.hass.states.set(ENT_SWITCH, STATE_ON if is_on else STATE_OFF)
self.calls = []
@@ -999,7 +969,7 @@ class TestClimateGenericThermostatRestoreState(unittest.TestCase):
"""Test generic thermostat when restore state from HA startup."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.config.temperature_unit = TEMP_CELSIUS
@@ -1047,14 +1017,12 @@ class TestClimateGenericThermostatRestoreState(unittest.TestCase):
'ac_mode': True
}})
def _setup_sensor(self, temp, unit=TEMP_CELSIUS):
"""Setup the test sensor."""
self.hass.states.set(ENT_SENSOR, temp, {
ATTR_UNIT_OF_MEASUREMENT: unit
})
def _setup_sensor(self, temp):
"""Set up the test sensor."""
self.hass.states.set(ENT_SENSOR, temp)
def _setup_switch(self, is_on):
"""Setup the test switch."""
"""Set up the test switch."""
self.hass.states.set(ENT_SWITCH, STATE_ON if is_on else STATE_OFF)
self.calls = []
+1 -1
View File
@@ -35,7 +35,7 @@ class TestMQTTClimate(unittest.TestCase):
"""Test the mqtt climate hvac."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_publish = mock_mqtt_component(self.hass)
self.hass.config.units = METRIC_SYSTEM
+22 -1
View File
@@ -4,7 +4,7 @@ import asyncio
import unittest
import logging
from homeassistant.core import CoreState, State
from homeassistant.core import CoreState, State, Context
from homeassistant.setup import setup_component, async_setup_component
from homeassistant.components.counter import (
DOMAIN, decrement, increment, reset, CONF_INITIAL, CONF_STEP, CONF_NAME,
@@ -202,3 +202,24 @@ def test_no_initial_state_and_no_restore_state(hass):
state = hass.states.get('counter.test1')
assert state
assert int(state.state) == 0
async def test_counter_context(hass):
"""Test that counter context works."""
assert await async_setup_component(hass, 'counter', {
'counter': {
'test': {}
}
})
state = hass.states.get('counter.test')
assert state is not None
await hass.services.async_call('counter', 'increment', {
'entity_id': state.entity_id,
}, True, Context(user_id='abcd'))
state2 = hass.states.get('counter.test')
assert state2 is not None
assert state.state != state2.state
assert state2.context.user_id == 'abcd'
+1 -1
View File
@@ -17,7 +17,7 @@ class TestCommandCover(unittest.TestCase):
"""Test the cover command line platform."""
def setup_method(self, method):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.rs = cmd_rs.CommandCover(self.hass, 'foo',
'command_open', 'command_close',
+1 -1
View File
@@ -14,7 +14,7 @@ class TestCoverDemo(unittest.TestCase):
"""Test the Demo cover."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.assertTrue(setup_component(self.hass, cover.DOMAIN, {'cover': {
'platform': 'demo',
+1 -1
View File
@@ -35,7 +35,7 @@ class TestMultiCover(unittest.TestCase):
"""Test the group cover platform."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self):
+1 -1
View File
@@ -15,7 +15,7 @@ class TestCoverMQTT(unittest.TestCase):
"""Test the MQTT cover."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_publish = mock_mqtt_component(self.hass)
+1 -1
View File
@@ -14,7 +14,7 @@ class TestCoverRfxtrx(unittest.TestCase):
"""Test the Rfxtrx cover platform."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_component('rfxtrx')
@@ -116,7 +116,7 @@ WAKE_DEVICES_NO_IP = {
def setup_module():
"""Setup the test module."""
"""Set up the test module."""
global FAKEFILE
FAKEFILE = get_test_config_dir('fake_file')
with open(FAKEFILE, 'w') as out:
@@ -138,7 +138,7 @@ class TestComponentsDeviceTrackerASUSWRT(unittest.TestCase):
hass = None
def setup_method(self, _):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_component(self.hass, 'zone')
@@ -500,7 +500,7 @@ class TestSshConnection(unittest.TestCase):
"""Testing SshConnection."""
def setUp(self):
"""Setup test env."""
"""Set up test env."""
self.connection = SshConnection(
'fake', 'fake', 'fake', 'fake', 'fake')
self.connection._connected = True
@@ -544,7 +544,7 @@ class TestTelnetConnection(unittest.TestCase):
"""Testing TelnetConnection."""
def setUp(self):
"""Setup test env."""
"""Set up test env."""
self.connection = TelnetConnection(
'fake', 'fake', 'fake', 'fake')
self.connection._connected = True
@@ -41,7 +41,7 @@ class TestDdwrt(unittest.TestCase):
super().run(result)
def setup_method(self, _):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_component(self.hass, 'zone')
@@ -220,7 +220,7 @@ class TestDdwrt(unittest.TestCase):
with requests_mock.Mocker() as mock_request:
mock_request.register_uri(
'GET', r'http://%s/Status_Wireless.live.asp' % TEST_HOST,
# First request has to work to setup connection
# First request has to work to set up connection
[{'text': load_fixture('Ddwrt_Status_Wireless.txt')},
# Second request to get active devices fails
{'text': None}])
@@ -122,7 +122,7 @@ def geofency_client(loop, hass, aiohttp_client):
@pytest.fixture(autouse=True)
def setup_zones(loop, hass):
"""Setup Zone config in HA."""
"""Set up Zone config in HA."""
assert loop.run_until_complete(async_setup_component(
hass, zone.DOMAIN, {
'zone': {
+3 -3
View File
@@ -20,7 +20,7 @@ from homeassistant.const import (
STATE_HOME, STATE_NOT_HOME, CONF_PLATFORM, ATTR_ICON)
import homeassistant.components.device_tracker as device_tracker
from homeassistant.exceptions import HomeAssistantError
from homeassistant.remote import JSONEncoder
from homeassistant.helpers.json import JSONEncoder
from tests.common import (
get_test_home_assistant, fire_time_changed,
@@ -39,7 +39,7 @@ class TestComponentsDeviceTracker(unittest.TestCase):
# pylint: disable=invalid-name
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.yaml_devices = self.hass.config.path(device_tracker.YAML_DEVICES)
@@ -323,7 +323,7 @@ class TestComponentsDeviceTracker(unittest.TestCase):
@callback
def listener(event):
"""Helper method that will verify our event got called."""
"""Record that our event got called."""
test_events.append(event)
self.hass.bus.listen("device_tracker_new_device", listener)
@@ -11,7 +11,7 @@ from homeassistant.components.device_tracker.locative import URL
def _url(data=None):
"""Helper method to generate URLs."""
"""Generate URL."""
data = data or {}
data = "&".join(["{}={}".format(name, value) for
name, value in data.items()])
+1 -1
View File
@@ -19,7 +19,7 @@ class TestComponentsDeviceTrackerMQTT(unittest.TestCase):
"""Test MQTT device tracker platform."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_mqtt_component(self.hass)
@@ -29,7 +29,7 @@ class TestComponentsDeviceTrackerJSONMQTT(unittest.TestCase):
"""Test JSON MQTT device tracker platform."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_mqtt_component(self.hass)
@@ -327,7 +327,7 @@ class TestDeviceTrackerOwnTracks(BaseMQTT):
# pylint: disable=invalid-name
def setup_method(self, _):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_mqtt_component(self.hass)
mock_component(self.hass, 'group')
@@ -1316,7 +1316,7 @@ class TestDeviceTrackerOwnTrackConfigs(BaseMQTT):
# pylint: disable=invalid-name
def setup_method(self, method):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_mqtt_component(self.hass)
mock_component(self.hass, 'group')
@@ -16,7 +16,7 @@ class TestTplink4DeviceScanner(unittest.TestCase):
"""Tests for the Tplink4DeviceScanner class."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self): # pylint: disable=invalid-name
@@ -31,7 +31,7 @@ class TestComponentsDeviceTrackerUnifiDirect(unittest.TestCase):
'unifi_direct.UnifiDeviceScanner'
def setup_method(self, _):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_component(self.hass, 'zone')
@@ -37,7 +37,7 @@ class TestUPCConnect:
"""Tests for the Ddwrt device tracker platform."""
def setup_method(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_component(self.hass, 'zone')
mock_component(self.hass, 'group')
@@ -52,7 +52,7 @@ class TestUPCConnect:
'UPCDeviceScanner.async_scan_devices',
return_value=async_scan_devices_mock)
def test_setup_platform(self, scan_mock, aioclient_mock):
"""Setup a platform."""
"""Set up a platform."""
aioclient_mock.get(
"http://{}/common_page/login.html".format(self.host),
cookies={'sessionToken': '654321'}
@@ -74,7 +74,7 @@ class TestUPCConnect:
@patch('homeassistant.components.device_tracker._LOGGER.error')
def test_setup_platform_timeout_webservice(self, mock_error,
aioclient_mock):
"""Setup a platform with api timeout."""
"""Set up a platform with api timeout."""
aioclient_mock.get(
"http://{}/common_page/login.html".format(self.host),
cookies={'sessionToken': '654321'},
@@ -97,7 +97,7 @@ class TestUPCConnect:
@patch('homeassistant.components.device_tracker._LOGGER.error')
def test_setup_platform_timeout_loginpage(self, mock_error,
aioclient_mock):
"""Setup a platform with timeout on loginpage."""
"""Set up a platform with timeout on loginpage."""
aioclient_mock.get(
"http://{}/common_page/login.html".format(self.host),
exc=asyncio.TimeoutError()
@@ -120,7 +120,7 @@ class TestUPCConnect:
str(mock_error.call_args_list[-1])
def test_scan_devices(self, aioclient_mock):
"""Setup a upc platform and scan device."""
"""Set up a upc platform and scan device."""
aioclient_mock.get(
"http://{}/common_page/login.html".format(self.host),
cookies={'sessionToken': '654321'}
@@ -156,7 +156,7 @@ class TestUPCConnect:
'70:EE:50:27:A1:38']
def test_scan_devices_without_session(self, aioclient_mock):
"""Setup a upc platform and scan device with no token."""
"""Set up a upc platform and scan device with no token."""
aioclient_mock.get(
"http://{}/common_page/login.html".format(self.host),
cookies={'sessionToken': '654321'}
@@ -197,7 +197,7 @@ class TestUPCConnect:
'70:EE:50:27:A1:38']
def test_scan_devices_without_session_wrong_re(self, aioclient_mock):
"""Setup a upc platform and scan device with no token and wrong."""
"""Set up a upc platform and scan device with no token and wrong."""
aioclient_mock.get(
"http://{}/common_page/login.html".format(self.host),
cookies={'sessionToken': '654321'}
@@ -237,7 +237,7 @@ class TestUPCConnect:
assert mac_list == []
def test_scan_devices_parse_error(self, aioclient_mock):
"""Setup a upc platform and scan device with parse error."""
"""Set up a upc platform and scan device with parse error."""
aioclient_mock.get(
"http://{}/common_page/login.html".format(self.host),
cookies={'sessionToken': '654321'}
@@ -26,7 +26,7 @@ JSON_HEADERS = {CONTENT_TYPE: const.CONTENT_TYPE_JSON}
@pytest.fixture
def hass_hue(loop, hass):
"""Setup a Home Assistant instance for these tests."""
"""Set up a Home Assistant instance for these tests."""
# We need to do this to get access to homeassistant/turn_(on,off)
loop.run_until_complete(
core_components.async_setup(hass, {core.DOMAIN: {}}))
+1 -1
View File
@@ -50,7 +50,7 @@ class TestEmulatedHue(unittest.TestCase):
@classmethod
def setUpClass(cls):
"""Setup the class."""
"""Set up the class."""
cls.hass = hass = get_test_home_assistant()
# We need to do this to get access to homeassistant/turn_(on,off)
+1 -1
View File
@@ -15,7 +15,7 @@ class TestDemoFan(unittest.TestCase):
"""Test the fan demo platform."""
def get_entity(self):
"""Helper method to get the fan entity."""
"""Get the fan entity."""
return self.hass.states.get(FAN_ENTITY_ID)
def setUp(self):
+1 -1
View File
@@ -68,7 +68,7 @@ class DysonTest(unittest.TestCase):
"""Dyson Sensor component test class."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self): # pylint: disable=invalid-name
+1 -1
View File
@@ -13,7 +13,7 @@ class TestMqttFan(unittest.TestCase):
"""Test the MQTT fan platform."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_publish = mock_mqtt_component(self.hass)
+1 -1
View File
@@ -33,7 +33,7 @@ class TestTemplateFan:
# pylint: disable=invalid-name
def setup_method(self, method):
"""Setup."""
"""Set up."""
self.hass = get_test_home_assistant()
self.calls = []
@@ -232,10 +232,10 @@ def test_query_climate_request(hass_fixture, assistant_client):
def test_query_climate_request_f(hass_fixture, assistant_client):
"""Test a query request."""
# Mock demo devices as fahrenheit to see if we convert to celsius
hass_fixture.config.units.temperature_unit = const.TEMP_FAHRENHEIT
for entity_id in ('climate.hvac', 'climate.heatpump', 'climate.ecobee'):
state = hass_fixture.states.get(entity_id)
attr = dict(state.attributes)
attr[const.ATTR_UNIT_OF_MEASUREMENT] = const.TEMP_FAHRENHEIT
hass_fixture.states.async_set(entity_id, state.state, attr)
reqid = '5711642932632160984'
@@ -282,6 +282,7 @@ def test_query_climate_request_f(hass_fixture, assistant_client):
'thermostatMode': 'cool',
'thermostatHumidityAmbient': 54,
}
hass_fixture.config.units.temperature_unit = const.TEMP_CELSIUS
@asyncio.coroutine
+62 -61
View File
@@ -3,7 +3,7 @@ import pytest
from homeassistant.const import (
STATE_ON, STATE_OFF, ATTR_ENTITY_ID, SERVICE_TURN_ON, SERVICE_TURN_OFF,
ATTR_UNIT_OF_MEASUREMENT, TEMP_CELSIUS, TEMP_FAHRENHEIT)
TEMP_CELSIUS, TEMP_FAHRENHEIT)
from homeassistant.core import State, DOMAIN as HA_DOMAIN
from homeassistant.components import (
climate,
@@ -27,7 +27,7 @@ async def test_brightness_light(hass):
assert trait.BrightnessTrait.supported(light.DOMAIN,
light.SUPPORT_BRIGHTNESS)
trt = trait.BrightnessTrait(State('light.bla', light.STATE_ON, {
trt = trait.BrightnessTrait(hass, State('light.bla', light.STATE_ON, {
light.ATTR_BRIGHTNESS: 243
}))
@@ -38,7 +38,7 @@ async def test_brightness_light(hass):
}
calls = async_mock_service(hass, light.DOMAIN, light.SERVICE_TURN_ON)
await trt.execute(hass, trait.COMMAND_BRIGHTNESS_ABSOLUTE, {
await trt.execute(trait.COMMAND_BRIGHTNESS_ABSOLUTE, {
'brightness': 50
})
assert len(calls) == 1
@@ -53,7 +53,7 @@ async def test_brightness_cover(hass):
assert trait.BrightnessTrait.supported(cover.DOMAIN,
cover.SUPPORT_SET_POSITION)
trt = trait.BrightnessTrait(State('cover.bla', cover.STATE_OPEN, {
trt = trait.BrightnessTrait(hass, State('cover.bla', cover.STATE_OPEN, {
cover.ATTR_CURRENT_POSITION: 75
}))
@@ -65,7 +65,7 @@ async def test_brightness_cover(hass):
calls = async_mock_service(
hass, cover.DOMAIN, cover.SERVICE_SET_COVER_POSITION)
await trt.execute(hass, trait.COMMAND_BRIGHTNESS_ABSOLUTE, {
await trt.execute(trait.COMMAND_BRIGHTNESS_ABSOLUTE, {
'brightness': 50
})
assert len(calls) == 1
@@ -80,7 +80,7 @@ async def test_brightness_media_player(hass):
assert trait.BrightnessTrait.supported(media_player.DOMAIN,
media_player.SUPPORT_VOLUME_SET)
trt = trait.BrightnessTrait(State(
trt = trait.BrightnessTrait(hass, State(
'media_player.bla', media_player.STATE_PLAYING, {
media_player.ATTR_MEDIA_VOLUME_LEVEL: .3
}))
@@ -93,7 +93,7 @@ async def test_brightness_media_player(hass):
calls = async_mock_service(
hass, media_player.DOMAIN, media_player.SERVICE_VOLUME_SET)
await trt.execute(hass, trait.COMMAND_BRIGHTNESS_ABSOLUTE, {
await trt.execute(trait.COMMAND_BRIGHTNESS_ABSOLUTE, {
'brightness': 60
})
assert len(calls) == 1
@@ -107,7 +107,7 @@ async def test_onoff_group(hass):
"""Test OnOff trait support for group domain."""
assert trait.OnOffTrait.supported(media_player.DOMAIN, 0)
trt_on = trait.OnOffTrait(State('group.bla', STATE_ON))
trt_on = trait.OnOffTrait(hass, State('group.bla', STATE_ON))
assert trt_on.sync_attributes() == {}
@@ -115,13 +115,13 @@ async def test_onoff_group(hass):
'on': True
}
trt_off = trait.OnOffTrait(State('group.bla', STATE_OFF))
trt_off = trait.OnOffTrait(hass, State('group.bla', STATE_OFF))
assert trt_off.query_attributes() == {
'on': False
}
on_calls = async_mock_service(hass, HA_DOMAIN, SERVICE_TURN_ON)
await trt_on.execute(hass, trait.COMMAND_ONOFF, {
await trt_on.execute(trait.COMMAND_ONOFF, {
'on': True
})
assert len(on_calls) == 1
@@ -130,7 +130,7 @@ async def test_onoff_group(hass):
}
off_calls = async_mock_service(hass, HA_DOMAIN, SERVICE_TURN_OFF)
await trt_on.execute(hass, trait.COMMAND_ONOFF, {
await trt_on.execute(trait.COMMAND_ONOFF, {
'on': False
})
assert len(off_calls) == 1
@@ -143,7 +143,7 @@ async def test_onoff_input_boolean(hass):
"""Test OnOff trait support for input_boolean domain."""
assert trait.OnOffTrait.supported(media_player.DOMAIN, 0)
trt_on = trait.OnOffTrait(State('input_boolean.bla', STATE_ON))
trt_on = trait.OnOffTrait(hass, State('input_boolean.bla', STATE_ON))
assert trt_on.sync_attributes() == {}
@@ -151,13 +151,13 @@ async def test_onoff_input_boolean(hass):
'on': True
}
trt_off = trait.OnOffTrait(State('input_boolean.bla', STATE_OFF))
trt_off = trait.OnOffTrait(hass, State('input_boolean.bla', STATE_OFF))
assert trt_off.query_attributes() == {
'on': False
}
on_calls = async_mock_service(hass, input_boolean.DOMAIN, SERVICE_TURN_ON)
await trt_on.execute(hass, trait.COMMAND_ONOFF, {
await trt_on.execute(trait.COMMAND_ONOFF, {
'on': True
})
assert len(on_calls) == 1
@@ -167,7 +167,7 @@ async def test_onoff_input_boolean(hass):
off_calls = async_mock_service(hass, input_boolean.DOMAIN,
SERVICE_TURN_OFF)
await trt_on.execute(hass, trait.COMMAND_ONOFF, {
await trt_on.execute(trait.COMMAND_ONOFF, {
'on': False
})
assert len(off_calls) == 1
@@ -180,7 +180,7 @@ async def test_onoff_switch(hass):
"""Test OnOff trait support for switch domain."""
assert trait.OnOffTrait.supported(media_player.DOMAIN, 0)
trt_on = trait.OnOffTrait(State('switch.bla', STATE_ON))
trt_on = trait.OnOffTrait(hass, State('switch.bla', STATE_ON))
assert trt_on.sync_attributes() == {}
@@ -188,13 +188,13 @@ async def test_onoff_switch(hass):
'on': True
}
trt_off = trait.OnOffTrait(State('switch.bla', STATE_OFF))
trt_off = trait.OnOffTrait(hass, State('switch.bla', STATE_OFF))
assert trt_off.query_attributes() == {
'on': False
}
on_calls = async_mock_service(hass, switch.DOMAIN, SERVICE_TURN_ON)
await trt_on.execute(hass, trait.COMMAND_ONOFF, {
await trt_on.execute(trait.COMMAND_ONOFF, {
'on': True
})
assert len(on_calls) == 1
@@ -203,7 +203,7 @@ async def test_onoff_switch(hass):
}
off_calls = async_mock_service(hass, switch.DOMAIN, SERVICE_TURN_OFF)
await trt_on.execute(hass, trait.COMMAND_ONOFF, {
await trt_on.execute(trait.COMMAND_ONOFF, {
'on': False
})
assert len(off_calls) == 1
@@ -216,7 +216,7 @@ async def test_onoff_fan(hass):
"""Test OnOff trait support for fan domain."""
assert trait.OnOffTrait.supported(media_player.DOMAIN, 0)
trt_on = trait.OnOffTrait(State('fan.bla', STATE_ON))
trt_on = trait.OnOffTrait(hass, State('fan.bla', STATE_ON))
assert trt_on.sync_attributes() == {}
@@ -224,13 +224,13 @@ async def test_onoff_fan(hass):
'on': True
}
trt_off = trait.OnOffTrait(State('fan.bla', STATE_OFF))
trt_off = trait.OnOffTrait(hass, State('fan.bla', STATE_OFF))
assert trt_off.query_attributes() == {
'on': False
}
on_calls = async_mock_service(hass, fan.DOMAIN, SERVICE_TURN_ON)
await trt_on.execute(hass, trait.COMMAND_ONOFF, {
await trt_on.execute(trait.COMMAND_ONOFF, {
'on': True
})
assert len(on_calls) == 1
@@ -239,7 +239,7 @@ async def test_onoff_fan(hass):
}
off_calls = async_mock_service(hass, fan.DOMAIN, SERVICE_TURN_OFF)
await trt_on.execute(hass, trait.COMMAND_ONOFF, {
await trt_on.execute(trait.COMMAND_ONOFF, {
'on': False
})
assert len(off_calls) == 1
@@ -252,7 +252,7 @@ async def test_onoff_light(hass):
"""Test OnOff trait support for light domain."""
assert trait.OnOffTrait.supported(media_player.DOMAIN, 0)
trt_on = trait.OnOffTrait(State('light.bla', STATE_ON))
trt_on = trait.OnOffTrait(hass, State('light.bla', STATE_ON))
assert trt_on.sync_attributes() == {}
@@ -260,13 +260,13 @@ async def test_onoff_light(hass):
'on': True
}
trt_off = trait.OnOffTrait(State('light.bla', STATE_OFF))
trt_off = trait.OnOffTrait(hass, State('light.bla', STATE_OFF))
assert trt_off.query_attributes() == {
'on': False
}
on_calls = async_mock_service(hass, light.DOMAIN, SERVICE_TURN_ON)
await trt_on.execute(hass, trait.COMMAND_ONOFF, {
await trt_on.execute(trait.COMMAND_ONOFF, {
'on': True
})
assert len(on_calls) == 1
@@ -275,7 +275,7 @@ async def test_onoff_light(hass):
}
off_calls = async_mock_service(hass, light.DOMAIN, SERVICE_TURN_OFF)
await trt_on.execute(hass, trait.COMMAND_ONOFF, {
await trt_on.execute(trait.COMMAND_ONOFF, {
'on': False
})
assert len(off_calls) == 1
@@ -288,7 +288,7 @@ async def test_onoff_cover(hass):
"""Test OnOff trait support for cover domain."""
assert trait.OnOffTrait.supported(media_player.DOMAIN, 0)
trt_on = trait.OnOffTrait(State('cover.bla', cover.STATE_OPEN))
trt_on = trait.OnOffTrait(hass, State('cover.bla', cover.STATE_OPEN))
assert trt_on.sync_attributes() == {}
@@ -296,13 +296,13 @@ async def test_onoff_cover(hass):
'on': True
}
trt_off = trait.OnOffTrait(State('cover.bla', cover.STATE_CLOSED))
trt_off = trait.OnOffTrait(hass, State('cover.bla', cover.STATE_CLOSED))
assert trt_off.query_attributes() == {
'on': False
}
on_calls = async_mock_service(hass, cover.DOMAIN, cover.SERVICE_OPEN_COVER)
await trt_on.execute(hass, trait.COMMAND_ONOFF, {
await trt_on.execute(trait.COMMAND_ONOFF, {
'on': True
})
assert len(on_calls) == 1
@@ -312,7 +312,7 @@ async def test_onoff_cover(hass):
off_calls = async_mock_service(hass, cover.DOMAIN,
cover.SERVICE_CLOSE_COVER)
await trt_on.execute(hass, trait.COMMAND_ONOFF, {
await trt_on.execute(trait.COMMAND_ONOFF, {
'on': False
})
assert len(off_calls) == 1
@@ -325,7 +325,7 @@ async def test_onoff_media_player(hass):
"""Test OnOff trait support for media_player domain."""
assert trait.OnOffTrait.supported(media_player.DOMAIN, 0)
trt_on = trait.OnOffTrait(State('media_player.bla', STATE_ON))
trt_on = trait.OnOffTrait(hass, State('media_player.bla', STATE_ON))
assert trt_on.sync_attributes() == {}
@@ -333,13 +333,13 @@ async def test_onoff_media_player(hass):
'on': True
}
trt_off = trait.OnOffTrait(State('media_player.bla', STATE_OFF))
trt_off = trait.OnOffTrait(hass, State('media_player.bla', STATE_OFF))
assert trt_off.query_attributes() == {
'on': False
}
on_calls = async_mock_service(hass, media_player.DOMAIN, SERVICE_TURN_ON)
await trt_on.execute(hass, trait.COMMAND_ONOFF, {
await trt_on.execute(trait.COMMAND_ONOFF, {
'on': True
})
assert len(on_calls) == 1
@@ -348,7 +348,7 @@ async def test_onoff_media_player(hass):
}
off_calls = async_mock_service(hass, media_player.DOMAIN, SERVICE_TURN_OFF)
await trt_on.execute(hass, trait.COMMAND_ONOFF, {
await trt_on.execute(trait.COMMAND_ONOFF, {
'on': False
})
assert len(off_calls) == 1
@@ -363,7 +363,7 @@ async def test_color_spectrum_light(hass):
assert trait.ColorSpectrumTrait.supported(light.DOMAIN,
light.SUPPORT_COLOR)
trt = trait.ColorSpectrumTrait(State('light.bla', STATE_ON, {
trt = trait.ColorSpectrumTrait(hass, State('light.bla', STATE_ON, {
light.ATTR_HS_COLOR: (0, 94),
}))
@@ -389,7 +389,7 @@ async def test_color_spectrum_light(hass):
})
calls = async_mock_service(hass, light.DOMAIN, SERVICE_TURN_ON)
await trt.execute(hass, trait.COMMAND_COLOR_ABSOLUTE, {
await trt.execute(trait.COMMAND_COLOR_ABSOLUTE, {
'color': {
'spectrumRGB': 1052927
}
@@ -407,7 +407,7 @@ async def test_color_temperature_light(hass):
assert trait.ColorTemperatureTrait.supported(light.DOMAIN,
light.SUPPORT_COLOR_TEMP)
trt = trait.ColorTemperatureTrait(State('light.bla', STATE_ON, {
trt = trait.ColorTemperatureTrait(hass, State('light.bla', STATE_ON, {
light.ATTR_MIN_MIREDS: 200,
light.ATTR_COLOR_TEMP: 300,
light.ATTR_MAX_MIREDS: 500,
@@ -438,14 +438,14 @@ async def test_color_temperature_light(hass):
calls = async_mock_service(hass, light.DOMAIN, SERVICE_TURN_ON)
with pytest.raises(helpers.SmartHomeError) as err:
await trt.execute(hass, trait.COMMAND_COLOR_ABSOLUTE, {
await trt.execute(trait.COMMAND_COLOR_ABSOLUTE, {
'color': {
'temperature': 5555
}
})
assert err.value.code == const.ERR_VALUE_OUT_OF_RANGE
await trt.execute(hass, trait.COMMAND_COLOR_ABSOLUTE, {
await trt.execute(trait.COMMAND_COLOR_ABSOLUTE, {
'color': {
'temperature': 2857
}
@@ -461,13 +461,13 @@ async def test_scene_scene(hass):
"""Test Scene trait support for scene domain."""
assert trait.SceneTrait.supported(scene.DOMAIN, 0)
trt = trait.SceneTrait(State('scene.bla', scene.STATE))
trt = trait.SceneTrait(hass, State('scene.bla', scene.STATE))
assert trt.sync_attributes() == {}
assert trt.query_attributes() == {}
assert trt.can_execute(trait.COMMAND_ACTIVATE_SCENE, {})
calls = async_mock_service(hass, scene.DOMAIN, SERVICE_TURN_ON)
await trt.execute(hass, trait.COMMAND_ACTIVATE_SCENE, {})
await trt.execute(trait.COMMAND_ACTIVATE_SCENE, {})
assert len(calls) == 1
assert calls[0].data == {
ATTR_ENTITY_ID: 'scene.bla',
@@ -478,13 +478,13 @@ async def test_scene_script(hass):
"""Test Scene trait support for script domain."""
assert trait.SceneTrait.supported(script.DOMAIN, 0)
trt = trait.SceneTrait(State('script.bla', STATE_OFF))
trt = trait.SceneTrait(hass, State('script.bla', STATE_OFF))
assert trt.sync_attributes() == {}
assert trt.query_attributes() == {}
assert trt.can_execute(trait.COMMAND_ACTIVATE_SCENE, {})
calls = async_mock_service(hass, script.DOMAIN, SERVICE_TURN_ON)
await trt.execute(hass, trait.COMMAND_ACTIVATE_SCENE, {})
await trt.execute(trait.COMMAND_ACTIVATE_SCENE, {})
# We don't wait till script execution is done.
await hass.async_block_till_done()
@@ -501,7 +501,9 @@ async def test_temperature_setting_climate_range(hass):
assert trait.TemperatureSettingTrait.supported(
climate.DOMAIN, climate.SUPPORT_OPERATION_MODE)
trt = trait.TemperatureSettingTrait(State(
hass.config.units.temperature_unit = TEMP_FAHRENHEIT
trt = trait.TemperatureSettingTrait(hass, State(
'climate.bla', climate.STATE_AUTO, {
climate.ATTR_CURRENT_TEMPERATURE: 70,
climate.ATTR_CURRENT_HUMIDITY: 25,
@@ -515,8 +517,7 @@ async def test_temperature_setting_climate_range(hass):
climate.ATTR_TARGET_TEMP_HIGH: 75,
climate.ATTR_TARGET_TEMP_LOW: 65,
climate.ATTR_MIN_TEMP: 50,
climate.ATTR_MAX_TEMP: 80,
ATTR_UNIT_OF_MEASUREMENT: TEMP_FAHRENHEIT,
climate.ATTR_MAX_TEMP: 80
}))
assert trt.sync_attributes() == {
'availableThermostatModes': 'off,cool,heat,heatcool',
@@ -535,7 +536,7 @@ async def test_temperature_setting_climate_range(hass):
calls = async_mock_service(
hass, climate.DOMAIN, climate.SERVICE_SET_TEMPERATURE)
await trt.execute(hass, trait.COMMAND_THERMOSTAT_TEMPERATURE_SET_RANGE, {
await trt.execute(trait.COMMAND_THERMOSTAT_TEMPERATURE_SET_RANGE, {
'thermostatTemperatureSetpointHigh': 25,
'thermostatTemperatureSetpointLow': 20,
})
@@ -548,7 +549,7 @@ async def test_temperature_setting_climate_range(hass):
calls = async_mock_service(
hass, climate.DOMAIN, climate.SERVICE_SET_OPERATION_MODE)
await trt.execute(hass, trait.COMMAND_THERMOSTAT_SET_MODE, {
await trt.execute(trait.COMMAND_THERMOSTAT_SET_MODE, {
'thermostatMode': 'heatcool',
})
assert len(calls) == 1
@@ -558,11 +559,11 @@ async def test_temperature_setting_climate_range(hass):
}
with pytest.raises(helpers.SmartHomeError) as err:
await trt.execute(
hass, trait.COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT, {
'thermostatTemperatureSetpoint': -100,
})
await trt.execute(trait.COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT, {
'thermostatTemperatureSetpoint': -100,
})
assert err.value.code == const.ERR_VALUE_OUT_OF_RANGE
hass.config.units.temperature_unit = TEMP_CELSIUS
async def test_temperature_setting_climate_setpoint(hass):
@@ -571,7 +572,9 @@ async def test_temperature_setting_climate_setpoint(hass):
assert trait.TemperatureSettingTrait.supported(
climate.DOMAIN, climate.SUPPORT_OPERATION_MODE)
trt = trait.TemperatureSettingTrait(State(
hass.config.units.temperature_unit = TEMP_CELSIUS
trt = trait.TemperatureSettingTrait(hass, State(
'climate.bla', climate.STATE_AUTO, {
climate.ATTR_OPERATION_MODE: climate.STATE_COOL,
climate.ATTR_OPERATION_LIST: [
@@ -581,8 +584,7 @@ async def test_temperature_setting_climate_setpoint(hass):
climate.ATTR_MIN_TEMP: 10,
climate.ATTR_MAX_TEMP: 30,
climate.ATTR_TEMPERATURE: 18,
climate.ATTR_CURRENT_TEMPERATURE: 20,
ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS,
climate.ATTR_CURRENT_TEMPERATURE: 20
}))
assert trt.sync_attributes() == {
'availableThermostatModes': 'off,cool',
@@ -601,12 +603,11 @@ async def test_temperature_setting_climate_setpoint(hass):
hass, climate.DOMAIN, climate.SERVICE_SET_TEMPERATURE)
with pytest.raises(helpers.SmartHomeError):
await trt.execute(
hass, trait.COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT, {
'thermostatTemperatureSetpoint': -100,
})
await trt.execute(trait.COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT, {
'thermostatTemperatureSetpoint': -100,
})
await trt.execute(hass, trait.COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT, {
await trt.execute(trait.COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT, {
'thermostatTemperatureSetpoint': 19,
})
assert len(calls) == 1
+4 -4
View File
@@ -19,7 +19,7 @@ class TestComponentsGroup(unittest.TestCase):
# pylint: disable=invalid-name
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
# pylint: disable=invalid-name
@@ -28,7 +28,7 @@ class TestComponentsGroup(unittest.TestCase):
self.hass.stop()
def test_setup_group_with_mixed_groupable_states(self):
"""Try to setup a group with mixed groupable states."""
"""Try to set up a group with mixed groupable states."""
self.hass.states.set('light.Bowl', STATE_ON)
self.hass.states.set('device_tracker.Paulus', STATE_HOME)
group.Group.create_group(
@@ -41,7 +41,7 @@ class TestComponentsGroup(unittest.TestCase):
group.ENTITY_ID_FORMAT.format('person_and_light')).state)
def test_setup_group_with_a_non_existing_state(self):
"""Try to setup a group with a non existing state."""
"""Try to set up a group with a non existing state."""
self.hass.states.set('light.Bowl', STATE_ON)
grp = group.Group.create_group(
@@ -62,7 +62,7 @@ class TestComponentsGroup(unittest.TestCase):
self.assertEqual(STATE_UNKNOWN, grp.state)
def test_setup_empty_group(self):
"""Try to setup an empty group."""
"""Try to set up an empty group."""
grp = group.Group.create_group(self.hass, 'nothing', [])
self.assertEqual(STATE_UNKNOWN, grp.state)
+1
View File
@@ -0,0 +1 @@
"""Tests for the Hangouts Component."""
@@ -0,0 +1,92 @@
"""Tests for the Google Hangouts config flow."""
from unittest.mock import patch
from homeassistant import data_entry_flow
from homeassistant.components.hangouts import config_flow
async def test_flow_works(hass, aioclient_mock):
"""Test config flow without 2fa."""
flow = config_flow.HangoutsFlowHandler()
flow.hass = hass
with patch('hangups.get_auth'):
result = await flow.async_step_user(
{'email': 'test@test.com', 'password': '1232456'})
assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result['title'] == 'test@test.com'
async def test_flow_works_with_2fa(hass, aioclient_mock):
"""Test config flow with 2fa."""
from homeassistant.components.hangouts.hangups_utils import Google2FAError
flow = config_flow.HangoutsFlowHandler()
flow.hass = hass
with patch('hangups.get_auth', side_effect=Google2FAError):
result = await flow.async_step_user(
{'email': 'test@test.com', 'password': '1232456'})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == '2fa'
with patch('hangups.get_auth'):
result = await flow.async_step_2fa({'2fa': 123456})
assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result['title'] == 'test@test.com'
async def test_flow_with_unknown_2fa(hass, aioclient_mock):
"""Test config flow with invalid 2fa method."""
from homeassistant.components.hangouts.hangups_utils import GoogleAuthError
flow = config_flow.HangoutsFlowHandler()
flow.hass = hass
with patch('hangups.get_auth',
side_effect=GoogleAuthError('Unknown verification code input')):
result = await flow.async_step_user(
{'email': 'test@test.com', 'password': '1232456'})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_2fa_method'
async def test_flow_invalid_login(hass, aioclient_mock):
"""Test config flow with invalid 2fa method."""
from homeassistant.components.hangouts.hangups_utils import GoogleAuthError
flow = config_flow.HangoutsFlowHandler()
flow.hass = hass
with patch('hangups.get_auth',
side_effect=GoogleAuthError):
result = await flow.async_step_user(
{'email': 'test@test.com', 'password': '1232456'})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_login'
async def test_flow_invalid_2fa(hass, aioclient_mock):
"""Test config flow with 2fa."""
from homeassistant.components.hangouts.hangups_utils import Google2FAError
flow = config_flow.HangoutsFlowHandler()
flow.hass = hass
with patch('hangups.get_auth', side_effect=Google2FAError):
result = await flow.async_step_user(
{'email': 'test@test.com', 'password': '1232456'})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == '2fa'
with patch('hangups.get_auth', side_effect=Google2FAError):
result = await flow.async_step_2fa({'2fa': 123456})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['errors']['base'] == 'invalid_2fa'
@@ -12,8 +12,8 @@ from homeassistant.components.climate import (
from homeassistant.components.homekit.const import (
PROP_MAX_VALUE, PROP_MIN_VALUE)
from homeassistant.const import (
ATTR_ENTITY_ID, ATTR_SUPPORTED_FEATURES, ATTR_UNIT_OF_MEASUREMENT,
CONF_TEMPERATURE_UNIT, STATE_OFF, TEMP_CELSIUS, TEMP_FAHRENHEIT)
ATTR_ENTITY_ID, ATTR_SUPPORTED_FEATURES, CONF_TEMPERATURE_UNIT, STATE_OFF,
TEMP_FAHRENHEIT)
from tests.common import async_mock_service
from tests.components.homekit.common import patch_debounce
@@ -58,8 +58,7 @@ async def test_default_thermostat(hass, hk_driver, cls):
hass.states.async_set(entity_id, STATE_HEAT,
{ATTR_OPERATION_MODE: STATE_HEAT,
ATTR_TEMPERATURE: 22.0,
ATTR_CURRENT_TEMPERATURE: 18.0,
ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
ATTR_CURRENT_TEMPERATURE: 18.0})
await hass.async_block_till_done()
assert acc.char_target_temp.value == 22.0
assert acc.char_current_heat_cool.value == 1
@@ -70,8 +69,7 @@ async def test_default_thermostat(hass, hk_driver, cls):
hass.states.async_set(entity_id, STATE_HEAT,
{ATTR_OPERATION_MODE: STATE_HEAT,
ATTR_TEMPERATURE: 22.0,
ATTR_CURRENT_TEMPERATURE: 23.0,
ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
ATTR_CURRENT_TEMPERATURE: 23.0})
await hass.async_block_till_done()
assert acc.char_target_temp.value == 22.0
assert acc.char_current_heat_cool.value == 0
@@ -82,8 +80,7 @@ async def test_default_thermostat(hass, hk_driver, cls):
hass.states.async_set(entity_id, STATE_COOL,
{ATTR_OPERATION_MODE: STATE_COOL,
ATTR_TEMPERATURE: 20.0,
ATTR_CURRENT_TEMPERATURE: 25.0,
ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
ATTR_CURRENT_TEMPERATURE: 25.0})
await hass.async_block_till_done()
assert acc.char_target_temp.value == 20.0
assert acc.char_current_heat_cool.value == 2
@@ -94,8 +91,7 @@ async def test_default_thermostat(hass, hk_driver, cls):
hass.states.async_set(entity_id, STATE_COOL,
{ATTR_OPERATION_MODE: STATE_COOL,
ATTR_TEMPERATURE: 20.0,
ATTR_CURRENT_TEMPERATURE: 19.0,
ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
ATTR_CURRENT_TEMPERATURE: 19.0})
await hass.async_block_till_done()
assert acc.char_target_temp.value == 20.0
assert acc.char_current_heat_cool.value == 0
@@ -106,8 +102,7 @@ async def test_default_thermostat(hass, hk_driver, cls):
hass.states.async_set(entity_id, STATE_OFF,
{ATTR_OPERATION_MODE: STATE_OFF,
ATTR_TEMPERATURE: 22.0,
ATTR_CURRENT_TEMPERATURE: 18.0,
ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
ATTR_CURRENT_TEMPERATURE: 18.0})
await hass.async_block_till_done()
assert acc.char_target_temp.value == 22.0
assert acc.char_current_heat_cool.value == 0
@@ -119,8 +114,7 @@ async def test_default_thermostat(hass, hk_driver, cls):
{ATTR_OPERATION_MODE: STATE_AUTO,
ATTR_OPERATION_LIST: [STATE_HEAT, STATE_COOL],
ATTR_TEMPERATURE: 22.0,
ATTR_CURRENT_TEMPERATURE: 18.0,
ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
ATTR_CURRENT_TEMPERATURE: 18.0})
await hass.async_block_till_done()
assert acc.char_target_temp.value == 22.0
assert acc.char_current_heat_cool.value == 1
@@ -132,8 +126,7 @@ async def test_default_thermostat(hass, hk_driver, cls):
{ATTR_OPERATION_MODE: STATE_AUTO,
ATTR_OPERATION_LIST: [STATE_HEAT, STATE_COOL],
ATTR_TEMPERATURE: 22.0,
ATTR_CURRENT_TEMPERATURE: 25.0,
ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
ATTR_CURRENT_TEMPERATURE: 25.0})
await hass.async_block_till_done()
assert acc.char_target_temp.value == 22.0
assert acc.char_current_heat_cool.value == 2
@@ -145,8 +138,7 @@ async def test_default_thermostat(hass, hk_driver, cls):
{ATTR_OPERATION_MODE: STATE_AUTO,
ATTR_OPERATION_LIST: [STATE_HEAT, STATE_COOL],
ATTR_TEMPERATURE: 22.0,
ATTR_CURRENT_TEMPERATURE: 22.0,
ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
ATTR_CURRENT_TEMPERATURE: 22.0})
await hass.async_block_till_done()
assert acc.char_target_temp.value == 22.0
assert acc.char_current_heat_cool.value == 0
@@ -201,8 +193,7 @@ async def test_auto_thermostat(hass, hk_driver, cls):
{ATTR_OPERATION_MODE: STATE_AUTO,
ATTR_TARGET_TEMP_HIGH: 22.0,
ATTR_TARGET_TEMP_LOW: 20.0,
ATTR_CURRENT_TEMPERATURE: 18.0,
ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
ATTR_CURRENT_TEMPERATURE: 18.0})
await hass.async_block_till_done()
assert acc.char_heating_thresh_temp.value == 20.0
assert acc.char_cooling_thresh_temp.value == 22.0
@@ -215,8 +206,7 @@ async def test_auto_thermostat(hass, hk_driver, cls):
{ATTR_OPERATION_MODE: STATE_AUTO,
ATTR_TARGET_TEMP_HIGH: 23.0,
ATTR_TARGET_TEMP_LOW: 19.0,
ATTR_CURRENT_TEMPERATURE: 24.0,
ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
ATTR_CURRENT_TEMPERATURE: 24.0})
await hass.async_block_till_done()
assert acc.char_heating_thresh_temp.value == 19.0
assert acc.char_cooling_thresh_temp.value == 23.0
@@ -229,8 +219,7 @@ async def test_auto_thermostat(hass, hk_driver, cls):
{ATTR_OPERATION_MODE: STATE_AUTO,
ATTR_TARGET_TEMP_HIGH: 23.0,
ATTR_TARGET_TEMP_LOW: 19.0,
ATTR_CURRENT_TEMPERATURE: 21.0,
ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
ATTR_CURRENT_TEMPERATURE: 21.0})
await hass.async_block_till_done()
assert acc.char_heating_thresh_temp.value == 19.0
assert acc.char_cooling_thresh_temp.value == 23.0
@@ -334,8 +323,7 @@ async def test_thermostat_fahrenheit(hass, hk_driver, cls):
ATTR_TARGET_TEMP_HIGH: 75.2,
ATTR_TARGET_TEMP_LOW: 68,
ATTR_TEMPERATURE: 71.6,
ATTR_CURRENT_TEMPERATURE: 73.4,
ATTR_UNIT_OF_MEASUREMENT: TEMP_FAHRENHEIT})
ATTR_CURRENT_TEMPERATURE: 73.4})
await hass.async_block_till_done()
assert acc.char_heating_thresh_temp.value == 20.0
assert acc.char_cooling_thresh_temp.value == 24.0
+2 -2
View File
@@ -38,7 +38,7 @@ async def mock_handler(request):
@pytest.fixture
def app(hass):
"""Fixture to setup a web.Application."""
"""Fixture to set up a web.Application."""
app = web.Application()
app['hass'] = hass
app.router.add_get('/', mock_handler)
@@ -48,7 +48,7 @@ def app(hass):
@pytest.fixture
def app2(hass):
"""Fixture to setup a web.Application without real_ip middleware."""
"""Fixture to set up a web.Application without real_ip middleware."""
app = web.Application()
app['hass'] = hass
app.router.add_get('/', mock_handler)
+1 -1
View File
@@ -49,7 +49,7 @@ async def mock_handler(request):
@pytest.fixture
def client(loop, aiohttp_client):
"""Fixture to setup a web.Application."""
"""Fixture to set up a web.Application."""
app = web.Application()
app.router.add_get('/', mock_handler)
setup_cors(app, [TRUSTED_ORIGIN])
+1 -1
View File
@@ -8,7 +8,7 @@ from homeassistant.components.http.const import KEY_REAL_IP
async def mock_handler(request):
"""Handler that returns the real IP as text."""
"""Return the real IP as text."""
return web.Response(text=str(request[KEY_REAL_IP]))
+1 -1
View File
@@ -8,7 +8,7 @@ from tests.common import mock_coro, MockConfigEntry
async def test_setup_with_no_config(hass):
"""Test that we do not discover anything or try to setup a bridge."""
"""Test that we do not discover anything or try to set up a bridge."""
with patch.object(hass, 'config_entries') as mock_config_entries, \
patch.object(hue, 'configured_hosts', return_value=[]):
assert await async_setup_component(hass, hue.DOMAIN, {}) is True
@@ -141,13 +141,13 @@ def test_valid_file_path():
async def test_setup_platform(hass, mock_healthybox):
"""Setup platform with one entity."""
"""Set up platform with one entity."""
await async_setup_component(hass, ip.DOMAIN, VALID_CONFIG)
assert hass.states.get(VALID_ENTITY_ID)
async def test_setup_platform_with_auth(hass, mock_healthybox):
"""Setup platform with one entity and auth."""
"""Set up platform with one entity and auth."""
valid_config_auth = VALID_CONFIG.copy()
valid_config_auth[ip.DOMAIN][CONF_USERNAME] = MOCK_USERNAME
valid_config_auth[ip.DOMAIN][CONF_PASSWORD] = MOCK_PASSWORD
@@ -297,7 +297,7 @@ async def test_teach_service(
async def test_setup_platform_with_name(hass, mock_healthybox):
"""Setup platform with one entity and a name."""
"""Set up platform with one entity and a name."""
named_entity_id = 'image_processing.{}'.format(MOCK_NAME)
valid_config_named = VALID_CONFIG.copy()
+11 -11
View File
@@ -16,7 +16,7 @@ class TestSetupImageProcessing:
"""Test class for setup image processing."""
def setup_method(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def teardown_method(self):
@@ -24,7 +24,7 @@ class TestSetupImageProcessing:
self.hass.stop()
def test_setup_component(self):
"""Setup demo platform on image_process component."""
"""Set up demo platform on image_process component."""
config = {
ip.DOMAIN: {
'platform': 'demo'
@@ -35,7 +35,7 @@ class TestSetupImageProcessing:
setup_component(self.hass, ip.DOMAIN, config)
def test_setup_component_with_service(self):
"""Setup demo platform on image_process component test service."""
"""Set up demo platform on image_process component test service."""
config = {
ip.DOMAIN: {
'platform': 'demo'
@@ -52,7 +52,7 @@ class TestImageProcessing:
"""Test class for image processing."""
def setup_method(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
setup_component(
@@ -113,7 +113,7 @@ class TestImageProcessingAlpr:
"""Test class for alpr image processing."""
def setup_method(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
config = {
@@ -149,7 +149,7 @@ class TestImageProcessingAlpr:
self.hass.stop()
def test_alpr_event_single_call(self, aioclient_mock):
"""Setup and scan a picture and test plates from event."""
"""Set up and scan a picture and test plates from event."""
aioclient_mock.get(self.url, content=b'image')
ip.scan(self.hass, entity_id='image_processing.demo_alpr')
@@ -168,7 +168,7 @@ class TestImageProcessingAlpr:
assert event_data[0]['entity_id'] == 'image_processing.demo_alpr'
def test_alpr_event_double_call(self, aioclient_mock):
"""Setup and scan a picture and test plates from event."""
"""Set up and scan a picture and test plates from event."""
aioclient_mock.get(self.url, content=b'image')
ip.scan(self.hass, entity_id='image_processing.demo_alpr')
@@ -192,7 +192,7 @@ class TestImageProcessingAlpr:
new_callable=PropertyMock(return_value=95))
def test_alpr_event_single_call_confidence(self, confidence_mock,
aioclient_mock):
"""Setup and scan a picture and test plates from event."""
"""Set up and scan a picture and test plates from event."""
aioclient_mock.get(self.url, content=b'image')
ip.scan(self.hass, entity_id='image_processing.demo_alpr')
@@ -215,7 +215,7 @@ class TestImageProcessingFace:
"""Test class for face image processing."""
def setup_method(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
config = {
@@ -251,7 +251,7 @@ class TestImageProcessingFace:
self.hass.stop()
def test_face_event_call(self, aioclient_mock):
"""Setup and scan a picture and test faces from event."""
"""Set up and scan a picture and test faces from event."""
aioclient_mock.get(self.url, content=b'image')
ip.scan(self.hass, entity_id='image_processing.demo_face')
@@ -276,7 +276,7 @@ class TestImageProcessingFace:
'DemoImageProcessingFace.confidence',
new_callable=PropertyMock(return_value=None))
def test_face_event_call_no_confidence(self, mock_config, aioclient_mock):
"""Setup and scan a picture and test faces from event."""
"""Set up and scan a picture and test faces from event."""
aioclient_mock.get(self.url, content=b'image')
ip.scan(self.hass, entity_id='image_processing.demo_face')
@@ -15,7 +15,7 @@ class TestMicrosoftFaceDetectSetup:
"""Test class for image processing."""
def setup_method(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def teardown_method(self):
@@ -25,7 +25,7 @@ class TestMicrosoftFaceDetectSetup:
@patch('homeassistant.components.microsoft_face.'
'MicrosoftFace.update_store', return_value=mock_coro())
def test_setup_platform(self, store_mock):
"""Setup platform with one entity."""
"""Set up platform with one entity."""
config = {
ip.DOMAIN: {
'platform': 'microsoft_face_detect',
@@ -51,7 +51,7 @@ class TestMicrosoftFaceDetectSetup:
@patch('homeassistant.components.microsoft_face.'
'MicrosoftFace.update_store', return_value=mock_coro())
def test_setup_platform_name(self, store_mock):
"""Setup platform with one entity and set name."""
"""Set up platform with one entity and set name."""
config = {
ip.DOMAIN: {
'platform': 'microsoft_face_detect',
@@ -78,7 +78,7 @@ class TestMicrosoftFaceDetect:
"""Test class for image processing."""
def setup_method(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.config = {
@@ -108,7 +108,7 @@ class TestMicrosoftFaceDetect:
'MicrosoftFaceDetectEntity.should_poll',
new_callable=PropertyMock(return_value=False))
def test_ms_detect_process_image(self, poll_mock, aioclient_mock):
"""Setup and scan a picture and test plates from event."""
"""Set up and scan a picture and test plates from event."""
aioclient_mock.get(
self.endpoint_url.format("persongroups"),
text=load_fixture('microsoft_face_persongroups.json')
@@ -15,7 +15,7 @@ class TestMicrosoftFaceIdentifySetup:
"""Test class for image processing."""
def setup_method(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def teardown_method(self):
@@ -25,7 +25,7 @@ class TestMicrosoftFaceIdentifySetup:
@patch('homeassistant.components.microsoft_face.'
'MicrosoftFace.update_store', return_value=mock_coro())
def test_setup_platform(self, store_mock):
"""Setup platform with one entity."""
"""Set up platform with one entity."""
config = {
ip.DOMAIN: {
'platform': 'microsoft_face_identify',
@@ -51,7 +51,7 @@ class TestMicrosoftFaceIdentifySetup:
@patch('homeassistant.components.microsoft_face.'
'MicrosoftFace.update_store', return_value=mock_coro())
def test_setup_platform_name(self, store_mock):
"""Setup platform with one entity and set name."""
"""Set up platform with one entity and set name."""
config = {
ip.DOMAIN: {
'platform': 'microsoft_face_identify',
@@ -79,7 +79,7 @@ class TestMicrosoftFaceIdentify:
"""Test class for image processing."""
def setup_method(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.config = {
@@ -109,7 +109,7 @@ class TestMicrosoftFaceIdentify:
'MicrosoftFaceIdentifyEntity.should_poll',
new_callable=PropertyMock(return_value=False))
def test_ms_identify_process_image(self, poll_mock, aioclient_mock):
"""Setup and scan a picture and test plates from event."""
"""Set up and scan a picture and test plates from event."""
aioclient_mock.get(
self.endpoint_url.format("persongroups"),
text=load_fixture('microsoft_face_persongroups.json')
@@ -16,7 +16,7 @@ class TestOpenAlprCloudSetup:
"""Test class for image processing."""
def setup_method(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def teardown_method(self):
@@ -24,7 +24,7 @@ class TestOpenAlprCloudSetup:
self.hass.stop()
def test_setup_platform(self):
"""Setup platform with one entity."""
"""Set up platform with one entity."""
config = {
ip.DOMAIN: {
'platform': 'openalpr_cloud',
@@ -45,7 +45,7 @@ class TestOpenAlprCloudSetup:
assert self.hass.states.get('image_processing.openalpr_demo_camera')
def test_setup_platform_name(self):
"""Setup platform with one entity and set name."""
"""Set up platform with one entity and set name."""
config = {
ip.DOMAIN: {
'platform': 'openalpr_cloud',
@@ -67,7 +67,7 @@ class TestOpenAlprCloudSetup:
assert self.hass.states.get('image_processing.test_local')
def test_setup_platform_without_api_key(self):
"""Setup platform with one entity without api_key."""
"""Set up platform with one entity without api_key."""
config = {
ip.DOMAIN: {
'platform': 'openalpr_cloud',
@@ -85,7 +85,7 @@ class TestOpenAlprCloudSetup:
setup_component(self.hass, ip.DOMAIN, config)
def test_setup_platform_without_region(self):
"""Setup platform with one entity without region."""
"""Set up platform with one entity without region."""
config = {
ip.DOMAIN: {
'platform': 'openalpr_cloud',
@@ -107,7 +107,7 @@ class TestOpenAlprCloud:
"""Test class for image processing."""
def setup_method(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
config = {
@@ -151,7 +151,7 @@ class TestOpenAlprCloud:
self.hass.stop()
def test_openalpr_process_image(self, aioclient_mock):
"""Setup and scan a picture and test plates from event."""
"""Set up and scan a picture and test plates from event."""
aioclient_mock.post(
OPENALPR_API_URL, params=self.params,
text=load_fixture('alpr_cloud.json'), status=200
@@ -179,7 +179,7 @@ class TestOpenAlprCloud:
'image_processing.test_local'
def test_openalpr_process_image_api_error(self, aioclient_mock):
"""Setup and scan a picture and test api error."""
"""Set up and scan a picture and test api error."""
aioclient_mock.post(
OPENALPR_API_URL, params=self.params,
text="{'error': 'error message'}", status=400
@@ -195,7 +195,7 @@ class TestOpenAlprCloud:
assert len(self.alpr_events) == 0
def test_openalpr_process_image_api_timeout(self, aioclient_mock):
"""Setup and scan a picture and test api error."""
"""Set up and scan a picture and test api error."""
aioclient_mock.post(
OPENALPR_API_URL, params=self.params,
exc=asyncio.TimeoutError()
@@ -30,7 +30,7 @@ class TestOpenAlprLocalSetup:
"""Test class for image processing."""
def setup_method(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def teardown_method(self):
@@ -38,7 +38,7 @@ class TestOpenAlprLocalSetup:
self.hass.stop()
def test_setup_platform(self):
"""Setup platform with one entity."""
"""Set up platform with one entity."""
config = {
ip.DOMAIN: {
'platform': 'openalpr_local',
@@ -58,7 +58,7 @@ class TestOpenAlprLocalSetup:
assert self.hass.states.get('image_processing.openalpr_demo_camera')
def test_setup_platform_name(self):
"""Setup platform with one entity and set name."""
"""Set up platform with one entity and set name."""
config = {
ip.DOMAIN: {
'platform': 'openalpr_local',
@@ -79,7 +79,7 @@ class TestOpenAlprLocalSetup:
assert self.hass.states.get('image_processing.test_local')
def test_setup_platform_without_region(self):
"""Setup platform with one entity without region."""
"""Set up platform with one entity without region."""
config = {
ip.DOMAIN: {
'platform': 'openalpr_local',
@@ -100,7 +100,7 @@ class TestOpenAlprLocal:
"""Test class for image processing."""
def setup_method(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
config = {
@@ -143,7 +143,7 @@ class TestOpenAlprLocal:
@patch('asyncio.create_subprocess_exec',
return_value=mock_async_subprocess())
def test_openalpr_process_image(self, popen_mock, aioclient_mock):
"""Setup and scan a picture and test plates from event."""
"""Set up and scan a picture and test plates from event."""
aioclient_mock.get(self.url, content=b'image')
ip.scan(self.hass, entity_id='image_processing.test_local')
+1 -1
View File
@@ -15,7 +15,7 @@ class TestDemoLight(unittest.TestCase):
# pylint: disable=invalid-name
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.assertTrue(setup_component(self.hass, light.DOMAIN, {'light': {
'platform': 'demo',
+12 -10
View File
@@ -14,7 +14,7 @@ from homeassistant.components import light
from homeassistant.helpers.intent import IntentHandleError
from tests.common import (
async_mock_service, mock_service, get_test_home_assistant)
async_mock_service, mock_service, get_test_home_assistant, mock_storage)
class TestLight(unittest.TestCase):
@@ -22,7 +22,7 @@ class TestLight(unittest.TestCase):
# pylint: disable=invalid-name
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
# pylint: disable=invalid-name
@@ -333,10 +333,11 @@ class TestLight(unittest.TestCase):
"group.all_lights.default,.4,.6,99\n"
with mock.patch('os.path.isfile', side_effect=_mock_isfile):
with mock.patch('builtins.open', side_effect=_mock_open):
self.assertTrue(setup_component(
self.hass, light.DOMAIN,
{light.DOMAIN: {CONF_PLATFORM: 'test'}}
))
with mock_storage():
self.assertTrue(setup_component(
self.hass, light.DOMAIN,
{light.DOMAIN: {CONF_PLATFORM: 'test'}}
))
dev, _, _ = platform.DEVICES
light.turn_on(self.hass, dev.entity_id)
@@ -371,10 +372,11 @@ class TestLight(unittest.TestCase):
"light.ceiling_2.default,.6,.6,100\n"
with mock.patch('os.path.isfile', side_effect=_mock_isfile):
with mock.patch('builtins.open', side_effect=_mock_open):
self.assertTrue(setup_component(
self.hass, light.DOMAIN,
{light.DOMAIN: {CONF_PLATFORM: 'test'}}
))
with mock_storage():
self.assertTrue(setup_component(
self.hass, light.DOMAIN,
{light.DOMAIN: {CONF_PLATFORM: 'test'}}
))
dev = next(filter(lambda x: x.entity_id == 'light.ceiling_2',
platform.DEVICES))
+1 -1
View File
@@ -21,7 +21,7 @@ class TestLiteJetLight(unittest.TestCase):
@mock.patch('pylitejet.LiteJet')
def setup_method(self, method, mock_pylitejet):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.start()
+13 -13
View File
@@ -28,7 +28,7 @@ class TestMochadSwitchSetup(unittest.TestCase):
THING = 'light'
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self):
@@ -57,7 +57,7 @@ class TestMochadLight(unittest.TestCase):
"""Test for mochad light platform."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
controller_mock = mock.MagicMock()
dev_dict = {'address': 'a1', 'name': 'fake_light',
@@ -76,25 +76,25 @@ class TestMochadLight(unittest.TestCase):
def test_turn_on_with_no_brightness(self):
"""Test turn_on."""
self.light.turn_on()
self.light.device.send_cmd.assert_called_once_with('on')
self.light.light.send_cmd.assert_called_once_with('on')
def test_turn_on_with_brightness(self):
"""Test turn_on."""
self.light.turn_on(brightness=45)
self.light.device.send_cmd.assert_has_calls(
self.light.light.send_cmd.assert_has_calls(
[mock.call('on'), mock.call('dim 25')])
def test_turn_off(self):
"""Test turn_off."""
self.light.turn_off()
self.light.device.send_cmd.assert_called_once_with('off')
self.light.light.send_cmd.assert_called_once_with('off')
class TestMochadLight256Levels(unittest.TestCase):
"""Test for mochad light platform."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
controller_mock = mock.MagicMock()
dev_dict = {'address': 'a1', 'name': 'fake_light',
@@ -109,24 +109,24 @@ class TestMochadLight256Levels(unittest.TestCase):
def test_turn_on_with_no_brightness(self):
"""Test turn_on."""
self.light.turn_on()
self.light.device.send_cmd.assert_called_once_with('xdim 255')
self.light.light.send_cmd.assert_called_once_with('xdim 255')
def test_turn_on_with_brightness(self):
"""Test turn_on."""
self.light.turn_on(brightness=45)
self.light.device.send_cmd.assert_called_once_with('xdim 45')
self.light.light.send_cmd.assert_called_once_with('xdim 45')
def test_turn_off(self):
"""Test turn_off."""
self.light.turn_off()
self.light.device.send_cmd.assert_called_once_with('off')
self.light.light.send_cmd.assert_called_once_with('off')
class TestMochadLight64Levels(unittest.TestCase):
"""Test for mochad light platform."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
controller_mock = mock.MagicMock()
dev_dict = {'address': 'a1', 'name': 'fake_light',
@@ -141,14 +141,14 @@ class TestMochadLight64Levels(unittest.TestCase):
def test_turn_on_with_no_brightness(self):
"""Test turn_on."""
self.light.turn_on()
self.light.device.send_cmd.assert_called_once_with('xdim 63')
self.light.light.send_cmd.assert_called_once_with('xdim 63')
def test_turn_on_with_brightness(self):
"""Test turn_on."""
self.light.turn_on(brightness=45)
self.light.device.send_cmd.assert_called_once_with('xdim 11')
self.light.light.send_cmd.assert_called_once_with('xdim 11')
def test_turn_off(self):
"""Test turn_off."""
self.light.turn_off()
self.light.device.send_cmd.assert_called_once_with('off')
self.light.light.send_cmd.assert_called_once_with('off')
+1 -1
View File
@@ -158,7 +158,7 @@ class TestLightMQTT(unittest.TestCase):
# pylint: disable=invalid-name
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_publish = mock_mqtt_component(self.hass)
+1 -1
View File
@@ -107,7 +107,7 @@ class TestLightMQTTJSON(unittest.TestCase):
"""Test the MQTT JSON light."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_publish = mock_mqtt_component(self.hass)
+1 -1
View File
@@ -43,7 +43,7 @@ class TestLightMQTTTemplate(unittest.TestCase):
"""Test the MQTT Template light."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_publish = mock_mqtt_component(self.hass)
+1 -1
View File
@@ -14,7 +14,7 @@ class TestLightRfxtrx(unittest.TestCase):
"""Test the Rfxtrx light platform."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_component(self.hass, 'rfxtrx')
+1 -1
View File
@@ -20,7 +20,7 @@ class TestTemplateLight:
# pylint: disable=invalid-name
def setup_method(self, method):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.calls = []
+1 -1
View File
@@ -14,7 +14,7 @@ class TestLockDemo(unittest.TestCase):
"""Test the demo lock."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.assertTrue(setup_component(self.hass, lock.DOMAIN, {
'lock': {
+1 -1
View File
@@ -13,7 +13,7 @@ class TestLockMQTT(unittest.TestCase):
"""Test the MQTT lock."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_publish = mock_mqtt_component(self.hass)
@@ -123,7 +123,7 @@ class TestAsyncMediaPlayer(unittest.TestCase):
"""Test the media_player module."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.player = AsyncMediaPlayer(self.hass)
@@ -176,7 +176,7 @@ class TestSyncMediaPlayer(unittest.TestCase):
"""Test the media_player module."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.player = SyncMediaPlayer(self.hass)
+3 -3
View File
@@ -48,7 +48,7 @@ def get_fake_chromecast_info(host='192.168.178.42', port=8009,
async def async_setup_cast(hass, config=None, discovery_info=None):
"""Helper to setup the cast platform."""
"""Set up the cast platform."""
if config is None:
config = {}
add_devices = Mock()
@@ -62,7 +62,7 @@ async def async_setup_cast(hass, config=None, discovery_info=None):
async def async_setup_cast_internal_discovery(hass, config=None,
discovery_info=None):
"""Setup the cast platform and the discovery."""
"""Set up the cast platform and the discovery."""
listener = MagicMock(services={})
with patch('pychromecast.start_discovery',
@@ -85,7 +85,7 @@ async def async_setup_cast_internal_discovery(hass, config=None,
async def async_setup_media_player_cast(hass: HomeAssistantType,
info: ChromecastInfo):
"""Setup the cast platform with async_setup_component."""
"""Set up the cast platform with async_setup_component."""
chromecast = get_fake_chromecast(info)
cast.CastStatusListener = MagicMock()
+2 -2
View File
@@ -25,7 +25,7 @@ class TestDemoMediaPlayer(unittest.TestCase):
"""Test the media_player module."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self):
@@ -227,7 +227,7 @@ class TestMediaPlayerWeb(unittest.TestCase):
"""Test the media player web views sensor."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
assert setup_component(self.hass, http.DOMAIN, {
@@ -52,7 +52,7 @@ class TestSamsungTv(unittest.TestCase):
@MockDependency('samsungctl')
@MockDependency('wakeonlan')
def setUp(self, samsung_mock, wol_mock):
"""Setting up test environment."""
"""Set up test environment."""
self.hass = tests.common.get_test_home_assistant()
self.hass.start()
self.hass.block_till_done()
+1 -1
View File
@@ -135,7 +135,7 @@ class TestSonosMediaPlayer(unittest.TestCase):
# pylint: disable=invalid-name
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def monkey_available(self):
@@ -148,7 +148,7 @@ class TestSoundtouchMediaPlayer(unittest.TestCase):
"""Bose Soundtouch test class."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
logging.disable(logging.CRITICAL)
@@ -94,7 +94,7 @@ class MockMediaPlayer(media_player.MediaPlayerDevice):
@property
def volume_level(self):
"""The volume level of player."""
"""Return the volume level of player."""
return self._volume_level
@property
@@ -158,7 +158,7 @@ class TestMediaPlayer(unittest.TestCase):
"""Test the media_player module."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_mp_1 = MockMediaPlayer(self.hass, 'mock1')
+1 -1
View File
@@ -33,7 +33,7 @@ class TestYamahaMediaPlayer(unittest.TestCase):
"""Test the Yamaha media player."""
def setUp(self):
"""Setup things to be run when tests are started."""
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.main_zone = _create_zone_mock('Main zone', 'http://main')
self.device = FakeYamahaDevice(
Loaded 100 of 485 files, more files were not shown because too many files have changed in this diff. Show more