init home-assistant
This commit is contained in:
1
home-assistant/tests/scripts/__init__.py
Normal file
1
home-assistant/tests/scripts/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""Tests for the scripts."""
|
||||
166
home-assistant/tests/scripts/test_auth.py
Normal file
166
home-assistant/tests/scripts/test_auth.py
Normal file
@@ -0,0 +1,166 @@
|
||||
"""Test the auth script to manage local users."""
|
||||
|
||||
import argparse
|
||||
from asyncio import AbstractEventLoop
|
||||
from collections.abc import Generator
|
||||
import logging
|
||||
from typing import Any
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.auth.providers import homeassistant as hass_auth
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.scripts import auth as script_auth
|
||||
|
||||
from tests.common import register_auth_provider
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def reset_log_level() -> Generator[None]:
|
||||
"""Reset log level after each test case."""
|
||||
logger = logging.getLogger("homeassistant.core")
|
||||
orig_level = logger.level
|
||||
yield
|
||||
logger.setLevel(orig_level)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def provider(hass: HomeAssistant) -> hass_auth.HassAuthProvider:
|
||||
"""Home Assistant auth provider."""
|
||||
provider = hass.loop.run_until_complete(
|
||||
register_auth_provider(hass, {"type": "homeassistant"})
|
||||
)
|
||||
hass.loop.run_until_complete(provider.async_initialize())
|
||||
return provider
|
||||
|
||||
|
||||
async def test_list_user(
|
||||
hass: HomeAssistant,
|
||||
provider: hass_auth.HassAuthProvider,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""Test we can list users."""
|
||||
data = provider.data
|
||||
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 == "test-user\nsecond-user\n\nTotal users: 2\n"
|
||||
|
||||
|
||||
async def test_add_user(
|
||||
hass: HomeAssistant,
|
||||
provider: hass_auth.HassAuthProvider,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
hass_storage: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test we can add a user."""
|
||||
data = provider.data
|
||||
await script_auth.add_user(
|
||||
hass, provider, Mock(username="paulus", password="test-pass")
|
||||
)
|
||||
|
||||
assert len(hass_storage[hass_auth.STORAGE_KEY]["data"]["users"]) == 1
|
||||
|
||||
captured = capsys.readouterr()
|
||||
assert captured.out == "Auth created\n"
|
||||
|
||||
assert len(data.users) == 1
|
||||
data.validate_login("paulus", "test-pass")
|
||||
|
||||
|
||||
async def test_validate_login(
|
||||
hass: HomeAssistant,
|
||||
provider: hass_auth.HassAuthProvider,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""Test we can validate a user login."""
|
||||
data = provider.data
|
||||
data.add_auth("test-user", "test-pass")
|
||||
|
||||
await script_auth.validate_login(
|
||||
hass, provider, Mock(username="test-user", password="test-pass")
|
||||
)
|
||||
captured = capsys.readouterr()
|
||||
assert captured.out == "Auth valid\n"
|
||||
|
||||
await script_auth.validate_login(
|
||||
hass, provider, Mock(username="test-user", password="invalid-pass")
|
||||
)
|
||||
captured = capsys.readouterr()
|
||||
assert captured.out == "Auth invalid\n"
|
||||
|
||||
await script_auth.validate_login(
|
||||
hass, provider, Mock(username="invalid-user", password="test-pass")
|
||||
)
|
||||
captured = capsys.readouterr()
|
||||
assert captured.out == "Auth invalid\n"
|
||||
|
||||
|
||||
async def test_change_password(
|
||||
hass: HomeAssistant,
|
||||
provider: hass_auth.HassAuthProvider,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
hass_storage: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test we can change a password."""
|
||||
data = provider.data
|
||||
data.add_auth("test-user", "test-pass")
|
||||
|
||||
await script_auth.change_password(
|
||||
hass, provider, Mock(username="test-user", new_password="new-pass")
|
||||
)
|
||||
|
||||
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")
|
||||
with pytest.raises(hass_auth.InvalidAuth):
|
||||
data.validate_login("test-user", "test-pass")
|
||||
|
||||
|
||||
async def test_change_password_invalid_user(
|
||||
hass: HomeAssistant,
|
||||
provider: hass_auth.HassAuthProvider,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
hass_storage: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test changing password of non-existing user."""
|
||||
data = provider.data
|
||||
data.add_auth("test-user", "test-pass")
|
||||
|
||||
await script_auth.change_password(
|
||||
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")
|
||||
with pytest.raises(hass_auth.InvalidAuth):
|
||||
data.validate_login("invalid-user", "new-pass")
|
||||
|
||||
|
||||
def test_parsing_args(event_loop: AbstractEventLoop) -> None:
|
||||
"""Test we parse args correctly."""
|
||||
called = False
|
||||
|
||||
async def mock_func(
|
||||
hass: HomeAssistant, provider: hass_auth.AuthProvider, args2: argparse.Namespace
|
||||
) -> None:
|
||||
"""Mock function to be called."""
|
||||
nonlocal called
|
||||
called = True
|
||||
assert provider.hass.config.config_dir == "/somewhere/config"
|
||||
assert args2 is args
|
||||
|
||||
args = Mock(config="/somewhere/config", func=mock_func)
|
||||
|
||||
with patch("argparse.ArgumentParser.parse_args", return_value=args):
|
||||
script_auth.run(None)
|
||||
|
||||
assert called, "Mock function did not get called"
|
||||
182
home-assistant/tests/scripts/test_check_config.py
Normal file
182
home-assistant/tests/scripts/test_check_config.py
Normal file
@@ -0,0 +1,182 @@
|
||||
"""Test check_config script."""
|
||||
|
||||
import logging
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.config import YAML_CONFIG_FILE
|
||||
from homeassistant.scripts import check_config
|
||||
|
||||
from tests.common import get_test_config_dir
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
BAD_CORE_CONFIG = "homeassistant:\n unit_system: bad\n\n\n"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def reset_log_level():
|
||||
"""Reset log level after each test case."""
|
||||
logger = logging.getLogger("homeassistant.loader")
|
||||
orig_level = logger.level
|
||||
yield
|
||||
logger.setLevel(orig_level)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def apply_stop_hass(stop_hass: None) -> None:
|
||||
"""Make sure all hass are stopped."""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_is_file():
|
||||
"""Mock is_file."""
|
||||
# All files exist except for the old entity registry file
|
||||
with patch(
|
||||
"os.path.isfile", lambda path: not path.endswith("entity_registry.yaml")
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
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())]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("hass_config_yaml", [BAD_CORE_CONFIG])
|
||||
@pytest.mark.usefixtures("mock_is_file", "event_loop", "mock_hass_config_yaml")
|
||||
def test_bad_core_config() -> None:
|
||||
"""Test a bad core config setup."""
|
||||
res = check_config.check(get_test_config_dir())
|
||||
assert res["except"].keys() == {"homeassistant"}
|
||||
assert res["except"]["homeassistant"][1] == {"unit_system": "bad"}
|
||||
assert res["warn"] == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("hass_config_yaml", [BASE_CONFIG + "light:\n platform: demo"])
|
||||
@pytest.mark.usefixtures("mock_is_file", "event_loop", "mock_hass_config_yaml")
|
||||
def test_config_platform_valid() -> None:
|
||||
"""Test a valid platform setup."""
|
||||
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 res["warn"] == {}
|
||||
assert len(res["yaml_files"]) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("hass_config_yaml", "platforms", "error"),
|
||||
[
|
||||
(
|
||||
BASE_CONFIG + "beer:",
|
||||
{"homeassistant"},
|
||||
"Integration error: beer - Integration 'beer' not found.",
|
||||
),
|
||||
(
|
||||
BASE_CONFIG + "light:\n platform: beer",
|
||||
{"homeassistant", "light"},
|
||||
(
|
||||
"Platform error 'light' from integration 'beer' - "
|
||||
"Integration 'beer' not found."
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("mock_is_file", "event_loop", "mock_hass_config_yaml")
|
||||
def test_component_platform_not_found(platforms: set[str], error: str) -> None:
|
||||
"""Test errors if component or platform not found."""
|
||||
# Make sure they don't exist
|
||||
res = check_config.check(get_test_config_dir())
|
||||
assert res["components"].keys() == platforms
|
||||
assert res["except"] == {}
|
||||
assert res["secret_cache"] == {}
|
||||
assert res["secrets"] == {}
|
||||
assert res["warn"] == {check_config.WARNING_STR: [error]}
|
||||
assert len(res["yaml_files"]) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"hass_config_yaml_files",
|
||||
[
|
||||
{
|
||||
get_test_config_dir(YAML_CONFIG_FILE): BASE_CONFIG
|
||||
+ "http:\n cors_allowed_origins: !secret http_pw",
|
||||
get_test_config_dir(
|
||||
"secrets.yaml"
|
||||
): "logger: debug\nhttp_pw: http://google.com",
|
||||
}
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("mock_is_file", "event_loop", "mock_hass_config_yaml")
|
||||
def test_secrets() -> None:
|
||||
"""Test secrets config checking method."""
|
||||
res = check_config.check(get_test_config_dir(), True)
|
||||
|
||||
assert res["except"] == {}
|
||||
assert res["components"].keys() == {"homeassistant", "http"}
|
||||
assert res["components"]["http"] == {
|
||||
"cors_allowed_origins": ["http://google.com"],
|
||||
"ip_ban_enabled": True,
|
||||
"login_attempts_threshold": -1,
|
||||
"server_port": 8123,
|
||||
"ssl_profile": "modern",
|
||||
"use_x_frame_options": True,
|
||||
"server_host": ["0.0.0.0", "::"],
|
||||
}
|
||||
assert res["secret_cache"] == {
|
||||
get_test_config_dir("secrets.yaml"): {"http_pw": "http://google.com"}
|
||||
}
|
||||
assert res["secrets"] == {"http_pw": "http://google.com"}
|
||||
assert res["warn"] == {}
|
||||
assert normalize_yaml_files(res) == [
|
||||
".../configuration.yaml",
|
||||
".../secrets.yaml",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"hass_config_yaml", [BASE_CONFIG + ' packages:\n p1:\n group: ["a"]']
|
||||
)
|
||||
@pytest.mark.usefixtures("mock_is_file", "event_loop", "mock_hass_config_yaml")
|
||||
def test_package_invalid() -> None:
|
||||
"""Test an invalid package."""
|
||||
res = check_config.check(get_test_config_dir())
|
||||
|
||||
assert res["except"] == {}
|
||||
assert res["components"].keys() == {"homeassistant"}
|
||||
assert res["secret_cache"] == {}
|
||||
assert res["secrets"] == {}
|
||||
assert res["warn"].keys() == {"homeassistant.packages.p1.group"}
|
||||
assert res["warn"]["homeassistant.packages.p1.group"][1] == {"group": ["a"]}
|
||||
assert len(res["yaml_files"]) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"hass_config_yaml", [BASE_CONFIG + "automation: !include no.yaml"]
|
||||
)
|
||||
@pytest.mark.usefixtures("event_loop", "mock_hass_config_yaml")
|
||||
def test_bootstrap_error() -> None:
|
||||
"""Test a valid platform setup."""
|
||||
res = check_config.check(get_test_config_dir(YAML_CONFIG_FILE))
|
||||
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["warn"] == {}
|
||||
assert res["yaml_files"] == {}
|
||||
15
home-assistant/tests/scripts/test_init.py
Normal file
15
home-assistant/tests/scripts/test_init.py
Normal file
@@ -0,0 +1,15 @@
|
||||
"""Test script init."""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from homeassistant import scripts
|
||||
|
||||
|
||||
@patch("homeassistant.scripts.get_default_config_dir", return_value="/default")
|
||||
def test_config_per_platform(mock_def) -> None:
|
||||
"""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"
|
||||
Reference in New Issue
Block a user