This commit is contained in:
Paulus Schoutsen
2019-07-31 12:25:30 -07:00
parent da05dfe708
commit 4de97abc3a
2676 changed files with 163166 additions and 140084 deletions

View File

@@ -12,9 +12,9 @@ from tests.common import register_auth_provider
@pytest.fixture
def provider(hass):
"""Home Assistant auth provider."""
provider = hass.loop.run_until_complete(register_auth_provider(hass, {
'type': 'homeassistant',
}))
provider = hass.loop.run_until_complete(
register_auth_provider(hass, {"type": "homeassistant"})
)
hass.loop.run_until_complete(provider.async_initialize())
return provider
@@ -22,89 +22,90 @@ def provider(hass):
async def test_list_user(hass, provider, capsys):
"""Test we can list users."""
data = provider.data
data.add_auth('test-user', 'test-pass')
data.add_auth('second-user', 'second-pass')
data.add_auth("test-user", "test-pass")
data.add_auth("second-user", "second-pass")
await script_auth.list_users(hass, provider, None)
captured = capsys.readouterr()
assert captured.out == '\n'.join([
'test-user',
'second-user',
'',
'Total users: 2',
''
])
assert captured.out == "\n".join(
["test-user", "second-user", "", "Total users: 2", ""]
)
async def test_add_user(hass, provider, capsys, hass_storage):
"""Test we can add a user."""
data = provider.data
await script_auth.add_user(
hass, provider, Mock(username='paulus', password='test-pass'))
hass, provider, Mock(username="paulus", password="test-pass")
)
assert len(hass_storage[hass_auth.STORAGE_KEY]['data']['users']) == 1
assert len(hass_storage[hass_auth.STORAGE_KEY]["data"]["users"]) == 1
captured = capsys.readouterr()
assert captured.out == 'Auth created\n'
assert captured.out == "Auth created\n"
assert len(data.users) == 1
data.validate_login('paulus', 'test-pass')
data.validate_login("paulus", "test-pass")
async def test_validate_login(hass, provider, capsys):
"""Test we can validate a user login."""
data = provider.data
data.add_auth('test-user', 'test-pass')
data.add_auth("test-user", "test-pass")
await script_auth.validate_login(
hass, provider, Mock(username='test-user', password='test-pass'))
hass, provider, Mock(username="test-user", password="test-pass")
)
captured = capsys.readouterr()
assert captured.out == 'Auth valid\n'
assert captured.out == "Auth valid\n"
await script_auth.validate_login(
hass, provider, Mock(username='test-user', password='invalid-pass'))
hass, provider, Mock(username="test-user", password="invalid-pass")
)
captured = capsys.readouterr()
assert captured.out == 'Auth invalid\n'
assert captured.out == "Auth invalid\n"
await script_auth.validate_login(
hass, provider, Mock(username='invalid-user', password='test-pass'))
hass, provider, Mock(username="invalid-user", password="test-pass")
)
captured = capsys.readouterr()
assert captured.out == 'Auth invalid\n'
assert captured.out == "Auth invalid\n"
async def test_change_password(hass, provider, capsys, hass_storage):
"""Test we can change a password."""
data = provider.data
data.add_auth('test-user', 'test-pass')
data.add_auth("test-user", "test-pass")
await script_auth.change_password(
hass, provider, Mock(username='test-user', new_password='new-pass'))
hass, provider, Mock(username="test-user", new_password="new-pass")
)
assert len(hass_storage[hass_auth.STORAGE_KEY]['data']['users']) == 1
assert len(hass_storage[hass_auth.STORAGE_KEY]["data"]["users"]) == 1
captured = capsys.readouterr()
assert captured.out == 'Password changed\n'
data.validate_login('test-user', 'new-pass')
assert captured.out == "Password changed\n"
data.validate_login("test-user", "new-pass")
with pytest.raises(hass_auth.InvalidAuth):
data.validate_login('test-user', 'test-pass')
data.validate_login("test-user", "test-pass")
async def test_change_password_invalid_user(hass, provider, capsys,
hass_storage):
async def test_change_password_invalid_user(hass, provider, capsys, hass_storage):
"""Test changing password of non-existing user."""
data = provider.data
data.add_auth('test-user', 'test-pass')
data.add_auth("test-user", "test-pass")
await script_auth.change_password(
hass, provider, Mock(username='invalid-user', new_password='new-pass'))
hass, provider, Mock(username="invalid-user", new_password="new-pass")
)
assert hass_auth.STORAGE_KEY not in hass_storage
captured = capsys.readouterr()
assert captured.out == 'User not found\n'
data.validate_login('test-user', 'test-pass')
assert captured.out == "User not found\n"
data.validate_login("test-user", "test-pass")
with pytest.raises(hass_auth.InvalidAuth):
data.validate_login('invalid-user', 'new-pass')
data.validate_login("invalid-user", "new-pass")
def test_parsing_args(loop):
@@ -115,12 +116,12 @@ def test_parsing_args(loop):
"""Mock function to be called."""
nonlocal called
called = True
assert provider.hass.config.config_dir == '/somewhere/config'
assert provider.hass.config.config_dir == "/somewhere/config"
assert args2 is args
args = Mock(config='/somewhere/config', func=mock_func)
args = Mock(config="/somewhere/config", func=mock_func)
with patch('argparse.ArgumentParser.parse_args', return_value=args):
with patch("argparse.ArgumentParser.parse_args", return_value=args):
script_auth.run(None)
assert called, 'Mock function did not get called'
assert called, "Mock function did not get called"

View File

@@ -10,161 +10,144 @@ from tests.common import get_test_config_dir, patch_yaml_files
_LOGGER = logging.getLogger(__name__)
BASE_CONFIG = (
'homeassistant:\n'
' name: Home\n'
' latitude: -26.107361\n'
' longitude: 28.054500\n'
' elevation: 1600\n'
' unit_system: metric\n'
' time_zone: GMT\n'
'\n\n'
"homeassistant:\n"
" name: Home\n"
" latitude: -26.107361\n"
" longitude: 28.054500\n"
" elevation: 1600\n"
" unit_system: metric\n"
" time_zone: GMT\n"
"\n\n"
)
BAD_CORE_CONFIG = (
'homeassistant:\n'
' unit_system: bad\n'
'\n\n'
)
BAD_CORE_CONFIG = "homeassistant:\n" " unit_system: bad\n" "\n\n"
def normalize_yaml_files(check_dict):
"""Remove configuration path from ['yaml_files']."""
root = get_test_config_dir()
return [key.replace(root, '...')
for key in sorted(check_dict['yaml_files'].keys())]
return [key.replace(root, "...") for key in sorted(check_dict["yaml_files"].keys())]
@patch('os.path.isfile', return_value=True)
@patch("os.path.isfile", return_value=True)
def test_bad_core_config(isfile_patch, loop):
"""Test a bad core config setup."""
files = {
YAML_CONFIG_FILE: BAD_CORE_CONFIG,
}
files = {YAML_CONFIG_FILE: BAD_CORE_CONFIG}
with patch_yaml_files(files):
res = check_config.check(get_test_config_dir())
assert res['except'].keys() == {'homeassistant'}
assert res['except']['homeassistant'][1] == {'unit_system': 'bad'}
assert res["except"].keys() == {"homeassistant"}
assert res["except"]["homeassistant"][1] == {"unit_system": "bad"}
@patch('os.path.isfile', return_value=True)
@patch("os.path.isfile", return_value=True)
def test_config_platform_valid(isfile_patch, loop):
"""Test a valid platform setup."""
files = {
YAML_CONFIG_FILE: BASE_CONFIG + 'light:\n platform: demo',
}
files = {YAML_CONFIG_FILE: BASE_CONFIG + "light:\n platform: demo"}
with patch_yaml_files(files):
res = check_config.check(get_test_config_dir())
assert res['components'].keys() == {'homeassistant', 'light'}
assert res['components']['light'] == [{'platform': 'demo'}]
assert res['except'] == {}
assert res['secret_cache'] == {}
assert res['secrets'] == {}
assert len(res['yaml_files']) == 1
assert res["components"].keys() == {"homeassistant", "light"}
assert res["components"]["light"] == [{"platform": "demo"}]
assert res["except"] == {}
assert res["secret_cache"] == {}
assert res["secrets"] == {}
assert len(res["yaml_files"]) == 1
@patch('os.path.isfile', return_value=True)
@patch("os.path.isfile", return_value=True)
def test_component_platform_not_found(isfile_patch, loop):
"""Test errors if component or platform not found."""
# Make sure they don't exist
files = {
YAML_CONFIG_FILE: BASE_CONFIG + 'beer:',
}
files = {YAML_CONFIG_FILE: BASE_CONFIG + "beer:"}
with patch_yaml_files(files):
res = check_config.check(get_test_config_dir())
assert res['components'].keys() == {'homeassistant'}
assert res['except'] == {
check_config.ERROR_STR: ['Integration not found: beer']}
assert res['secret_cache'] == {}
assert res['secrets'] == {}
assert len(res['yaml_files']) == 1
assert res["components"].keys() == {"homeassistant"}
assert res["except"] == {
check_config.ERROR_STR: ["Integration not found: beer"]
}
assert res["secret_cache"] == {}
assert res["secrets"] == {}
assert len(res["yaml_files"]) == 1
files = {
YAML_CONFIG_FILE: BASE_CONFIG + 'light:\n platform: beer',
}
files = {YAML_CONFIG_FILE: BASE_CONFIG + "light:\n platform: beer"}
with patch_yaml_files(files):
res = check_config.check(get_test_config_dir())
assert res['components'].keys() == {'homeassistant', 'light'}
assert res['components']['light'] == []
assert res['except'] == {
assert res["components"].keys() == {"homeassistant", "light"}
assert res["components"]["light"] == []
assert res["except"] == {
check_config.ERROR_STR: [
'Integration beer not found when trying to verify its '
'light platform.',
]}
assert res['secret_cache'] == {}
assert res['secrets'] == {}
assert len(res['yaml_files']) == 1
"Integration beer not found when trying to verify its "
"light platform."
]
}
assert res["secret_cache"] == {}
assert res["secrets"] == {}
assert len(res["yaml_files"]) == 1
@patch('os.path.isfile', return_value=True)
@patch("os.path.isfile", return_value=True)
def test_secrets(isfile_patch, loop):
"""Test secrets config checking method."""
secrets_path = get_test_config_dir('secrets.yaml')
secrets_path = get_test_config_dir("secrets.yaml")
files = {
get_test_config_dir(YAML_CONFIG_FILE): BASE_CONFIG + (
'http:\n'
' api_password: !secret http_pw'),
secrets_path: (
'logger: debug\n'
'http_pw: abc123'),
get_test_config_dir(YAML_CONFIG_FILE): BASE_CONFIG
+ ("http:\n" " api_password: !secret http_pw"),
secrets_path: ("logger: debug\n" "http_pw: abc123"),
}
with patch_yaml_files(files):
res = check_config.check(get_test_config_dir(), True)
assert res['except'] == {}
assert res['components'].keys() == {'homeassistant', 'http'}
assert res['components']['http'] == {
'api_password': 'abc123',
'cors_allowed_origins': [],
'ip_ban_enabled': True,
'login_attempts_threshold': -1,
'server_host': '0.0.0.0',
'server_port': 8123,
'trusted_networks': [],
'ssl_profile': 'modern',
assert res["except"] == {}
assert res["components"].keys() == {"homeassistant", "http"}
assert res["components"]["http"] == {
"api_password": "abc123",
"cors_allowed_origins": [],
"ip_ban_enabled": True,
"login_attempts_threshold": -1,
"server_host": "0.0.0.0",
"server_port": 8123,
"trusted_networks": [],
"ssl_profile": "modern",
}
assert res['secret_cache'] == {secrets_path: {'http_pw': 'abc123'}}
assert res['secrets'] == {'http_pw': 'abc123'}
assert res["secret_cache"] == {secrets_path: {"http_pw": "abc123"}}
assert res["secrets"] == {"http_pw": "abc123"}
assert normalize_yaml_files(res) == [
'.../configuration.yaml', '.../secrets.yaml']
".../configuration.yaml",
".../secrets.yaml",
]
@patch('os.path.isfile', return_value=True)
@patch("os.path.isfile", return_value=True)
def test_package_invalid(isfile_patch, loop):
"""Test a valid platform setup."""
files = {
YAML_CONFIG_FILE: BASE_CONFIG + (
' packages:\n'
' p1:\n'
' group: ["a"]'),
YAML_CONFIG_FILE: BASE_CONFIG
+ (" packages:\n" " p1:\n" ' group: ["a"]')
}
with patch_yaml_files(files):
res = check_config.check(get_test_config_dir())
assert res['except'].keys() == {'homeassistant.packages.p1.group'}
assert res['except']['homeassistant.packages.p1.group'][1] == \
{'group': ['a']}
assert len(res['except']) == 1
assert res['components'].keys() == {'homeassistant'}
assert len(res['components']) == 1
assert res['secret_cache'] == {}
assert res['secrets'] == {}
assert len(res['yaml_files']) == 1
assert res["except"].keys() == {"homeassistant.packages.p1.group"}
assert res["except"]["homeassistant.packages.p1.group"][1] == {"group": ["a"]}
assert len(res["except"]) == 1
assert res["components"].keys() == {"homeassistant"}
assert len(res["components"]) == 1
assert res["secret_cache"] == {}
assert res["secrets"] == {}
assert len(res["yaml_files"]) == 1
def test_bootstrap_error(loop):
"""Test a valid platform setup."""
files = {
YAML_CONFIG_FILE: BASE_CONFIG + 'automation: !include no.yaml',
}
files = {YAML_CONFIG_FILE: BASE_CONFIG + "automation: !include no.yaml"}
with patch_yaml_files(files):
res = check_config.check(get_test_config_dir(YAML_CONFIG_FILE))
err = res['except'].pop(check_config.ERROR_STR)
err = res["except"].pop(check_config.ERROR_STR)
assert len(err) == 1
assert res['except'] == {}
assert res['components'] == {} # No components, load failed
assert res['secret_cache'] == {}
assert res['secrets'] == {}
assert res['yaml_files'] == {}
assert res["except"] == {}
assert res["components"] == {} # No components, load failed
assert res["secret_cache"] == {}
assert res["secrets"] == {}
assert res["yaml_files"] == {}

View File

@@ -4,12 +4,11 @@ from unittest.mock import patch
import homeassistant.scripts as scripts
@patch('homeassistant.scripts.get_default_config_dir',
return_value='/default')
@patch("homeassistant.scripts.get_default_config_dir", return_value="/default")
def test_config_per_platform(mock_def):
"""Test config per platform method."""
assert scripts.get_default_config_dir() == '/default'
assert scripts.extract_config_dir() == '/default'
assert scripts.extract_config_dir(['']) == '/default'
assert scripts.extract_config_dir(['-c', '/arg']) == '/arg'
assert scripts.extract_config_dir(['--config', '/a']) == '/a'
assert scripts.get_default_config_dir() == "/default"
assert scripts.extract_config_dir() == "/default"
assert scripts.extract_config_dir([""]) == "/default"
assert scripts.extract_config_dir(["-c", "/arg"]) == "/arg"
assert scripts.extract_config_dir(["--config", "/a"]) == "/a"