init home-assistant

This commit is contained in:
2026-11-19 15:15:32 -05:00
parent 2e81d9d300
commit feec6ef9fb
19230 changed files with 3335526 additions and 0 deletions

View File

@@ -0,0 +1 @@
"""Tests for Home Assistant."""

View File

@@ -0,0 +1 @@
"""Tests for the Home Assistant auth module."""

View File

@@ -0,0 +1 @@
"""Tests for the multi-factor auth modules."""

View File

@@ -0,0 +1,157 @@
"""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 homeassistant.core import HomeAssistant
from tests.common import MockUser
async def test_validate(hass: HomeAssistant) -> None:
"""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_validate("test-user", {"pin": "123456"})
assert result is True
result = await auth_module.async_validate("test-user", {"pin": "invalid"})
assert result is False
result = await auth_module.async_validate("invalid-user", {"pin": "123456"})
assert result is False
async def test_setup_user(hass: HomeAssistant) -> None:
"""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_validate("test-user", {"pin": "123456"})
assert result is True
async def test_depose_user(hass: HomeAssistant) -> None:
"""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: HomeAssistant) -> None:
"""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: HomeAssistant) -> None:
"""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.FlowResultType.FORM
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"username": "incorrect-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.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.FlowResultType.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.FlowResultType.FORM
assert result["step_id"] == "mfa"
assert result["data_schema"].schema.get("pin") is str
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"pin": "invalid-code"}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"]["base"] == "invalid_code"
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"pin": "123456"}
)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["data"].id == "mock-id"
async def test_setup_flow(hass: HomeAssistant) -> None:
"""Test validating pin."""
auth_module = await auth_mfa_module_from_config(
hass,
{
"type": "insecure_example",
"data": [{"user_id": "test-user", "pin": "123456"}],
},
)
flow = await auth_module.async_setup_flow("new-user")
result = await flow.async_step_init()
assert result["type"] == data_entry_flow.FlowResultType.FORM
result = await flow.async_step_init({"pin": "abcdefg"})
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert auth_module._data[1]["user_id"] == "new-user"
assert auth_module._data[1]["pin"] == "abcdefg"

View File

@@ -0,0 +1,401 @@
"""Test the HMAC-based One Time Password (MFA) auth module."""
import asyncio
from unittest.mock import patch
from homeassistant import data_entry_flow
from homeassistant.auth import auth_manager_from_config, models as auth_models
from homeassistant.auth.mfa_modules import auth_mfa_module_from_config
from homeassistant.components.notify import NOTIFY_SERVICE_SCHEMA
from homeassistant.core import HomeAssistant
from tests.common import MockUser, async_mock_service
MOCK_CODE = "123456"
MOCK_CODE_2 = "654321"
async def test_validating_mfa(hass: HomeAssistant) -> None:
"""Test validating mfa code."""
notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"})
await notify_auth_module.async_setup_user("test-user", {"notify_service": "dummy"})
with patch("pyotp.HOTP.verify", return_value=True):
assert await notify_auth_module.async_validate("test-user", {"code": MOCK_CODE})
async def test_validating_mfa_invalid_code(hass: HomeAssistant) -> None:
"""Test validating an invalid mfa code."""
notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"})
await notify_auth_module.async_setup_user("test-user", {"notify_service": "dummy"})
with patch("pyotp.HOTP.verify", return_value=False):
assert (
await notify_auth_module.async_validate("test-user", {"code": MOCK_CODE})
is False
)
async def test_validating_mfa_invalid_user(hass: HomeAssistant) -> None:
"""Test validating an mfa code with invalid user."""
notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"})
await notify_auth_module.async_setup_user("test-user", {"notify_service": "dummy"})
assert (
await notify_auth_module.async_validate("invalid-user", {"code": MOCK_CODE})
is False
)
async def test_validating_mfa_counter(hass: HomeAssistant) -> None:
"""Test counter will move only after generate code."""
notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"})
await notify_auth_module.async_setup_user(
"test-user", {"counter": 0, "notify_service": "dummy"}
)
async_mock_service(hass, "notify", "dummy")
assert notify_auth_module._user_settings
notify_setting = list(notify_auth_module._user_settings.values())[0]
init_count = notify_setting.counter
assert init_count is not None
with patch("pyotp.HOTP.at", return_value=MOCK_CODE):
await notify_auth_module.async_initialize_login_mfa_step("test-user")
notify_setting = list(notify_auth_module._user_settings.values())[0]
after_generate_count = notify_setting.counter
assert after_generate_count != init_count
with patch("pyotp.HOTP.verify", return_value=True):
assert await notify_auth_module.async_validate("test-user", {"code": MOCK_CODE})
notify_setting = list(notify_auth_module._user_settings.values())[0]
assert after_generate_count == notify_setting.counter
with patch("pyotp.HOTP.verify", return_value=False):
assert (
await notify_auth_module.async_validate("test-user", {"code": MOCK_CODE})
is False
)
notify_setting = list(notify_auth_module._user_settings.values())[0]
assert after_generate_count == notify_setting.counter
async def test_setup_depose_user(hass: HomeAssistant) -> None:
"""Test set up and despose user."""
notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"})
await notify_auth_module.async_setup_user("test-user", {})
assert len(notify_auth_module._user_settings) == 1
await notify_auth_module.async_setup_user("test-user", {})
assert len(notify_auth_module._user_settings) == 1
await notify_auth_module.async_depose_user("test-user")
assert len(notify_auth_module._user_settings) == 0
await notify_auth_module.async_setup_user("test-user2", {"secret": "secret-code"})
assert len(notify_auth_module._user_settings) == 1
async def test_login_flow_validates_mfa(hass: HomeAssistant) -> None:
"""Test login flow with mfa enabled."""
hass.auth = await auth_manager_from_config(
hass,
[
{
"type": "insecure_example",
"users": [{"username": "test-user", "password": "test-pass"}],
}
],
[{"type": "notify"}],
)
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,
auth_models.Credentials(
id="mock-id",
auth_provider_type="insecure_example",
auth_provider_id=None,
data={"username": "test-user"},
is_new=False,
),
)
notify_calls = async_mock_service(
hass, "notify", "test-notify", NOTIFY_SERVICE_SCHEMA
)
await hass.auth.async_enable_user_mfa(
user, "notify", {"notify_service": "test-notify"}
)
provider = hass.auth.auth_providers[0]
result = await hass.auth.login_flow.async_init((provider.type, provider.id))
assert result["type"] == data_entry_flow.FlowResultType.FORM
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"username": "incorrect-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.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.FlowResultType.FORM
assert result["errors"]["base"] == "invalid_auth"
with patch("pyotp.HOTP.at", return_value=MOCK_CODE):
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"username": "test-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "mfa"
assert result["data_schema"].schema.get("code") is str
# wait service call finished
await hass.async_block_till_done()
assert len(notify_calls) == 1
notify_call = notify_calls[0]
assert notify_call.domain == "notify"
assert notify_call.service == "test-notify"
message = notify_call.data["message"]
assert MOCK_CODE in message
with patch("pyotp.HOTP.verify", return_value=False):
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"code": "invalid-code"}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "mfa"
assert result["errors"]["base"] == "invalid_code"
# wait service call finished
await hass.async_block_till_done()
# would not send new code, allow user retry
assert len(notify_calls) == 1
# retry twice
with (
patch("pyotp.HOTP.verify", return_value=False),
patch("pyotp.HOTP.at", return_value=MOCK_CODE_2),
):
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"code": "invalid-code"}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "mfa"
assert result["errors"]["base"] == "invalid_code"
# after the 3rd failure, flow abort
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"code": "invalid-code"}
)
assert result["type"] == data_entry_flow.FlowResultType.ABORT
assert result["reason"] == "too_many_retry"
# wait service call finished
await hass.async_block_till_done()
# restart login
result = await hass.auth.login_flow.async_init((provider.type, provider.id))
assert result["type"] == data_entry_flow.FlowResultType.FORM
with patch("pyotp.HOTP.at", return_value=MOCK_CODE):
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"username": "test-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "mfa"
assert result["data_schema"].schema.get("code") is str
# wait service call finished
await hass.async_block_till_done()
assert len(notify_calls) == 2
notify_call = notify_calls[1]
assert notify_call.domain == "notify"
assert notify_call.service == "test-notify"
message = notify_call.data["message"]
assert MOCK_CODE in message
with patch("pyotp.HOTP.verify", return_value=True):
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"code": MOCK_CODE}
)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["data"].id == "mock-id"
async def test_setup_user_notify_service(hass: HomeAssistant) -> None:
"""Test allow select notify service during mfa setup."""
notify_calls = async_mock_service(hass, "notify", "test1", NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, "notify", "test2", NOTIFY_SERVICE_SCHEMA)
notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"})
services = notify_auth_module.aync_get_available_notify_services()
assert services == ["test1", "test2"]
flow = await notify_auth_module.async_setup_flow("test-user")
step = await flow.async_step_init()
assert step["type"] == data_entry_flow.FlowResultType.FORM
assert step["step_id"] == "init"
schema = step["data_schema"]
schema({"notify_service": "test2"})
with patch("pyotp.HOTP.at", return_value=MOCK_CODE):
step = await flow.async_step_init({"notify_service": "test1"})
assert step["type"] == data_entry_flow.FlowResultType.FORM
assert step["step_id"] == "setup"
# wait service call finished
await hass.async_block_till_done()
assert len(notify_calls) == 1
notify_call = notify_calls[0]
assert notify_call.domain == "notify"
assert notify_call.service == "test1"
message = notify_call.data["message"]
assert MOCK_CODE in message
with patch("pyotp.HOTP.at", return_value=MOCK_CODE_2):
step = await flow.async_step_setup({"code": "invalid"})
assert step["type"] == data_entry_flow.FlowResultType.FORM
assert step["step_id"] == "setup"
assert step["errors"]["base"] == "invalid_code"
# wait service call finished
await hass.async_block_till_done()
assert len(notify_calls) == 2
notify_call = notify_calls[1]
assert notify_call.domain == "notify"
assert notify_call.service == "test1"
message = notify_call.data["message"]
assert MOCK_CODE_2 in message
with patch("pyotp.HOTP.verify", return_value=True):
step = await flow.async_step_setup({"code": MOCK_CODE_2})
assert step["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
async def test_include_exclude_config(hass: HomeAssistant) -> None:
"""Test allow include exclude config."""
async_mock_service(hass, "notify", "include1", NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, "notify", "include2", NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, "notify", "exclude1", NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, "notify", "exclude2", NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, "other", "include3", NOTIFY_SERVICE_SCHEMA)
async_mock_service(hass, "other", "exclude3", NOTIFY_SERVICE_SCHEMA)
notify_auth_module = await auth_mfa_module_from_config(
hass, {"type": "notify", "exclude": ["exclude1", "exclude2", "exclude3"]}
)
services = notify_auth_module.aync_get_available_notify_services()
assert services == ["include1", "include2"]
notify_auth_module = await auth_mfa_module_from_config(
hass, {"type": "notify", "include": ["include1", "include2", "include3"]}
)
services = notify_auth_module.aync_get_available_notify_services()
assert services == ["include1", "include2"]
# exclude has high priority than include
notify_auth_module = await auth_mfa_module_from_config(
hass,
{
"type": "notify",
"include": ["include1", "include2", "include3"],
"exclude": ["exclude1", "exclude2", "include2"],
},
)
services = notify_auth_module.aync_get_available_notify_services()
assert services == ["include1"]
async def test_setup_user_no_notify_service(hass: HomeAssistant) -> None:
"""Test setup flow abort if there is no available notify service."""
async_mock_service(hass, "notify", "test1", NOTIFY_SERVICE_SCHEMA)
notify_auth_module = await auth_mfa_module_from_config(
hass, {"type": "notify", "exclude": "test1"}
)
services = notify_auth_module.aync_get_available_notify_services()
assert services == []
flow = await notify_auth_module.async_setup_flow("test-user")
step = await flow.async_step_init()
assert step["type"] == data_entry_flow.FlowResultType.ABORT
assert step["reason"] == "no_available_service"
async def test_not_raise_exception_when_service_not_exist(hass: HomeAssistant) -> None:
"""Test login flow will not raise exception when notify service error."""
hass.auth = await auth_manager_from_config(
hass,
[
{
"type": "insecure_example",
"users": [{"username": "test-user", "password": "test-pass"}],
}
],
[{"type": "notify"}],
)
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,
auth_models.Credentials(
id="mock-id",
auth_provider_type="insecure_example",
auth_provider_id=None,
data={"username": "test-user"},
is_new=False,
),
)
await hass.auth.async_enable_user_mfa(
user, "notify", {"notify_service": "invalid-notify"}
)
provider = hass.auth.auth_providers[0]
result = await hass.auth.login_flow.async_init((provider.type, provider.id))
assert result["type"] == data_entry_flow.FlowResultType.FORM
with patch("pyotp.HOTP.at", return_value=MOCK_CODE):
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"username": "test-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.ABORT
assert result["reason"] == "unknown_error"
# wait service call finished
await hass.async_block_till_done()
async def test_race_condition_in_data_loading(hass: HomeAssistant) -> None:
"""Test race condition in the data loading."""
counter = 0
async def mock_load(_):
"""Mock homeassistant.helpers.storage.Store.async_load."""
nonlocal counter
counter += 1
await asyncio.sleep(0)
notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"})
with patch("homeassistant.helpers.storage.Store.async_load", new=mock_load):
task1 = notify_auth_module.async_validate("user", {"code": "value"})
task2 = notify_auth_module.async_validate("user", {"code": "value"})
results = await asyncio.gather(task1, task2, return_exceptions=True)
assert counter == 1
assert results[0] is False
assert results[1] is False

View File

@@ -0,0 +1,152 @@
"""Test the Time-based One Time Password (MFA) auth module."""
import asyncio
from unittest.mock import patch
from homeassistant import data_entry_flow
from homeassistant.auth import auth_manager_from_config, models as auth_models
from homeassistant.auth.mfa_modules import auth_mfa_module_from_config
from homeassistant.core import HomeAssistant
from tests.common import MockUser
MOCK_CODE = "123456"
async def test_validating_mfa(hass: HomeAssistant) -> None:
"""Test validating mfa code."""
totp_auth_module = await auth_mfa_module_from_config(hass, {"type": "totp"})
await totp_auth_module.async_setup_user("test-user", {})
with patch("pyotp.TOTP.verify", return_value=True):
assert await totp_auth_module.async_validate("test-user", {"code": MOCK_CODE})
async def test_validating_mfa_invalid_code(hass: HomeAssistant) -> None:
"""Test validating an invalid mfa code."""
totp_auth_module = await auth_mfa_module_from_config(hass, {"type": "totp"})
await totp_auth_module.async_setup_user("test-user", {})
with patch("pyotp.TOTP.verify", return_value=False):
assert (
await totp_auth_module.async_validate("test-user", {"code": MOCK_CODE})
is False
)
async def test_validating_mfa_invalid_user(hass: HomeAssistant) -> None:
"""Test validating an mfa code with invalid user."""
totp_auth_module = await auth_mfa_module_from_config(hass, {"type": "totp"})
await totp_auth_module.async_setup_user("test-user", {})
assert (
await totp_auth_module.async_validate("invalid-user", {"code": MOCK_CODE})
is False
)
async def test_setup_depose_user(hass: HomeAssistant) -> None:
"""Test despose user."""
totp_auth_module = await auth_mfa_module_from_config(hass, {"type": "totp"})
result = await totp_auth_module.async_setup_user("test-user", {})
assert len(totp_auth_module._users) == 1
result2 = await totp_auth_module.async_setup_user("test-user", {})
assert len(totp_auth_module._users) == 1
assert result != result2
await totp_auth_module.async_depose_user("test-user")
assert len(totp_auth_module._users) == 0
result = await totp_auth_module.async_setup_user(
"test-user2", {"secret": "secret-code"}
)
assert result == "secret-code"
assert len(totp_auth_module._users) == 1
async def test_login_flow_validates_mfa(hass: HomeAssistant) -> None:
"""Test login flow with mfa enabled."""
hass.auth = await auth_manager_from_config(
hass,
[
{
"type": "insecure_example",
"users": [{"username": "test-user", "password": "test-pass"}],
}
],
[{"type": "totp"}],
)
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,
auth_models.Credentials(
id="mock-id",
auth_provider_type="insecure_example",
auth_provider_id=None,
data={"username": "test-user"},
is_new=False,
),
)
await hass.auth.async_enable_user_mfa(user, "totp", {})
provider = hass.auth.auth_providers[0]
result = await hass.auth.login_flow.async_init((provider.type, provider.id))
assert result["type"] == data_entry_flow.FlowResultType.FORM
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"username": "incorrect-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.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.FlowResultType.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.FlowResultType.FORM
assert result["step_id"] == "mfa"
assert result["data_schema"].schema.get("code") is str
with patch("pyotp.TOTP.verify", return_value=False):
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"code": "invalid-code"}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "mfa"
assert result["errors"]["base"] == "invalid_code"
with patch("pyotp.TOTP.verify", return_value=True):
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"code": MOCK_CODE}
)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["data"].id == "mock-id"
async def test_race_condition_in_data_loading(hass: HomeAssistant) -> None:
"""Test race condition in the data loading."""
counter = 0
async def mock_load(_):
"""Mock of homeassistant.helpers.storage.Store.async_load."""
nonlocal counter
counter += 1
await asyncio.sleep(0)
totp_auth_module = await auth_mfa_module_from_config(hass, {"type": "totp"})
with patch("homeassistant.helpers.storage.Store.async_load", new=mock_load):
task1 = totp_auth_module.async_validate("user", {"code": "value"})
task2 = totp_auth_module.async_validate("user", {"code": "value"})
results = await asyncio.gather(task1, task2, return_exceptions=True)
assert counter == 1
assert results[0] is False
assert results[1] is False

View File

@@ -0,0 +1 @@
"""Tests for permissions."""

View File

@@ -0,0 +1,219 @@
"""Tests for entity permissions."""
import pytest
import voluptuous as vol
from homeassistant.auth.permissions.entities import (
ENTITY_POLICY_SCHEMA,
compile_entities,
)
from homeassistant.auth.permissions.models import PermissionLookup
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceEntry
from homeassistant.helpers.entity_registry import RegistryEntry
from tests.common import mock_device_registry, mock_registry
def test_entities_none() -> None:
"""Test entity ID policy."""
policy = None
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is False
def test_entities_empty() -> None:
"""Test entity ID policy."""
policy = {}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is False
def test_entities_false() -> None:
"""Test entity ID policy."""
policy = False
with pytest.raises(vol.Invalid):
ENTITY_POLICY_SCHEMA(policy)
def test_entities_true() -> None:
"""Test entity ID policy."""
policy = True
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
def test_entities_domains_true() -> None:
"""Test entity ID policy."""
policy = {"domains": True}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
def test_entities_domains_domain_true() -> None:
"""Test entity ID policy."""
policy = {"domains": {"light": True}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
assert compiled("switch.kitchen", "read") is False
def test_entities_domains_domain_false() -> None:
"""Test entity ID policy."""
policy = {"domains": {"light": False}}
with pytest.raises(vol.Invalid):
ENTITY_POLICY_SCHEMA(policy)
def test_entities_entity_ids_true() -> None:
"""Test entity ID policy."""
policy = {"entity_ids": True}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
def test_entities_entity_ids_false() -> None:
"""Test entity ID policy."""
policy = {"entity_ids": False}
with pytest.raises(vol.Invalid):
ENTITY_POLICY_SCHEMA(policy)
def test_entities_entity_ids_entity_id_true() -> None:
"""Test entity ID policy."""
policy = {"entity_ids": {"light.kitchen": True}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
assert compiled("switch.kitchen", "read") is False
def test_entities_entity_ids_entity_id_false() -> None:
"""Test entity ID policy."""
policy = {"entity_ids": {"light.kitchen": False}}
with pytest.raises(vol.Invalid):
ENTITY_POLICY_SCHEMA(policy)
def test_entities_control_only() -> None:
"""Test policy granting control only."""
policy = {"entity_ids": {"light.kitchen": {"read": True}}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
assert compiled("light.kitchen", "control") is False
assert compiled("light.kitchen", "edit") is False
def test_entities_read_control() -> None:
"""Test policy granting control only."""
policy = {"domains": {"light": {"read": True, "control": True}}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
assert compiled("light.kitchen", "control") is True
assert compiled("light.kitchen", "edit") is False
def test_entities_all_allow() -> None:
"""Test policy allowing all entities."""
policy = {"all": True}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
assert compiled("light.kitchen", "control") is True
assert compiled("switch.kitchen", "read") is True
def test_entities_all_read() -> None:
"""Test policy applying read to all entities."""
policy = {"all": {"read": True}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
assert compiled("light.kitchen", "control") is False
assert compiled("switch.kitchen", "read") is True
def test_entities_all_control() -> None:
"""Test entity ID policy applying control to all."""
policy = {"all": {"control": True}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is False
assert compiled("light.kitchen", "control") is True
assert compiled("switch.kitchen", "read") is False
assert compiled("switch.kitchen", "control") is True
def test_entities_device_id_boolean(hass: HomeAssistant) -> None:
"""Test entity ID policy applying control on device id."""
entity_registry = mock_registry(
hass,
{
"test_domain.allowed": RegistryEntry(
entity_id="test_domain.allowed",
unique_id="1234",
platform="test_platform",
device_id="mock-allowed-dev-id",
),
"test_domain.not_allowed": RegistryEntry(
entity_id="test_domain.not_allowed",
unique_id="5678",
platform="test_platform",
device_id="mock-not-allowed-dev-id",
),
},
)
device_registry = mock_device_registry(hass)
policy = {"device_ids": {"mock-allowed-dev-id": {"read": True}}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(
policy, PermissionLookup(entity_registry, device_registry)
)
assert compiled("test_domain.allowed", "read") is True
assert compiled("test_domain.allowed", "control") is False
assert compiled("test_domain.not_allowed", "read") is False
assert compiled("test_domain.not_allowed", "control") is False
def test_entities_areas_true() -> None:
"""Test entity ID policy for areas."""
policy = {"area_ids": True}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
def test_entities_areas_area_true(hass: HomeAssistant) -> None:
"""Test entity ID policy for areas with specific area."""
entity_registry = mock_registry(
hass,
{
"light.kitchen": RegistryEntry(
entity_id="light.kitchen",
unique_id="1234",
platform="test_platform",
device_id="mock-dev-id",
)
},
)
device_registry = mock_device_registry(
hass, {"mock-dev-id": DeviceEntry(id="mock-dev-id", area_id="mock-area-id")}
)
policy = {"area_ids": {"mock-area-id": {"read": True, "control": True}}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(
policy, PermissionLookup(entity_registry, device_registry)
)
assert compiled("light.kitchen", "read") is True
assert compiled("light.kitchen", "control") is True
assert compiled("light.kitchen", "edit") is False
assert compiled("switch.kitchen", "read") is False

View File

@@ -0,0 +1,27 @@
"""Tests for permissions merging."""
from homeassistant.auth.permissions.merge import merge_policies
def test_merging_permissions_true_rules_dict() -> None:
"""Test merging policy with two entities."""
policy1 = {
"something_else": True,
"entities": {"entity_ids": {"light.kitchen": True}},
}
policy2 = {"entities": {"entity_ids": True}}
assert merge_policies([policy1, policy2]) == {
"something_else": True,
"entities": {"entity_ids": True},
}
def test_merging_permissions_multiple_subcategories() -> None:
"""Test merging policy with two entities."""
policy1 = {"entities": None}
policy2 = {"entities": {"entity_ids": True}}
policy3 = {"entities": True}
assert merge_policies([policy1, policy2]) == policy2
assert merge_policies([policy1, policy3]) == policy3
assert merge_policies([policy2, policy3]) == policy3

View File

@@ -0,0 +1,40 @@
"""Test system policies."""
from homeassistant.auth.permissions import (
POLICY_SCHEMA,
PolicyPermissions,
system_policies,
)
def test_admin_policy() -> None:
"""Test admin policy works."""
# Make sure it's valid
POLICY_SCHEMA(system_policies.ADMIN_POLICY)
perms = PolicyPermissions(system_policies.ADMIN_POLICY, None)
assert perms.check_entity("light.kitchen", "read")
assert perms.check_entity("light.kitchen", "control")
assert perms.check_entity("light.kitchen", "edit")
def test_user_policy() -> None:
"""Test user policy works."""
# Make sure it's valid
POLICY_SCHEMA(system_policies.USER_POLICY)
perms = PolicyPermissions(system_policies.USER_POLICY, None)
assert perms.check_entity("light.kitchen", "read")
assert perms.check_entity("light.kitchen", "control")
assert perms.check_entity("light.kitchen", "edit")
def test_read_only_policy() -> None:
"""Test read only policy works."""
# Make sure it's valid
POLICY_SCHEMA(system_policies.READ_ONLY_POLICY)
perms = PolicyPermissions(system_policies.READ_ONLY_POLICY, None)
assert perms.check_entity("light.kitchen", "read")
assert not perms.check_entity("light.kitchen", "control")
assert not perms.check_entity("light.kitchen", "edit")

View File

@@ -0,0 +1,12 @@
"""Test the permission utils."""
from homeassistant.auth.permissions import util
def test_test_all() -> None:
"""Test if we can test the all group."""
for val in (None, {}, {"all": None}, {"all": {}}):
assert util.test_all(val, "read") is False
for val in (True, {"all": True}, {"all": {"read": True}}):
assert util.test_all(val, "read") is True

View File

@@ -0,0 +1 @@
"""Tests for the auth providers."""

View File

@@ -0,0 +1,164 @@
"""Tests for the command_line auth provider."""
import os
from unittest.mock import AsyncMock
import uuid
import pytest
from homeassistant import data_entry_flow
from homeassistant.auth import AuthManager, auth_store, models as auth_models
from homeassistant.auth.providers import command_line
from homeassistant.const import CONF_TYPE
from homeassistant.core import HomeAssistant
@pytest.fixture
async def store(hass: HomeAssistant) -> auth_store.AuthStore:
"""Mock store."""
store = auth_store.AuthStore(hass)
await store.async_load()
return store
@pytest.fixture
def provider(
hass: HomeAssistant, store: auth_store.AuthStore
) -> command_line.CommandLineAuthProvider:
"""Mock provider."""
return command_line.CommandLineAuthProvider(
hass,
store,
{
CONF_TYPE: "command_line",
command_line.CONF_COMMAND: os.path.join(
os.path.dirname(__file__), "test_command_line_cmd.sh"
),
command_line.CONF_ARGS: [],
command_line.CONF_META: False,
},
)
@pytest.fixture
def manager(
hass: HomeAssistant,
store: auth_store.AuthStore,
provider: command_line.CommandLineAuthProvider,
) -> AuthManager:
"""Mock manager."""
return AuthManager(hass, store, {(provider.type, provider.id): provider}, {})
async def test_create_new_credential(
manager: AuthManager, provider: command_line.CommandLineAuthProvider
) -> None:
"""Test that we create a new credential."""
credentials = await provider.async_get_or_create_credentials(
{"username": "good-user", "password": "good-pass"}
)
assert credentials.is_new is True
user = await manager.async_get_or_create_user(credentials)
assert user.is_active
assert len(user.groups) == 1
assert user.groups[0].id == "system-admin"
assert not user.local_only
async def test_match_existing_credentials(
provider: command_line.CommandLineAuthProvider,
) -> None:
"""See if we match existing users."""
existing = auth_models.Credentials(
id=uuid.uuid4(),
auth_provider_type="command_line",
auth_provider_id=None,
data={"username": "good-user"},
is_new=False,
)
provider.async_credentials = AsyncMock(return_value=[existing])
credentials = await provider.async_get_or_create_credentials(
{"username": "good-user", "password": "irrelevant"}
)
assert credentials is existing
async def test_invalid_username(provider: command_line.CommandLineAuthProvider) -> None:
"""Test we raise if incorrect user specified."""
with pytest.raises(command_line.InvalidAuthError):
await provider.async_validate_login("bad-user", "good-pass")
async def test_invalid_password(provider: command_line.CommandLineAuthProvider) -> None:
"""Test we raise if incorrect password specified."""
with pytest.raises(command_line.InvalidAuthError):
await provider.async_validate_login("good-user", "bad-pass")
async def test_good_auth(provider: command_line.CommandLineAuthProvider) -> None:
"""Test nothing is raised with good credentials."""
await provider.async_validate_login("good-user", "good-pass")
async def test_good_auth_with_meta(
manager: AuthManager, provider: command_line.CommandLineAuthProvider
) -> None:
"""Test metadata is added upon successful authentication."""
provider.config[command_line.CONF_ARGS] = ["--with-meta"]
provider.config[command_line.CONF_META] = True
await provider.async_validate_login("good-user", "good-pass")
credentials = await provider.async_get_or_create_credentials(
{"username": "good-user", "password": "good-pass"}
)
assert credentials.is_new is True
user = await manager.async_get_or_create_user(credentials)
assert user.name == "Bob"
assert user.is_active
assert len(user.groups) == 1
assert user.groups[0].id == "system-users"
assert user.local_only
async def test_utf_8_username_password(
provider: command_line.CommandLineAuthProvider,
) -> None:
"""Test that we create a new credential."""
credentials = await provider.async_get_or_create_credentials(
{"username": "ßßß", "password": "äöü"}
)
assert credentials.is_new is True
async def test_login_flow_validates(
provider: command_line.CommandLineAuthProvider,
) -> None:
"""Test login flow."""
flow = await provider.async_login_flow({})
result = await flow.async_step_init()
assert result["type"] == data_entry_flow.FlowResultType.FORM
result = await flow.async_step_init(
{"username": "bad-user", "password": "bad-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"]["base"] == "invalid_auth"
result = await flow.async_step_init(
{"username": "good-user", "password": "good-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["data"]["username"] == "good-user"
async def test_strip_username(provider: command_line.CommandLineAuthProvider) -> None:
"""Test authentication works with username with whitespace around."""
flow = await provider.async_login_flow({})
result = await flow.async_step_init(
{"username": "\t\ngood-user ", "password": "good-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["data"]["username"] == "good-user"

View File

@@ -0,0 +1,14 @@
#!/bin/sh
if [ "$username" = "good-user" ] && [ "$password" = "good-pass" ]; then
echo "Auth should succeed." >&2
if [ "$1" = "--with-meta" ]; then
echo "name=Bob"
echo "group=system-users"
echo "local_only=true"
fi
exit 0
fi
echo "Auth should fail." >&2
exit 1

View File

@@ -0,0 +1,481 @@
"""Test the Home Assistant local auth provider."""
import asyncio
from typing import Any
from unittest.mock import Mock, patch
import pytest
import voluptuous as vol
from homeassistant import data_entry_flow
from homeassistant.auth import auth_manager_from_config, auth_store
from homeassistant.auth.providers import (
auth_provider_from_config,
homeassistant as hass_auth,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import issue_registry as ir
from homeassistant.setup import async_setup_component
@pytest.fixture
def data(hass: HomeAssistant) -> hass_auth.Data:
"""Create a loaded data class."""
data = hass_auth.Data(hass)
hass.loop.run_until_complete(data.async_load())
return data
@pytest.fixture
def legacy_data(hass: HomeAssistant) -> hass_auth.Data:
"""Create a loaded legacy data class."""
data = hass_auth.Data(hass)
hass.loop.run_until_complete(data.async_load())
data.is_legacy = True
return data
@pytest.fixture
async def load_auth_component(hass: HomeAssistant) -> None:
"""Load the auth component for translations."""
await async_setup_component(hass, "auth", {})
async def test_validating_password_invalid_user(data: hass_auth.Data) -> None:
"""Test validating an invalid user."""
with pytest.raises(hass_auth.InvalidAuth):
data.validate_login("non-existing", "pw")
async def test_not_allow_set_id() -> None:
"""Test we are not allowed to set an ID in config."""
hass = Mock()
hass.data = {}
with pytest.raises(vol.Invalid):
await auth_provider_from_config(
hass, None, {"type": "homeassistant", "id": "invalid"}
)
async def test_new_users_populate_values(
hass: HomeAssistant, data: hass_auth.Data
) -> None:
"""Test that we populate data for new users."""
data.add_auth("hello", "test-pass")
await data.async_save()
manager = await auth_manager_from_config(hass, [{"type": "homeassistant"}], [])
provider = manager.auth_providers[0]
credentials = await provider.async_get_or_create_credentials({"username": "hello"})
user = await manager.async_get_or_create_user(credentials)
assert user.name == "hello"
assert user.is_active
async def test_changing_password_raises_invalid_user(data: hass_auth.Data) -> None:
"""Test that changing password raises invalid user."""
with pytest.raises(hass_auth.InvalidUser):
data.change_password("non-existing", "pw")
# Modern mode
async def test_adding_user(data: hass_auth.Data) -> None:
"""Test adding a user."""
data.add_auth("test-user", "test-pass")
data.validate_login(" test-user ", "test-pass")
@pytest.mark.parametrize("username", ["test-user ", "TEST-USER"])
@pytest.mark.usefixtures("load_auth_component")
def test_adding_user_not_normalized(data: hass_auth.Data, username: str) -> None:
"""Test adding a user."""
with pytest.raises(
hass_auth.InvalidUsername, match=f'Username "{username}" is not normalized'
):
data.add_auth(username, "test-pass")
@pytest.mark.usefixtures("load_auth_component")
def test_adding_user_duplicate_username(data: hass_auth.Data) -> None:
"""Test adding a user with duplicate username."""
data.add_auth("test-user", "test-pass")
with pytest.raises(
hass_auth.InvalidUsername, match='Username "test-user" already exists'
):
data.add_auth("test-user", "other-pass")
async def test_validating_password_invalid_password(data: hass_auth.Data) -> None:
"""Test validating an invalid password."""
data.add_auth("test-user", "test-pass")
with pytest.raises(hass_auth.InvalidAuth):
data.validate_login(" test-user ", "invalid-pass")
with pytest.raises(hass_auth.InvalidAuth):
data.validate_login("test-user", "test-pass ")
with pytest.raises(hass_auth.InvalidAuth):
data.validate_login("test-user", "Test-pass")
async def test_changing_password(data: hass_auth.Data) -> None:
"""Test adding a user."""
data.add_auth("test-user", "test-pass")
data.change_password("TEST-USER ", "new-pass")
with pytest.raises(hass_auth.InvalidAuth):
data.validate_login("test-user", "test-pass")
data.validate_login("test-UsEr", "new-pass")
async def test_login_flow_validates(data: hass_auth.Data, hass: HomeAssistant) -> None:
"""Test login flow."""
data.add_auth("test-user", "test-pass")
await data.async_save()
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.FlowResultType.FORM
result = await flow.async_step_init(
{"username": "incorrect-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"]["base"] == "invalid_auth"
result = await flow.async_step_init(
{"username": "TEST-user ", "password": "incorrect-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"]["base"] == "invalid_auth"
result = await flow.async_step_init(
{"username": "test-USER", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["data"]["username"] == "test-USER"
async def test_saving_loading(data: hass_auth.Data, hass: HomeAssistant) -> None:
"""Test saving and loading JSON."""
data.add_auth("test-user", "test-pass")
data.add_auth("second-user", "second-pass")
await data.async_save()
data = hass_auth.Data(hass)
await data.async_load()
data.validate_login("test-user ", "test-pass")
data.validate_login("second-user ", "second-pass")
async def test_get_or_create_credentials(
hass: HomeAssistant, data: hass_auth.Data
) -> None:
"""Test that we can get or create credentials."""
manager = await auth_manager_from_config(hass, [{"type": "homeassistant"}], [])
provider = manager.auth_providers[0]
provider.data = data
credentials1 = await provider.async_get_or_create_credentials({"username": "hello"})
with patch.object(provider, "async_credentials", return_value=[credentials1]):
credentials2 = await provider.async_get_or_create_credentials(
{"username": "hello "}
)
assert credentials1 is credentials2
# Legacy mode
async def test_legacy_adding_user(legacy_data: hass_auth.Data) -> None:
"""Test in legacy mode adding a user."""
legacy_data.add_auth("test-user", "test-pass")
legacy_data.validate_login("test-user", "test-pass")
async def test_legacy_validating_password_invalid_password(
legacy_data: hass_auth.Data,
) -> None:
"""Test in legacy mode validating an invalid password."""
legacy_data.add_auth("test-user", "test-pass")
with pytest.raises(hass_auth.InvalidAuth):
legacy_data.validate_login("test-user", "invalid-pass")
async def test_legacy_changing_password(legacy_data: hass_auth.Data) -> None:
"""Test in legacy mode adding a user."""
user = "test-user"
legacy_data.add_auth(user, "test-pass")
legacy_data.change_password(user, "new-pass")
with pytest.raises(hass_auth.InvalidAuth):
legacy_data.validate_login(user, "test-pass")
legacy_data.validate_login(user, "new-pass")
async def test_legacy_changing_password_raises_invalid_user(
legacy_data: hass_auth.Data,
) -> None:
"""Test in legacy mode that we initialize an empty config."""
with pytest.raises(hass_auth.InvalidUser):
legacy_data.change_password("non-existing", "pw")
async def test_legacy_login_flow_validates(
legacy_data: hass_auth.Data, hass: HomeAssistant
) -> None:
"""Test in legacy mode login flow."""
legacy_data.add_auth("test-user", "test-pass")
await legacy_data.async_save()
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.FlowResultType.FORM
result = await flow.async_step_init(
{"username": "incorrect-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"]["base"] == "invalid_auth"
result = await flow.async_step_init(
{"username": "test-user", "password": "incorrect-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"]["base"] == "invalid_auth"
result = await flow.async_step_init(
{"username": "test-user", "password": "test-pass"}
)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["data"]["username"] == "test-user"
async def test_legacy_saving_loading(
legacy_data: hass_auth.Data, hass: HomeAssistant
) -> None:
"""Test in legacy mode saving and loading JSON."""
legacy_data.add_auth("test-user", "test-pass")
legacy_data.add_auth("second-user", "second-pass")
await legacy_data.async_save()
legacy_data = hass_auth.Data(hass)
await legacy_data.async_load()
legacy_data.is_legacy = True
legacy_data.validate_login("test-user", "test-pass")
legacy_data.validate_login("second-user", "second-pass")
with pytest.raises(hass_auth.InvalidAuth):
legacy_data.validate_login("test-user ", "test-pass")
async def test_legacy_get_or_create_credentials(
hass: HomeAssistant, legacy_data: hass_auth.Data
) -> None:
"""Test in legacy mode that we can get or create credentials."""
manager = await auth_manager_from_config(hass, [{"type": "homeassistant"}], [])
provider = manager.auth_providers[0]
provider.data = legacy_data
credentials1 = await provider.async_get_or_create_credentials({"username": "hello"})
with patch.object(provider, "async_credentials", return_value=[credentials1]):
credentials2 = await provider.async_get_or_create_credentials(
{"username": "hello"}
)
assert credentials1 is credentials2
with patch.object(provider, "async_credentials", return_value=[credentials1]):
credentials3 = await provider.async_get_or_create_credentials(
{"username": "hello "}
)
assert credentials1 is not credentials3
async def test_race_condition_in_data_loading(hass: HomeAssistant) -> None:
"""Test race condition in the hass_auth.Data loading.
Ref issue: https://github.com/home-assistant/core/issues/21569
"""
counter = 0
async def mock_load(_):
"""Mock of homeassistant.helpers.storage.Store.async_load."""
nonlocal counter
counter += 1
await asyncio.sleep(0)
provider = hass_auth.HassAuthProvider(
hass, auth_store.AuthStore(hass), {"type": "homeassistant"}
)
with patch("homeassistant.helpers.storage.Store.async_load", new=mock_load):
task1 = provider.async_validate_login("user", "pass")
task2 = provider.async_validate_login("user", "pass")
results = await asyncio.gather(task1, task2, return_exceptions=True)
assert counter == 1
assert isinstance(results[0], hass_auth.InvalidAuth)
# results[1] will be a TypeError if race condition occurred
assert isinstance(results[1], hass_auth.InvalidAuth)
def test_change_username(data: hass_auth.Data) -> None:
"""Test changing username."""
data.add_auth("test-user", "test-pass")
users = data.users
assert len(users) == 1
assert users[0]["username"] == "test-user"
data.change_username("test-user", "new-user")
users = data.users
assert len(users) == 1
assert users[0]["username"] == "new-user"
@pytest.mark.parametrize("username", ["test-user ", "TEST-USER"])
def test_change_username_legacy(legacy_data: hass_auth.Data, username: str) -> None:
"""Test changing username."""
# Cannot use add_auth as it normalizes username
legacy_data.users.append(
{
"username": username,
"password": legacy_data.hash_password("test-pass", True).decode(),
}
)
users = legacy_data.users
assert len(users) == 1
assert users[0]["username"] == username
legacy_data.change_username(username, "test-user")
users = legacy_data.users
assert len(users) == 1
assert users[0]["username"] == "test-user"
def test_change_username_invalid_user(data: hass_auth.Data) -> None:
"""Test changing username raises on invalid user."""
data.add_auth("test-user", "test-pass")
users = data.users
assert len(users) == 1
assert users[0]["username"] == "test-user"
with pytest.raises(hass_auth.InvalidUser):
data.change_username("non-existing", "new-user")
users = data.users
assert len(users) == 1
assert users[0]["username"] == "test-user"
@pytest.mark.usefixtures("load_auth_component")
async def test_change_username_not_normalized(
data: hass_auth.Data, hass: HomeAssistant
) -> None:
"""Test changing username raises on not normalized username."""
data.add_auth("test-user", "test-pass")
with pytest.raises(
hass_auth.InvalidUsername, match='Username "TEST-user " is not normalized'
):
data.change_username("test-user", "TEST-user ")
@pytest.mark.parametrize(
("usernames_in_storage", "usernames_in_repair"),
[
(["Uppercase"], '- "Uppercase"'),
([" leading"], '- " leading"'),
(["trailing "], '- "trailing "'),
(["Test", "test", "Fritz "], '- "Fritz "\n- "Test"'),
],
)
async def test_create_repair_on_legacy_usernames(
hass: HomeAssistant,
hass_storage: dict[str, Any],
issue_registry: ir.IssueRegistry,
usernames_in_storage: list[str],
usernames_in_repair: str,
) -> None:
"""Test that we create a repair issue for legacy usernames."""
assert not issue_registry.issues.get(
("auth", "homeassistant_provider_not_normalized_usernames")
), "Repair issue already exists"
hass_storage[hass_auth.STORAGE_KEY] = {
"version": 1,
"minor_version": 1,
"key": "auth_provider.homeassistant",
"data": {
"users": [
{
"username": username,
"password": "onlyherebecauseweneedapasswordstring",
}
for username in usernames_in_storage
]
},
}
data = hass_auth.Data(hass)
await data.async_load()
issue = issue_registry.issues.get(
("auth", "homeassistant_provider_not_normalized_usernames")
)
assert issue, "Repair issue not created"
assert issue.translation_placeholders == {"usernames": usernames_in_repair}
async def test_delete_repair_after_fixing_usernames(
hass: HomeAssistant,
hass_storage: dict[str, Any],
issue_registry: ir.IssueRegistry,
) -> None:
"""Test that the repair is deleted after fixing the usernames."""
hass_storage[hass_auth.STORAGE_KEY] = {
"version": 1,
"minor_version": 1,
"key": "auth_provider.homeassistant",
"data": {
"users": [
{
"username": "Test",
"password": "onlyherebecauseweneedapasswordstring",
},
{
"username": "bla ",
"password": "onlyherebecauseweneedapasswordstring",
},
]
},
}
data = hass_auth.Data(hass)
await data.async_load()
issue = issue_registry.issues.get(
("auth", "homeassistant_provider_not_normalized_usernames")
)
assert issue, "Repair issue not created"
assert issue.translation_placeholders == {"usernames": '- "Test"\n- "bla "'}
data.change_username("Test", "test")
issue = issue_registry.issues.get(
("auth", "homeassistant_provider_not_normalized_usernames")
)
assert issue
assert issue.translation_placeholders == {"usernames": '- "bla "'}
data.change_username("bla ", "bla")
assert not issue_registry.issues.get(
("auth", "homeassistant_provider_not_normalized_usernames")
), "Repair issue should be deleted"

View File

@@ -0,0 +1,104 @@
"""Tests for the insecure example auth provider."""
from unittest.mock import AsyncMock
import uuid
import pytest
from homeassistant.auth import AuthManager, auth_store, models as auth_models
from homeassistant.auth.providers import insecure_example
from homeassistant.core import HomeAssistant
@pytest.fixture
async def store(hass: HomeAssistant) -> auth_store.AuthStore:
"""Mock store."""
store = auth_store.AuthStore(hass)
await store.async_load()
return store
@pytest.fixture
def provider(
hass: HomeAssistant, store: auth_store.AuthStore
) -> insecure_example.ExampleAuthProvider:
"""Mock provider."""
return insecure_example.ExampleAuthProvider(
hass,
store,
{
"type": "insecure_example",
"users": [
{
"name": "Test Name",
"username": "user-test",
"password": "password-test",
},
{"username": "🎉", "password": "😎"},
],
},
)
@pytest.fixture
def manager(
hass: HomeAssistant,
store: auth_store.AuthStore,
provider: insecure_example.ExampleAuthProvider,
) -> AuthManager:
"""Mock manager."""
return AuthManager(hass, store, {(provider.type, provider.id): provider}, {})
async def test_create_new_credential(
manager: AuthManager, provider: insecure_example.ExampleAuthProvider
) -> None:
"""Test that we create a new credential."""
credentials = await provider.async_get_or_create_credentials(
{"username": "user-test", "password": "password-test"}
)
assert credentials.is_new is True
user = await manager.async_get_or_create_user(credentials)
assert user.name == "Test Name"
assert user.is_active
async def test_match_existing_credentials(
provider: insecure_example.ExampleAuthProvider,
) -> None:
"""See if we match existing users."""
existing = auth_models.Credentials(
id=uuid.uuid4(),
auth_provider_type="insecure_example",
auth_provider_id=None,
data={"username": "user-test"},
is_new=False,
)
provider.async_credentials = AsyncMock(return_value=[existing])
credentials = await provider.async_get_or_create_credentials(
{"username": "user-test", "password": "password-test"}
)
assert credentials is existing
async def test_verify_username(provider: insecure_example.ExampleAuthProvider) -> None:
"""Test we raise if incorrect user specified."""
with pytest.raises(insecure_example.InvalidAuthError):
await provider.async_validate_login("non-existing-user", "password-test")
async def test_verify_password(provider: insecure_example.ExampleAuthProvider) -> None:
"""Test we raise if incorrect user specified."""
with pytest.raises(insecure_example.InvalidAuthError):
await provider.async_validate_login("user-test", "incorrect-password")
async def test_utf_8_username_password(
provider: insecure_example.ExampleAuthProvider,
) -> None:
"""Test that we create a new credential."""
credentials = await provider.async_get_or_create_credentials(
{"username": "🎉", "password": "😎"}
)
assert credentials.is_new is True

View File

@@ -0,0 +1,461 @@
"""Test the Trusted Networks auth provider."""
from ipaddress import ip_address, ip_network
from unittest.mock import Mock, patch
from hass_nabucasa import remote
import pytest
import voluptuous as vol
from homeassistant import auth
from homeassistant.auth import auth_store
from homeassistant.auth.providers import trusted_networks as tn_auth
from homeassistant.components.http import CONF_TRUSTED_PROXIES, CONF_USE_X_FORWARDED_FOR
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.setup import async_setup_component
@pytest.fixture
async def store(hass: HomeAssistant) -> auth_store.AuthStore:
"""Mock store."""
store = auth_store.AuthStore(hass)
await store.async_load()
return store
@pytest.fixture
def provider(
hass: HomeAssistant, store: auth_store.AuthStore
) -> tn_auth.TrustedNetworksAuthProvider:
"""Mock provider."""
return tn_auth.TrustedNetworksAuthProvider(
hass,
store,
tn_auth.CONFIG_SCHEMA(
{
"type": "trusted_networks",
"trusted_networks": [
"192.168.0.1",
"192.168.128.0/24",
"::1",
"fd00::/8",
],
}
),
)
@pytest.fixture
def provider_with_user(
hass: HomeAssistant, store: auth_store.AuthStore
) -> tn_auth.TrustedNetworksAuthProvider:
"""Mock provider with trusted users config."""
return tn_auth.TrustedNetworksAuthProvider(
hass,
store,
tn_auth.CONFIG_SCHEMA(
{
"type": "trusted_networks",
"trusted_networks": [
"192.168.0.1",
"192.168.128.0/24",
"::1",
"fd00::/8",
],
# user_id will be injected in test
"trusted_users": {
"192.168.0.1": [],
"192.168.128.0/24": [],
"fd00::/8": [],
},
}
),
)
@pytest.fixture
def provider_bypass_login(
hass: HomeAssistant, store: auth_store.AuthStore
) -> tn_auth.TrustedNetworksAuthProvider:
"""Mock provider with allow_bypass_login config."""
return tn_auth.TrustedNetworksAuthProvider(
hass,
store,
tn_auth.CONFIG_SCHEMA(
{
"type": "trusted_networks",
"trusted_networks": [
"192.168.0.1",
"192.168.128.0/24",
"::1",
"fd00::/8",
],
"allow_bypass_login": True,
}
),
)
@pytest.fixture
def manager(
hass: HomeAssistant,
store: auth_store.AuthStore,
provider: tn_auth.TrustedNetworksAuthProvider,
) -> auth.AuthManager:
"""Mock manager."""
return auth.AuthManager(hass, store, {(provider.type, provider.id): provider}, {})
@pytest.fixture
def manager_with_user(
hass: HomeAssistant,
store: auth_store.AuthStore,
provider_with_user: tn_auth.TrustedNetworksAuthProvider,
) -> auth.AuthManager:
"""Mock manager with trusted user."""
return auth.AuthManager(
hass,
store,
{(provider_with_user.type, provider_with_user.id): provider_with_user},
{},
)
@pytest.fixture
def manager_bypass_login(
hass: HomeAssistant,
store: auth_store.AuthStore,
provider_bypass_login: tn_auth.TrustedNetworksAuthProvider,
) -> auth.AuthManager:
"""Mock manager with allow bypass login."""
return auth.AuthManager(
hass,
store,
{(provider_bypass_login.type, provider_bypass_login.id): provider_bypass_login},
{},
)
async def test_config_schema() -> None:
"""Test CONFIG_SCHEMA."""
# Valid configuration
tn_auth.CONFIG_SCHEMA(
{
"type": "trusted_networks",
"trusted_networks": ["192.168.0.1"],
"trusted_users": {
"192.168.0.1": [
"a1ab982744b64757bf80515589258924",
{"group": "system-group"},
]
},
}
)
# Wrong user id format
with pytest.raises(vol.Invalid):
tn_auth.CONFIG_SCHEMA(
{
"type": "trusted_networks",
"trusted_networks": ["192.168.0.1"],
"trusted_users": {"192.168.0.1": ["abcde"]},
}
)
async def test_trusted_networks_credentials(
manager: auth.AuthManager, provider: tn_auth.TrustedNetworksAuthProvider
) -> None:
"""Test trusted_networks credentials related functions."""
owner = await manager.async_create_user("test-owner")
tn_owner_cred = await provider.async_get_or_create_credentials({"user": owner.id})
assert tn_owner_cred.is_new is False
assert any(cred.id == tn_owner_cred.id for cred in owner.credentials)
user = await manager.async_create_user("test-user")
tn_user_cred = await provider.async_get_or_create_credentials({"user": user.id})
assert tn_user_cred.id != tn_owner_cred.id
assert tn_user_cred.is_new is False
assert any(cred.id == tn_user_cred.id for cred in user.credentials)
with pytest.raises(tn_auth.InvalidUserError):
await provider.async_get_or_create_credentials({"user": "invalid-user"})
async def test_validate_access(provider: tn_auth.TrustedNetworksAuthProvider) -> None:
"""Test validate access from trusted networks."""
provider.async_validate_access(ip_address("192.168.0.1"))
provider.async_validate_access(ip_address("192.168.128.10"))
provider.async_validate_access(ip_address("::1"))
provider.async_validate_access(ip_address("fd01:db8::ff00:42:8329"))
with pytest.raises(auth.InvalidAuthError):
provider.async_validate_access(ip_address("192.168.0.2"))
with pytest.raises(auth.InvalidAuthError):
provider.async_validate_access(ip_address("127.0.0.1"))
with pytest.raises(auth.InvalidAuthError):
provider.async_validate_access(ip_address("2001:db8::ff00:42:8329"))
async def test_validate_access_proxy(
hass: HomeAssistant, provider: tn_auth.TrustedNetworksAuthProvider
) -> None:
"""Test validate access from trusted networks are blocked from proxy."""
await async_setup_component(
hass,
"http",
{
"http": {
CONF_TRUSTED_PROXIES: ["192.168.128.0/31", "fd00::1"],
CONF_USE_X_FORWARDED_FOR: True,
}
},
)
provider.async_validate_access(ip_address("192.168.128.2"))
provider.async_validate_access(ip_address("fd00::2"))
with pytest.raises(auth.InvalidAuthError):
provider.async_validate_access(ip_address("192.168.128.0"))
with pytest.raises(auth.InvalidAuthError):
provider.async_validate_access(ip_address("192.168.128.1"))
with pytest.raises(auth.InvalidAuthError):
provider.async_validate_access(ip_address("fd00::1"))
async def test_validate_access_cloud(
hass: HomeAssistant, provider: tn_auth.TrustedNetworksAuthProvider
) -> None:
"""Test validate access from trusted networks are blocked from cloud."""
await async_setup_component(
hass,
"http",
{
"http": {
CONF_TRUSTED_PROXIES: ["192.168.128.0/31", "fd00::1"],
CONF_USE_X_FORWARDED_FOR: True,
}
},
)
hass.config.components.add("cloud")
provider.async_validate_access(ip_address("192.168.128.2"))
remote.is_cloud_request.set(True)
with pytest.raises(auth.InvalidAuthError):
provider.async_validate_access(ip_address("192.168.128.2"))
async def test_validate_refresh_token(
provider: tn_auth.TrustedNetworksAuthProvider,
) -> None:
"""Verify re-validation of refresh token."""
with patch.object(provider, "async_validate_access") as mock:
with pytest.raises(auth.InvalidAuthError):
provider.async_validate_refresh_token(Mock(), None)
provider.async_validate_refresh_token(Mock(), "127.0.0.1")
mock.assert_called_once_with(ip_address("127.0.0.1"))
async def test_login_flow(
manager: auth.AuthManager, provider: tn_auth.TrustedNetworksAuthProvider
) -> None:
"""Test login flow."""
owner = await manager.async_create_user("test-owner")
user = await manager.async_create_user("test-user")
# not from trusted network
flow = await provider.async_login_flow({"ip_address": ip_address("127.0.0.1")})
step = await flow.async_step_init()
assert step["type"] == FlowResultType.ABORT
assert step["reason"] == "not_allowed"
# from trusted network, list users
flow = await provider.async_login_flow({"ip_address": ip_address("192.168.0.1")})
step = await flow.async_step_init()
assert step["step_id"] == "init"
schema = step["data_schema"]
assert schema({"user": owner.id})
with pytest.raises(vol.Invalid):
assert schema({"user": "invalid-user"})
# login with valid user
step = await flow.async_step_init({"user": user.id})
assert step["type"] == FlowResultType.CREATE_ENTRY
assert step["data"]["user"] == user.id
async def test_trusted_users_login(
manager_with_user: auth.AuthManager,
provider_with_user: tn_auth.TrustedNetworksAuthProvider,
) -> None:
"""Test available user list changed per different IP."""
owner = await manager_with_user.async_create_user("test-owner")
sys_user = await manager_with_user.async_create_system_user(
"test-sys-user"
) # system user will not be available to select
user = await manager_with_user.async_create_user("test-user")
# change the trusted users config
config = provider_with_user.config["trusted_users"]
assert ip_network("192.168.0.1") in config
config[ip_network("192.168.0.1")] = [owner.id]
assert ip_network("192.168.128.0/24") in config
config[ip_network("192.168.128.0/24")] = [sys_user.id, user.id]
# not from trusted network
flow = await provider_with_user.async_login_flow(
{"ip_address": ip_address("127.0.0.1")}
)
step = await flow.async_step_init()
assert step["type"] == FlowResultType.ABORT
assert step["reason"] == "not_allowed"
# from trusted network, list users intersect trusted_users
flow = await provider_with_user.async_login_flow(
{"ip_address": ip_address("192.168.0.1")}
)
step = await flow.async_step_init()
assert step["step_id"] == "init"
schema = step["data_schema"]
# only owner listed
assert schema({"user": owner.id})
with pytest.raises(vol.Invalid):
assert schema({"user": user.id})
# from trusted network, list users intersect trusted_users
flow = await provider_with_user.async_login_flow(
{"ip_address": ip_address("192.168.128.1")}
)
step = await flow.async_step_init()
assert step["step_id"] == "init"
schema = step["data_schema"]
# only user listed
assert schema({"user": user.id})
with pytest.raises(vol.Invalid):
assert schema({"user": owner.id})
with pytest.raises(vol.Invalid):
assert schema({"user": sys_user.id})
# from trusted network, list users intersect trusted_users
flow = await provider_with_user.async_login_flow({"ip_address": ip_address("::1")})
step = await flow.async_step_init()
assert step["step_id"] == "init"
schema = step["data_schema"]
# both owner and user listed
assert schema({"user": owner.id})
assert schema({"user": user.id})
with pytest.raises(vol.Invalid):
assert schema({"user": sys_user.id})
# from trusted network, list users intersect trusted_users
flow = await provider_with_user.async_login_flow(
{"ip_address": ip_address("fd00::1")}
)
step = await flow.async_step_init()
assert step["step_id"] == "init"
schema = step["data_schema"]
# no user listed
with pytest.raises(vol.Invalid):
assert schema({"user": owner.id})
with pytest.raises(vol.Invalid):
assert schema({"user": user.id})
with pytest.raises(vol.Invalid):
assert schema({"user": sys_user.id})
async def test_trusted_group_login(
manager_with_user: auth.AuthManager,
provider_with_user: tn_auth.TrustedNetworksAuthProvider,
) -> None:
"""Test config trusted_user with group_id."""
owner = await manager_with_user.async_create_user("test-owner")
# create a user in user group
user = await manager_with_user.async_create_user("test-user")
await manager_with_user.async_update_user(
user, group_ids=[auth.const.GROUP_ID_USER]
)
# change the trusted users config
config = provider_with_user.config["trusted_users"]
assert ip_network("192.168.0.1") in config
config[ip_network("192.168.0.1")] = [{"group": [auth.const.GROUP_ID_USER]}]
assert ip_network("192.168.128.0/24") in config
config[ip_network("192.168.128.0/24")] = [
owner.id,
{"group": [auth.const.GROUP_ID_USER]},
]
# not from trusted network
flow = await provider_with_user.async_login_flow(
{"ip_address": ip_address("127.0.0.1")}
)
step = await flow.async_step_init()
assert step["type"] == FlowResultType.ABORT
assert step["reason"] == "not_allowed"
# from trusted network, list users intersect trusted_users
flow = await provider_with_user.async_login_flow(
{"ip_address": ip_address("192.168.0.1")}
)
step = await flow.async_step_init()
assert step["step_id"] == "init"
schema = step["data_schema"]
# only user listed
assert schema({"user": user.id})
with pytest.raises(vol.Invalid):
assert schema({"user": owner.id})
# from trusted network, list users intersect trusted_users
flow = await provider_with_user.async_login_flow(
{"ip_address": ip_address("192.168.128.1")}
)
step = await flow.async_step_init()
assert step["step_id"] == "init"
schema = step["data_schema"]
# both owner and user listed
assert schema({"user": owner.id})
assert schema({"user": user.id})
async def test_bypass_login_flow(
manager_bypass_login: auth.AuthManager,
provider_bypass_login: tn_auth.TrustedNetworksAuthProvider,
) -> None:
"""Test login flow can be bypass if only one user available."""
owner = await manager_bypass_login.async_create_user("test-owner")
# not from trusted network
flow = await provider_bypass_login.async_login_flow(
{"ip_address": ip_address("127.0.0.1")}
)
step = await flow.async_step_init()
assert step["type"] == FlowResultType.ABORT
assert step["reason"] == "not_allowed"
# from trusted network, only one available user, bypass the login flow
flow = await provider_bypass_login.async_login_flow(
{"ip_address": ip_address("192.168.0.1")}
)
step = await flow.async_step_init()
assert step["type"] == FlowResultType.CREATE_ENTRY
assert step["data"]["user"] == owner.id
user = await manager_bypass_login.async_create_user("test-user")
# from trusted network, two available user, show up login form
flow = await provider_bypass_login.async_login_flow(
{"ip_address": ip_address("192.168.0.1")}
)
step = await flow.async_step_init()
schema = step["data_schema"]
# both owner and user listed
assert schema({"user": owner.id})
assert schema({"user": user.id})

View File

@@ -0,0 +1,381 @@
"""Tests for the auth store."""
import asyncio
from typing import Any
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from homeassistant.auth import auth_store
from homeassistant.core import HomeAssistant
MOCK_STORAGE_DATA = {
"version": 1,
"data": {
"credentials": [],
"users": [
{
"id": "user-id",
"is_active": True,
"is_owner": True,
"name": "Paulus",
"system_generated": False,
},
{
"id": "system-id",
"is_active": True,
"is_owner": True,
"name": "Hass.io",
"system_generated": True,
},
],
"refresh_tokens": [
{
"access_token_expiration": 1800.0,
"client_id": "http://localhost:8123/",
"created_at": "2018-10-03T13:43:19.774637+00:00",
"id": "user-token-id",
"jwt_key": "some-key",
"last_used_at": "2018-10-03T13:43:19.774712+00:00",
"token": "some-token",
"user_id": "user-id",
"version": "1.2.3",
},
{
"access_token_expiration": 1800.0,
"client_id": None,
"created_at": "2018-10-03T13:43:19.774637+00:00",
"id": "system-token-id",
"jwt_key": "some-key",
"last_used_at": "2018-10-03T13:43:19.774712+00:00",
"token": "some-token",
"user_id": "system-id",
},
{
"access_token_expiration": 1800.0,
"client_id": "http://localhost:8123/",
"created_at": "2018-10-03T13:43:19.774637+00:00",
"id": "hidden-because-no-jwt-id",
"last_used_at": "2018-10-03T13:43:19.774712+00:00",
"token": "some-token",
"user_id": "user-id",
},
],
},
}
async def test_loading_no_group_data_format(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test we correctly load old data without any groups."""
hass_storage[auth_store.STORAGE_KEY] = MOCK_STORAGE_DATA
store = auth_store.AuthStore(hass)
await store.async_load()
groups = await store.async_get_groups()
assert len(groups) == 3
admin_group = groups[0]
assert admin_group.name == auth_store.GROUP_NAME_ADMIN
assert admin_group.system_generated
assert admin_group.id == auth_store.GROUP_ID_ADMIN
read_group = groups[1]
assert read_group.name == auth_store.GROUP_NAME_READ_ONLY
assert read_group.system_generated
assert read_group.id == auth_store.GROUP_ID_READ_ONLY
user_group = groups[2]
assert user_group.name == auth_store.GROUP_NAME_USER
assert user_group.system_generated
assert user_group.id == auth_store.GROUP_ID_USER
users = await store.async_get_users()
assert len(users) == 2
owner, system = users
assert owner.system_generated is False
assert owner.groups == [admin_group]
assert len(owner.refresh_tokens) == 1
owner_token = list(owner.refresh_tokens.values())[0]
assert owner_token.id == "user-token-id"
assert owner_token.version == "1.2.3"
assert system.system_generated is True
assert system.groups == []
assert len(system.refresh_tokens) == 1
system_token = list(system.refresh_tokens.values())[0]
assert system_token.id == "system-token-id"
assert system_token.version is None
async def test_loading_all_access_group_data_format(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test we correctly load old data with single group."""
hass_storage[auth_store.STORAGE_KEY] = MOCK_STORAGE_DATA
store = auth_store.AuthStore(hass)
await store.async_load()
groups = await store.async_get_groups()
assert len(groups) == 3
admin_group = groups[0]
assert admin_group.name == auth_store.GROUP_NAME_ADMIN
assert admin_group.system_generated
assert admin_group.id == auth_store.GROUP_ID_ADMIN
read_group = groups[1]
assert read_group.name == auth_store.GROUP_NAME_READ_ONLY
assert read_group.system_generated
assert read_group.id == auth_store.GROUP_ID_READ_ONLY
user_group = groups[2]
assert user_group.name == auth_store.GROUP_NAME_USER
assert user_group.system_generated
assert user_group.id == auth_store.GROUP_ID_USER
users = await store.async_get_users()
assert len(users) == 2
owner, system = users
assert owner.system_generated is False
assert owner.groups == [admin_group]
assert len(owner.refresh_tokens) == 1
owner_token = list(owner.refresh_tokens.values())[0]
assert owner_token.id == "user-token-id"
assert owner_token.version == "1.2.3"
assert system.system_generated is True
assert system.groups == []
assert len(system.refresh_tokens) == 1
system_token = list(system.refresh_tokens.values())[0]
assert system_token.id == "system-token-id"
assert system_token.version is None
async def test_loading_empty_data(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test we correctly load with no existing data."""
store = auth_store.AuthStore(hass)
await store.async_load()
groups = await store.async_get_groups()
assert len(groups) == 3
admin_group = groups[0]
assert admin_group.name == auth_store.GROUP_NAME_ADMIN
assert admin_group.system_generated
assert admin_group.id == auth_store.GROUP_ID_ADMIN
user_group = groups[1]
assert user_group.name == auth_store.GROUP_NAME_USER
assert user_group.system_generated
assert user_group.id == auth_store.GROUP_ID_USER
read_group = groups[2]
assert read_group.name == auth_store.GROUP_NAME_READ_ONLY
assert read_group.system_generated
assert read_group.id == auth_store.GROUP_ID_READ_ONLY
users = await store.async_get_users()
assert len(users) == 0
async def test_system_groups_store_id_and_name(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test that for system groups we store the ID and name.
Name is stored so that we remain backwards compat with < 0.82.
"""
store = auth_store.AuthStore(hass)
await store.async_load()
data = store._data_to_save()
assert len(data["users"]) == 0
assert data["groups"] == [
{"id": auth_store.GROUP_ID_ADMIN, "name": auth_store.GROUP_NAME_ADMIN},
{"id": auth_store.GROUP_ID_USER, "name": auth_store.GROUP_NAME_USER},
{"id": auth_store.GROUP_ID_READ_ONLY, "name": auth_store.GROUP_NAME_READ_ONLY},
]
async def test_loading_only_once(hass: HomeAssistant) -> None:
"""Test only one storage load is allowed."""
store = auth_store.AuthStore(hass)
with (
patch("homeassistant.helpers.entity_registry.async_get") as mock_ent_registry,
patch("homeassistant.helpers.device_registry.async_get") as mock_dev_registry,
patch(
"homeassistant.helpers.storage.Store.async_load", return_value=None
) as mock_load,
):
await store.async_load()
with pytest.raises(RuntimeError, match="Auth storage is already loaded"):
await store.async_load()
results = await asyncio.gather(store.async_get_users(), store.async_get_users())
mock_ent_registry.assert_called_once_with(hass)
mock_dev_registry.assert_called_once_with(hass)
mock_load.assert_called_once_with()
assert results[0] == results[1]
async def test_dont_change_expire_at_on_load(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test we correctly don't modify expired_at store load."""
hass_storage[auth_store.STORAGE_KEY] = {
"version": 1,
"data": {
"credentials": [],
"users": [
{
"id": "user-id",
"is_active": True,
"is_owner": True,
"name": "Paulus",
"system_generated": False,
},
{
"id": "system-id",
"is_active": True,
"is_owner": True,
"name": "Hass.io",
"system_generated": True,
},
],
"refresh_tokens": [
{
"access_token_expiration": 1800.0,
"client_id": "http://localhost:8123/",
"created_at": "2018-10-03T13:43:19.774637+00:00",
"id": "user-token-id",
"jwt_key": "some-key",
"token": "some-token",
"user_id": "user-id",
"version": "1.2.3",
},
{
"access_token_expiration": 1800.0,
"client_id": "http://localhost:8123/",
"created_at": "2018-10-03T13:43:19.774637+00:00",
"id": "user-token-id2",
"jwt_key": "some-key2",
"token": "some-token",
"user_id": "user-id",
"expire_at": 1724133771.079745,
},
],
},
}
store = auth_store.AuthStore(hass)
await store.async_load()
users = await store.async_get_users()
assert len(users[0].refresh_tokens) == 2
token1, token2 = users[0].refresh_tokens.values()
assert not token1.expire_at
assert token2.expire_at == 1724133771.079745
async def test_loading_does_not_write_right_away(
hass: HomeAssistant, hass_storage: dict[str, Any], freezer: FrozenDateTimeFactory
) -> None:
"""Test after calling load we wait five minutes to write."""
hass_storage[auth_store.STORAGE_KEY] = MOCK_STORAGE_DATA
store = auth_store.AuthStore(hass)
await store.async_load()
# Wipe storage so we can verify if it was written
hass_storage[auth_store.STORAGE_KEY] = {}
freezer.tick(auth_store.DEFAULT_SAVE_DELAY)
await hass.async_block_till_done()
assert hass_storage[auth_store.STORAGE_KEY] == {}
freezer.tick(auth_store.INITIAL_LOAD_SAVE_DELAY)
# Once for scheduling the task
await hass.async_block_till_done()
# Once for the task
await hass.async_block_till_done()
assert hass_storage[auth_store.STORAGE_KEY] != {}
async def test_add_remove_user_affects_tokens(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test adding and removing a user removes the tokens."""
store = auth_store.AuthStore(hass)
await store.async_load()
user = await store.async_create_user("Test User")
assert user.name == "Test User"
refresh_token = await store.async_create_refresh_token(
user, "client_id", "access_token_expiration"
)
assert user.refresh_tokens == {refresh_token.id: refresh_token}
assert await store.async_get_user(user.id) == user
assert store.async_get_refresh_token(refresh_token.id) == refresh_token
assert store.async_get_refresh_token_by_token(refresh_token.token) == refresh_token
await store.async_remove_user(user)
assert store.async_get_refresh_token(refresh_token.id) is None
assert store.async_get_refresh_token_by_token(refresh_token.token) is None
assert user.refresh_tokens == {}
async def test_set_expiry_date(
hass: HomeAssistant, hass_storage: dict[str, Any], freezer: FrozenDateTimeFactory
) -> None:
"""Test set expiry date of a refresh token."""
hass_storage[auth_store.STORAGE_KEY] = {
"version": 1,
"data": {
"credentials": [],
"users": [
{
"id": "user-id",
"is_active": True,
"is_owner": True,
"name": "Paulus",
"system_generated": False,
},
],
"refresh_tokens": [
{
"access_token_expiration": 1800.0,
"client_id": "http://localhost:8123/",
"created_at": "2018-10-03T13:43:19.774637+00:00",
"id": "user-token-id",
"jwt_key": "some-key",
"token": "some-token",
"user_id": "user-id",
"expire_at": 1724133771.079745,
},
],
},
}
store = auth_store.AuthStore(hass)
await store.async_load()
users = await store.async_get_users()
assert len(users[0].refresh_tokens) == 1
(token,) = users[0].refresh_tokens.values()
assert token.expire_at == 1724133771.079745
store.async_set_expiry(token, enable_expiry=False)
assert token.expire_at is None
freezer.tick(auth_store.DEFAULT_SAVE_DELAY * 2)
# Once for scheduling the task
await hass.async_block_till_done()
# Once for the task
await hass.async_block_till_done()
# verify token is saved without expire_at
assert (
hass_storage[auth_store.STORAGE_KEY]["data"]["refresh_tokens"][0]["expire_at"]
is None
)
store.async_set_expiry(token, enable_expiry=True)
assert token.expire_at is not None

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,18 @@
"""Tests for the Home Assistant auth jwt_wrapper module."""
import jwt
import pytest
from homeassistant.auth import jwt_wrapper
async def test_all_default_options_are_in_verify_options() -> None:
"""Test that all default options in _VERIFY_OPTIONS."""
for option in jwt_wrapper._PyJWTWithVerify._get_default_options():
assert option in jwt_wrapper._VERIFY_OPTIONS
async def test_reject_access_token_with_impossible_large_size() -> None:
"""Test rejecting access tokens with impossible sizes."""
with pytest.raises(jwt.DecodeError):
jwt_wrapper.unverified_hs256_token_decode("a" * 10000)

View File

@@ -0,0 +1,63 @@
"""Tests for the auth models."""
from homeassistant.auth import models, permissions
def test_owner_fetching_owner_permissions() -> None:
"""Test we fetch the owner permissions for an owner user."""
group = models.Group(name="Test Group", policy={})
owner = models.User(
name="Test User", perm_lookup=None, groups=[group], is_owner=True
)
assert owner.permissions is permissions.OwnerPermissions
def test_permissions_merged() -> None:
"""Test we merge the groups permissions."""
group = models.Group(
name="Test Group", policy={"entities": {"domains": {"switch": True}}}
)
group2 = models.Group(
name="Test Group", policy={"entities": {"entity_ids": {"light.kitchen": True}}}
)
user = models.User(name="Test User", perm_lookup=None, groups=[group, group2])
# Make sure we cache instance
assert user.permissions is user.permissions
assert user.permissions.check_entity("switch.bla", "read") is True
assert user.permissions.check_entity("light.kitchen", "read") is True
assert user.permissions.check_entity("light.not_kitchen", "read") is False
def test_cache_cleared_on_group_change() -> None:
"""Test we clear the cache when a group changes."""
group = models.Group(
name="Test Group", policy={"entities": {"domains": {"switch": True}}}
)
admin_group = models.Group(
name="Admin group", id=models.GROUP_ID_ADMIN, policy={"entities": {}}
)
user = models.User(
name="Test User", perm_lookup=None, groups=[group], is_active=True
)
# Make sure we cache instance
assert user.permissions is user.permissions
# Make sure we cache is_admin
assert user.is_admin is user.is_admin
assert user.is_active is True
user.groups = []
assert user.groups == []
assert user.is_admin is False
user.is_owner = True
assert user.is_admin is True
user.is_owner = False
assert user.is_admin is False
user.groups = [admin_group]
assert user.is_admin is True
user.is_active = False
assert user.is_admin is False

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1 @@
"""The tests for components."""

View File

@@ -0,0 +1 @@
"""Tests for the Abode component."""

View File

@@ -0,0 +1,33 @@
"""Common methods used across tests for Abode."""
from unittest.mock import patch
from homeassistant.components.abode import DOMAIN as ABODE_DOMAIN
from homeassistant.components.abode.const import CONF_POLLING
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry
async def setup_platform(hass: HomeAssistant, platform: str) -> MockConfigEntry:
"""Set up the Abode platform."""
mock_entry = MockConfigEntry(
domain=ABODE_DOMAIN,
data={
CONF_USERNAME: "user@email.com",
CONF_PASSWORD: "password",
CONF_POLLING: False,
},
)
mock_entry.add_to_hass(hass)
with (
patch("homeassistant.components.abode.PLATFORMS", [platform]),
patch("jaraco.abode.event_controller.sio"),
):
assert await async_setup_component(hass, ABODE_DOMAIN, {})
await hass.async_block_till_done()
return mock_entry

View File

@@ -0,0 +1,37 @@
"""Configuration for Abode tests."""
from collections.abc import Generator
from unittest.mock import AsyncMock, patch
from jaraco.abode.helpers import urls as URL
import pytest
from requests_mock import Mocker
from tests.common import load_fixture
from tests.components.light.conftest import mock_light_profiles # noqa: F401
@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock]:
"""Override async_setup_entry."""
with patch(
"homeassistant.components.abode.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry
@pytest.fixture(autouse=True)
def requests_mock_fixture(requests_mock: Mocker) -> None:
"""Fixture to provide a requests mocker."""
# Mocks the login response for abodepy.
requests_mock.post(URL.LOGIN, text=load_fixture("login.json", "abode"))
# Mocks the logout response for abodepy.
requests_mock.post(URL.LOGOUT, text=load_fixture("logout.json", "abode"))
# Mocks the oauth claims response for abodepy.
requests_mock.get(URL.OAUTH_TOKEN, text=load_fixture("oauth_claims.json", "abode"))
# Mocks the panel response for abodepy.
requests_mock.get(URL.PANEL, text=load_fixture("panel.json", "abode"))
# Mocks the automations response for abodepy.
requests_mock.get(URL.AUTOMATION, text=load_fixture("automation.json", "abode"))
# Mocks the devices response for abodepy.
requests_mock.get(URL.DEVICES, text=load_fixture("devices.json", "abode"))

View File

@@ -0,0 +1,35 @@
{
"name": "Test Automation",
"enabled": "True",
"version": 2,
"id": "47fae27488f74f55b964a81a066c3a01",
"subType": "",
"actions": [
{
"directive": {
"trait": "panel.traits.panelMode",
"name": "panel.directives.arm",
"state": {
"panelMode": "AWAY"
}
}
}
],
"conditions": {},
"triggers": {
"operator": "OR",
"expressions": [
{
"mobileDevices": ["89381", "658"],
"property": {
"trait": "mobile.traits.location",
"name": "location",
"rule": {
"location": "31675",
"equalTo": "LAST_OUT"
}
}
}
]
}
}

View File

@@ -0,0 +1,35 @@
{
"name": "Test Automation",
"enabled": "False",
"version": 2,
"id": "47fae27488f74f55b964a81a066c3a01",
"subType": "",
"actions": [
{
"directive": {
"trait": "panel.traits.panelMode",
"name": "panel.directives.arm",
"state": {
"panelMode": "AWAY"
}
}
}
],
"conditions": {},
"triggers": {
"operator": "OR",
"expressions": [
{
"mobileDevices": ["89381", "658"],
"property": {
"trait": "mobile.traits.location",
"name": "location",
"rule": {
"location": "31675",
"equalTo": "LAST_OUT"
}
}
}
]
}
}

View File

@@ -0,0 +1,799 @@
[
{
"id": "RF:01430030",
"type_tag": "device_type.door_contact",
"type": "Door Contact",
"name": "Front Door",
"area": "1",
"zone": "15",
"sort_order": "",
"is_window": "1",
"bypass": "0",
"schar_24hr": "0",
"sresp_24hr": "0",
"sresp_mode_0": "3",
"sresp_entry_0": "3",
"sresp_exit_0": "0",
"group_name": "Doors and Windows",
"group_id": "397972",
"default_group_id": "1",
"sort_id": "10000",
"sresp_mode_1": "1",
"sresp_entry_1": "1",
"sresp_exit_1": "0",
"sresp_mode_2": "1",
"sresp_entry_2": "1",
"sresp_exit_2": "0",
"sresp_mode_3": "1",
"uuid": "2834013428b6035fba7d4054aa7b25a3",
"sresp_entry_3": "1",
"sresp_exit_3": "0",
"sresp_mode_4": "1",
"sresp_entry_4": "1",
"sresp_exit_4": "0",
"version": "",
"origin": "abode",
"has_subscription": null,
"onboard": "0",
"s2_grnt_keys": "",
"s2_dsk": "",
"s2_propty": "",
"s2_keys_valid": "",
"zwave_secure_protocol": "",
"control_url": "",
"deep_link": null,
"status_color": "#5cb85c",
"faults": {
"low_battery": 0,
"tempered": 0,
"supervision": 0,
"out_of_order": 0,
"no_response": 0,
"jammed": 0,
"zwave_fault": 0
},
"status": "Closed",
"status_display": "Closed",
"statuses": {
"open": "0"
},
"status_ex": "",
"actions": [],
"status_icons": {
"Open": "assets/icons/WindowOpened.svg",
"Closed": "assets/icons/WindowClosed.svg"
},
"icon": "assets/icons/doorsensor-a.svg",
"sresp_trigger": "0",
"sresp_restore": "0"
},
{
"id": "RF:01c34a30",
"type_tag": "device_type.povs",
"type": "Occupancy",
"name": "Hallway Motion",
"area": "1",
"zone": "17",
"sort_order": "",
"is_window": "",
"bypass": "0",
"schar_24hr": "0",
"sresp_24hr": "0",
"sresp_mode_0": "0",
"sresp_entry_0": "0",
"sresp_exit_0": "0",
"group_name": "Ungrouped",
"group_id": "1",
"default_group_id": "1",
"sort_id": "10000",
"sresp_mode_1": "5",
"sresp_entry_1": "4",
"sresp_exit_1": "0",
"sresp_mode_2": "0",
"sresp_entry_2": "4",
"sresp_exit_2": "0",
"sresp_mode_3": "0",
"uuid": "ba2c7e8d4430da8d34c31425a2823fe0",
"sresp_entry_3": "0",
"sresp_exit_3": "0",
"sresp_mode_4": "0",
"sresp_entry_4": "0",
"sresp_exit_4": "0",
"version": "",
"origin": "abode",
"has_subscription": null,
"onboard": "0",
"s2_grnt_keys": "",
"s2_dsk": "",
"s2_propty": "",
"s2_keys_valid": "",
"zwave_secure_protocol": "",
"control_url": "",
"deep_link": null,
"status_color": "#5cb85c",
"faults": {
"low_battery": 0,
"tempered": 0,
"supervision": 0,
"out_of_order": 0,
"no_response": 0,
"jammed": 0,
"zwave_fault": 0
},
"status": "Online",
"status_display": "Online",
"statuses": {
"motion": "0"
},
"status_ex": "",
"actions": [],
"status_icons": [],
"icon": "assets/icons/motioncamera-a.svg",
"sresp_trigger": "0",
"sresp_restore": "0",
"occupancy_timer": null,
"sensitivity": null,
"model": "L1",
"is_motion_sensor": true
},
{
"id": "SR:PIR",
"type_tag": "device_type.pir",
"type": "Motion Sensor",
"name": "Living Room Motion",
"area": "1",
"zone": "2",
"sort_order": "",
"is_window": "",
"bypass": "0",
"schar_24hr": "0",
"sresp_24hr": "0",
"sresp_mode_0": "0",
"sresp_entry_0": "0",
"sresp_exit_0": "0",
"group_name": "Motion",
"group_id": "397973",
"default_group_id": "1",
"sort_id": "10000",
"sresp_mode_1": "5",
"sresp_entry_1": "4",
"sresp_exit_1": "0",
"sresp_mode_2": "0",
"sresp_entry_2": "4",
"sresp_exit_2": "0",
"sresp_mode_3": "0",
"uuid": "2f1bc34ceadac032af4fc9189ef821a8",
"sresp_entry_3": "0",
"sresp_exit_3": "0",
"sresp_mode_4": "0",
"sresp_entry_4": "0",
"sresp_exit_4": "0",
"version": "",
"origin": "abode",
"has_subscription": null,
"onboard": "1",
"s2_grnt_keys": "",
"s2_dsk": "",
"s2_propty": "",
"s2_keys_valid": "",
"zwave_secure_protocol": "",
"control_url": "",
"deep_link": null,
"status_color": "#5cb85c",
"faults": {
"low_battery": 0,
"tempered": 0,
"supervision": 0,
"out_of_order": 0,
"no_response": 0,
"jammed": 0,
"zwave_fault": 0
},
"status": "Online",
"status_display": "Online",
"statuses": [],
"status_ex": "",
"actions": [],
"status_icons": [],
"icon": "assets/icons/motioncamera-a.svg",
"schar_obpir_sens": "15",
"schar_obpir_pulse": "2",
"sensitivity": "15",
"model": "L1"
},
{
"id": "ZB:db5b1a",
"type_tag": "device_type.hue",
"type": "RGB Dimmer",
"name": "Living Room Lamp",
"area": "1",
"zone": "21",
"sort_order": "",
"is_window": "",
"bypass": "0",
"schar_24hr": "0",
"sresp_24hr": "0",
"sresp_mode_0": "0",
"sresp_entry_0": "0",
"sresp_exit_0": "0",
"group_name": "Ungrouped",
"group_id": "1",
"default_group_id": "1",
"sort_id": "10000",
"sresp_mode_1": "0",
"sresp_entry_1": "0",
"sresp_exit_1": "0",
"sresp_mode_2": "0",
"sresp_entry_2": "0",
"sresp_exit_2": "0",
"sresp_mode_3": "0",
"uuid": "741385f4388b2637df4c6b398fe50581",
"sresp_entry_3": "0",
"sresp_exit_3": "0",
"sresp_mode_4": "0",
"sresp_entry_4": "0",
"sresp_exit_4": "0",
"version": "LCT014",
"origin": "abode",
"has_subscription": null,
"onboard": "0",
"s2_grnt_keys": "",
"s2_dsk": "",
"s2_propty": "",
"s2_keys_valid": "",
"zwave_secure_protocol": "",
"control_url": "api/v1/control/light/ZB:db5b1a",
"deep_link": null,
"status_color": "#5cb85c",
"faults": {
"low_battery": 0,
"tempered": 0,
"supervision": 0,
"out_of_order": 0,
"no_response": 0,
"jammed": 0,
"zwave_fault": 0
},
"status": "On",
"status_display": "On",
"statuses": {
"saturation": 100,
"hue": 225,
"level": "79",
"switch": "1",
"color_temp": 3571,
"color_mode": "0"
},
"status_ex": "",
"actions": [],
"status_icons": [],
"icon": "assets/icons/bulb-1.svg",
"statusEx": "0"
},
{
"id": "ZB:db5b1b",
"type_tag": "device_type.hue",
"type": "Dimmer",
"name": "Test Dimmer Only Device",
"area": "1",
"zone": "21",
"sort_order": "",
"is_window": "",
"bypass": "0",
"schar_24hr": "0",
"sresp_24hr": "0",
"sresp_mode_0": "0",
"sresp_entry_0": "0",
"sresp_exit_0": "0",
"group_name": "Ungrouped",
"group_id": "1",
"default_group_id": "1",
"sort_id": "10000",
"sresp_mode_1": "0",
"sresp_entry_1": "0",
"sresp_exit_1": "0",
"sresp_mode_2": "0",
"sresp_entry_2": "0",
"sresp_exit_2": "0",
"sresp_mode_3": "0",
"uuid": "641385f4388b2637df4c6b398fe50581",
"sresp_entry_3": "0",
"sresp_exit_3": "0",
"sresp_mode_4": "0",
"sresp_entry_4": "0",
"sresp_exit_4": "0",
"version": "LCT014",
"origin": "abode",
"has_subscription": null,
"onboard": "0",
"s2_grnt_keys": "",
"s2_dsk": "",
"s2_propty": "",
"s2_keys_valid": "",
"zwave_secure_protocol": "",
"control_url": "api/v1/control/light/ZB:db5b1b",
"deep_link": null,
"status_color": "#5cb85c",
"faults": {
"low_battery": 0,
"tempered": 0,
"supervision": 0,
"out_of_order": 0,
"no_response": 0,
"jammed": 0,
"zwave_fault": 0
},
"status": "On",
"status_display": "On",
"statuses": {
"saturation": 100,
"hue": 225,
"level": "100",
"switch": "1",
"color_temp": 3571,
"color_mode": "2"
},
"status_ex": "",
"actions": [],
"status_icons": [],
"icon": "assets/icons/bulb-1.svg",
"statusEx": "0"
},
{
"id": "ZB:db5b1c",
"type_tag": "device_type.dimmer",
"type": "Light",
"name": "Test Non-dimmer Device",
"area": "1",
"zone": "21",
"sort_order": "",
"is_window": "",
"bypass": "0",
"schar_24hr": "0",
"sresp_24hr": "0",
"sresp_mode_0": "0",
"sresp_entry_0": "0",
"sresp_exit_0": "0",
"group_name": "Ungrouped",
"group_id": "1",
"default_group_id": "1",
"sort_id": "10000",
"sresp_mode_1": "0",
"sresp_entry_1": "0",
"sresp_exit_1": "0",
"sresp_mode_2": "0",
"sresp_entry_2": "0",
"sresp_exit_2": "0",
"sresp_mode_3": "0",
"uuid": "641385f4388b2637df4c6b398fe50583",
"sresp_entry_3": "0",
"sresp_exit_3": "0",
"sresp_mode_4": "0",
"sresp_entry_4": "0",
"sresp_exit_4": "0",
"version": "LCT014",
"origin": "abode",
"has_subscription": null,
"onboard": "0",
"s2_grnt_keys": "",
"s2_dsk": "",
"s2_propty": "",
"s2_keys_valid": "",
"zwave_secure_protocol": "",
"control_url": "api/v1/control/light/ZB:db5b1c",
"deep_link": null,
"status_color": "#5cb85c",
"faults": {
"low_battery": 0,
"tempered": 0,
"supervision": 0,
"out_of_order": 0,
"no_response": 0,
"jammed": 0,
"zwave_fault": 0
},
"status": "On",
"status_display": "On",
"statuses": {
"switch": "1"
},
"status_ex": "",
"actions": [],
"status_icons": [],
"icon": "assets/icons/bulb-1.svg",
"statusEx": "0"
},
{
"id": "RF:02148e70",
"type_tag": "device_type.lm",
"type": "LM",
"name": "Environment Sensor",
"area": "1",
"zone": "24",
"sort_order": "",
"is_window": "",
"bypass": "0",
"schar_24hr": "0",
"sresp_24hr": "0",
"sresp_mode_0": "0",
"sresp_entry_0": "0",
"sresp_exit_0": "0",
"group_name": "Ungrouped",
"group_id": "1",
"default_group_id": "1",
"sort_id": "10000",
"sresp_mode_1": "0",
"sresp_entry_1": "0",
"sresp_exit_1": "0",
"sresp_mode_2": "0",
"sresp_entry_2": "0",
"sresp_exit_2": "0",
"sresp_mode_3": "0",
"uuid": "13545b21f4bdcd33d9abd461f8443e65",
"sresp_entry_3": "0",
"sresp_exit_3": "0",
"sresp_mode_4": "0",
"sresp_entry_4": "0",
"sresp_exit_4": "0",
"version": "",
"origin": "abode",
"has_subscription": null,
"onboard": "0",
"s2_grnt_keys": "",
"s2_dsk": "",
"s2_propty": "",
"s2_keys_valid": "",
"zwave_secure_protocol": "",
"control_url": "",
"deep_link": null,
"status_color": "#5cb85c",
"faults": {
"low_battery": 0,
"tempered": 0,
"supervision": 0,
"out_of_order": 0,
"no_response": 0,
"jammed": 0,
"zwave_fault": 0
},
"status": "67 \u00b0F",
"status_display": "Online",
"statuses": {
"temperature": "67 \u00b0F",
"temp": "19.5",
"lux": "1 lx",
"humidity": "32 %"
},
"status_ex": "",
"actions": [
{
"label": "High Humidity Alarm",
"value": "a=1&z=24&trigger=HMH;"
},
{
"label": "Low Humidity Alarm",
"value": "a=1&z=24&trigger=HML;"
},
{
"label": "High Temperature Alarm",
"value": "a=1&z=24&trigger=TSH;"
},
{
"label": "Low Temperature Alarm",
"value": "a=1&z=24&trigger=TSL;"
}
],
"status_icons": [],
"icon": "assets/icons/occupancy-sensor.svg",
"statusEx": "1"
},
{
"id": "ZW:0000000b",
"type_tag": "device_type.power_switch_sensor",
"type": "Power Switch Sensor",
"name": "Test Switch",
"area": "1",
"zone": "23",
"sort_order": "",
"is_window": "",
"bypass": "0",
"schar_24hr": "0",
"sresp_24hr": "0",
"sresp_mode_0": "0",
"sresp_entry_0": "0",
"sresp_exit_0": "0",
"group_name": "Lighting",
"group_id": "377075",
"default_group_id": "1",
"sort_id": "7",
"sresp_mode_1": "0",
"sresp_entry_1": "0",
"sresp_exit_1": "0",
"sresp_mode_2": "0",
"sresp_entry_2": "0",
"sresp_exit_2": "0",
"sresp_mode_3": "0",
"uuid": "0012a4d3614cb7e2b8c9abea31d2fb2a",
"sresp_entry_3": "0",
"sresp_exit_3": "0",
"sresp_mode_4": "0",
"sresp_entry_4": "0",
"sresp_exit_4": "0",
"version": "006349523032",
"origin": "abode",
"has_subscription": null,
"onboard": "0",
"s2_grnt_keys": "",
"s2_dsk": "",
"s2_propty": "",
"s2_keys_valid": "",
"zwave_secure_protocol": "",
"control_url": "api/v1/control/power_switch/ZW:0000000b",
"deep_link": null,
"status_color": "#5cb85c",
"faults": {
"low_battery": 0,
"tempered": 0,
"supervision": 0,
"out_of_order": 0,
"no_response": 0,
"jammed": 0,
"zwave_fault": 0
},
"status": "Off",
"status_display": "OFF",
"statuses": {
"switch": "0"
},
"status_ex": "",
"actions": [],
"status_icons": [],
"icon": "assets/icons/plug.svg"
},
{
"id": "XF:b0c5ba27592a",
"type_tag": "device_type.ipcam",
"type": "IP Cam",
"name": "Test Cam",
"area": "1",
"zone": "1",
"sort_order": "",
"is_window": "",
"bypass": "0",
"schar_24hr": "1",
"sresp_24hr": "5",
"sresp_mode_0": "0",
"sresp_entry_0": "0",
"sresp_exit_0": "0",
"group_name": "Streaming Camera",
"group_id": "397893",
"default_group_id": "1",
"sort_id": "10000",
"sresp_mode_1": "0",
"sresp_entry_1": "0",
"sresp_exit_1": "0",
"sresp_mode_2": "0",
"sresp_entry_2": "0",
"sresp_exit_2": "0",
"sresp_mode_3": "0",
"uuid": "d0a3a1c316891ceb00c20118aae2a133",
"sresp_entry_3": "0",
"sresp_exit_3": "0",
"sresp_mode_4": "0",
"sresp_entry_4": "0",
"sresp_exit_4": "0",
"version": "1.0.2.22G_6.8E_homekit_2.0.9_s2 ABODE oz",
"origin": "abode",
"has_subscription": null,
"onboard": "1",
"s2_grnt_keys": "",
"s2_dsk": "",
"s2_propty": "",
"s2_keys_valid": "",
"zwave_secure_protocol": "",
"control_url": "api/v1/cams/XF:b0c5ba27592a/record",
"deep_link": null,
"status_color": "#5cb85c",
"faults": {
"low_battery": 0,
"tempered": 0,
"supervision": 0,
"out_of_order": 0,
"no_response": 0,
"jammed": 0,
"zwave_fault": 0
},
"status": "Online",
"status_display": "Online",
"statuses": [],
"status_ex": "",
"actions": [
{
"label": "Capture Video",
"value": "a=1&z=1&req=vid;"
},
{
"label": "Turn off Live Video",
"value": "a=1&z=1&privacy=on;"
},
{
"label": "Turn on Live Video",
"value": "a=1&z=1&privacy=off;"
}
],
"status_icons": [],
"icon": "assets/icons/streaming-camera-new.svg",
"control_url_snapshot": "api/v1/cams/XF:b0c5ba27592a/capture",
"ptt_supported": true,
"is_new_camera": 1,
"stream_quality": 2,
"camera_mac": "A0:C1:B2:C3:45:6D",
"privacy": "1",
"enable_audio": "1",
"alarm_video": "25",
"pre_alarm_video": "5",
"mic_volume": "75",
"speaker_volume": "75",
"mic_default_volume": 40,
"speaker_default_volume": 46,
"bandwidth": {
"slider_labels": [
{
"name": "High",
"value": 3
},
{
"name": "Medium",
"value": 2
},
{
"name": "Low",
"value": 1
}
],
"min": 1,
"max": 3,
"step": 1
},
"volume": {
"min": 0,
"max": 100,
"step": 1
},
"video_flip": "0",
"hframe": "480P"
},
{
"id": "ZW:00000004",
"type_tag": "device_type.door_lock",
"type": "Door Lock",
"name": "Test Lock",
"area": "1",
"zone": "16",
"sort_order": "",
"is_window": "",
"bypass": "0",
"schar_24hr": "0",
"sresp_24hr": "0",
"sresp_mode_0": "0",
"sresp_entry_0": "0",
"sresp_exit_0": "0",
"group_name": "Doors/Windows",
"group_id": "377028",
"default_group_id": "1",
"sort_id": "1",
"sresp_mode_1": "0",
"sresp_entry_1": "0",
"sresp_exit_1": "0",
"sresp_mode_2": "0",
"sresp_entry_2": "0",
"sresp_exit_2": "0",
"sresp_mode_3": "0",
"uuid": "51cab3b545d2o34ed7fz02731bda5324",
"sresp_entry_3": "0",
"sresp_exit_3": "0",
"sresp_mode_4": "0",
"sresp_entry_4": "0",
"sresp_exit_4": "0",
"version": "",
"origin": "abode",
"has_subscription": null,
"onboard": "0",
"s2_grnt_keys": "",
"s2_dsk": "",
"s2_propty": "",
"s2_keys_valid": "",
"zwave_secure_protocol": "",
"control_url": "api/v1/control/lock/ZW:00000004",
"deep_link": null,
"status_color": "#5cb85c",
"faults": {
"low_battery": 0,
"tempered": 0,
"supervision": 0,
"out_of_order": 0,
"no_response": 0,
"jammed": 0,
"zwave_fault": 0
},
"status": "LockClosed",
"status_display": "LockClosed",
"statuses": {
"open": "0"
},
"status_ex": "",
"actions": [
{
"label": "Lock",
"value": "a=1&z=16&sw=on;"
},
{
"label": "Unlock",
"value": "a=1&z=16&sw=off;"
}
],
"status_icons": {
"LockOpen": "assets/icons/unlocked-red.svg",
"LockClosed": "assets/icons/locked-green.svg"
},
"icon": "assets/icons/automation-lock.svg",
"automation_settings": null
},
{
"id": "ZW:00000007",
"type_tag": "device_type.secure_barrier",
"type": "Secure Barrier",
"name": "Garage Door",
"area": "1",
"zone": "11",
"sort_order": "0",
"is_window": "0",
"bypass": "0",
"schar_24hr": "0",
"sresp_mode_0": "0",
"sresp_entry_0": "0",
"sresp_exit_0": "0",
"sresp_mode_1": "0",
"sresp_entry_1": "0",
"sresp_exit_1": "0",
"sresp_mode_2": "0",
"sresp_entry_2": "0",
"sresp_exit_2": "0",
"sresp_mode_3": "0",
"uuid": "61cbz3b542d2o33ed2fz02721bda3324",
"sresp_entry_3": "0",
"sresp_exit_3": "0",
"capture_mode": null,
"origin": "abode",
"control_url": "api/v1/control/power_switch/ZW:00000007",
"deep_link": null,
"status_color": "#5cb85c",
"faults": {
"low_battery": 0,
"tempered": 0,
"supervision": 0,
"out_of_order": 0,
"no_response": 0
},
"status": "Closed",
"statuses": {
"hvac_mode": null
},
"status_ex": "",
"actions": [
{
"label": "Close",
"value": "a=1&z=11&sw=off;"
},
{
"label": "Open",
"value": "a=1&z=11&sw=on;"
}
],
"status_icons": {
"Open": "assets/icons/garage-door-red.svg",
"Closed": "assets/icons/garage-door-green.svg"
},
"icon": "assets/icons/garage-door.svg"
}
]

View File

@@ -0,0 +1,115 @@
{
"token": "web-1eb04ba2236d85f49d4b9b4bb91665f2",
"expired_at": "2017-06-05 00:14:12",
"initiate_screen": "timeline",
"user": {
"id": "user@email.com",
"email": "user@email.com",
"first_name": "John",
"last_name": "Doe",
"phone": "5555551212",
"profile_pic": "https://website.com/default-image.svg",
"address": "555 None St.",
"city": "New York City",
"state": "NY",
"zip": "10108",
"country": "US",
"longitude": "0",
"latitude": "0",
"timezone": "America/New_York_City",
"verified": "1",
"plan": "Basic",
"plan_id": "0",
"plan_active": "1",
"cms_code": "1111",
"cms_active": "0",
"cms_started_at": "",
"cms_expiry": "",
"cms_ondemand": "",
"step": "-1",
"cms_permit_no": "",
"opted_plan_id": "",
"stripe_account": "1",
"plan_effective_from": "",
"agreement": "1",
"associate_users": "1",
"owner": "1"
},
"panel": {
"version": "ABGW 0.0.2.17F ABGW-L1-XA36J 3.1.2.6.1 Z-Wave 3.95",
"report_account": "5555",
"online": "1",
"initialized": "1",
"net_version": "ABGW 0.0.2.17F",
"rf_version": "ABGW-L1-XA36J",
"zigbee_version": "3.1.2.6.1",
"z_wave_version": "Z-Wave 3.95",
"timezone": "America/New_York",
"ac_fail": "0",
"battery": "1",
"ip": "192.168.1.1",
"jam": "0",
"rssi": "2",
"setup_zone_1": "1",
"setup_zone_2": "1",
"setup_zone_3": "1",
"setup_zone_4": "1",
"setup_zone_5": "1",
"setup_zone_6": "1",
"setup_zone_7": "1",
"setup_zone_8": "1",
"setup_zone_9": "1",
"setup_zone_10": "1",
"setup_gateway": "1",
"setup_contacts": "1",
"setup_billing": "1",
"setup_users": "1",
"is_cellular": "False",
"plan_set_id": "1",
"dealer_id": "0",
"tz_diff": "-04:00",
"is_demo": "0",
"rf51_version": "ABGW-L1-XA36J",
"model": "L1",
"mac": "00:11:22:33:44:55",
"xml_version": "3",
"dealer_name": "abode",
"id": "0",
"dealer_address": "2625 Middlefield Road #900 Palo Alto CA 94306",
"dealer_domain": "https://my.goabode.com",
"domain_alias": "https://test.goabode.com",
"dealer_support_url": "https://support.goabode.com",
"app_launch_url": "https://goabode.app.link/abode",
"has_wifi": "0",
"mode": {
"area_1": "standby",
"area_2": "standby"
}
},
"permissions": {
"premium_streaming": "0",
"guest_app": "0",
"family_app": "0",
"multiple_accounts": "1",
"google_voice": "1",
"nest": "1",
"alexa": "1",
"ifttt": "1",
"no_associates": "100",
"no_contacts": "2",
"no_devices": "155",
"no_ipcam": "100",
"no_quick_action": "25",
"no_automation": "75",
"media_storage": "3",
"cellular_backup": "0",
"cms_duration": "",
"cms_included": "0"
},
"integrations": {
"nest": {
"is_connected": 0,
"is_home_selected": 0
}
}
}

View File

@@ -0,0 +1,4 @@
{
"code": 200,
"message": "Logout successful."
}

View File

@@ -0,0 +1,5 @@
{
"token_type": "Bearer",
"access_token": "ohyeahthisisanoauthtoken",
"expires_in": 3600
}

View File

@@ -0,0 +1,185 @@
{
"version": "Z3 1.0.2.22G_6.8E_homekit_2.0.9_s2 ABODE oz 19200_UITRF1BD_BL.A30.20181117 4.1.2.6.2 Z-Wave 6.02 Bridge controller library",
"report_account": "12345",
"online": "1",
"initialized": "1",
"net_version": "1.0.2.22G_6.8E_homekit_2.0.9_s2 ABODE oz",
"rf_version": "19200_UITRF1BD_BL.A30.20181117",
"zigbee_version": "4.1.2.6.2",
"z_wave_version": "Z-Wave 6.02 Bridge controller library",
"timezone": "America/Los_Angeles",
"ac_fail": "0",
"battery": "0",
"ip": "",
"jam": "0",
"rssi": "1",
"setup_zone_1": "1",
"setup_zone_2": "1",
"setup_zone_3": "1",
"setup_zone_4": "1",
"setup_zone_5": "1",
"setup_zone_6": "1",
"setup_zone_7": "1",
"setup_zone_8": "1",
"setup_zone_9": "1",
"setup_zone_10": "1",
"setup_gateway": "1",
"setup_contacts": "1",
"setup_billing": "1",
"setup_users": "1",
"is_cellular": "0",
"plan_set_id": "7",
"dealer_id": "0",
"tz_diff": "-08:00",
"model": "Z3",
"has_wifi": "1",
"has_s2_support": "1",
"mode": {
"area_1": "standby",
"area_1_label": "Standby",
"area_2": "standby",
"area_2_label": "Standby"
},
"areas": {
"1": {
"mode": "0",
"modes": {
"0": {
"area": "1",
"mode": "0",
"read_only": "1",
"is_set": "1",
"name": "standby",
"color": null,
"icon_id": null,
"entry1": null,
"entry2": null,
"exit": null,
"icon_path": null
},
"1": {
"area": "1",
"mode": "1",
"read_only": "1",
"is_set": "1",
"name": "away",
"color": null,
"icon_id": null,
"entry1": "30",
"entry2": "60",
"exit": "30",
"icon_path": null
},
"2": {
"area": "1",
"mode": "2",
"read_only": "1",
"is_set": "1",
"name": "home",
"color": null,
"icon_id": null,
"entry1": "30",
"entry2": "60",
"exit": "0",
"icon_path": null
},
"3": {
"area": "1",
"mode": "3",
"read_only": "0",
"is_set": "0",
"name": null,
"color": null,
"icon_id": null,
"entry1": "60",
"entry2": "60",
"exit": "60",
"icon_path": null
},
"4": {
"area": "1",
"mode": "4",
"read_only": "0",
"is_set": "0",
"name": null,
"color": null,
"icon_id": null,
"entry1": "60",
"entry2": "60",
"exit": "60",
"icon_path": null
}
}
},
"2": {
"mode": "0",
"modes": {
"0": {
"area": "2",
"mode": "0",
"read_only": "1",
"is_set": "1",
"name": "standby",
"color": null,
"icon_id": null,
"entry1": null,
"entry2": null,
"exit": null,
"icon_path": null
},
"1": {
"area": "2",
"mode": "1",
"read_only": "1",
"is_set": "1",
"name": "away",
"color": null,
"icon_id": null,
"entry1": "60",
"entry2": "60",
"exit": "60",
"icon_path": null
},
"2": {
"area": "2",
"mode": "2",
"read_only": "1",
"is_set": "1",
"name": "home",
"color": null,
"icon_id": null,
"entry1": "60",
"entry2": "60",
"exit": "60",
"icon_path": null
},
"3": {
"area": "2",
"mode": "3",
"read_only": "0",
"is_set": "0",
"name": null,
"color": null,
"icon_id": null,
"entry1": "60",
"entry2": "60",
"exit": "60",
"icon_path": null
},
"4": {
"area": "2",
"mode": "4",
"read_only": "0",
"is_set": "0",
"name": null,
"color": null,
"icon_id": null,
"entry1": "60",
"entry2": "60",
"exit": "60",
"icon_path": null
}
}
}
}
}

View File

@@ -0,0 +1,151 @@
"""Tests for the Abode alarm control panel device."""
from unittest.mock import PropertyMock, patch
from homeassistant.components.abode import ATTR_DEVICE_ID
from homeassistant.components.alarm_control_panel import (
DOMAIN as ALARM_DOMAIN,
AlarmControlPanelState,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
ATTR_SUPPORTED_FEATURES,
SERVICE_ALARM_ARM_AWAY,
SERVICE_ALARM_ARM_HOME,
SERVICE_ALARM_DISARM,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .common import setup_platform
DEVICE_ID = "alarm_control_panel.abode_alarm"
async def test_entity_registry(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Tests that the devices are registered in the entity registry."""
await setup_platform(hass, ALARM_DOMAIN)
entry = entity_registry.async_get(DEVICE_ID)
# Abode alarm device unique_id is the MAC address
assert entry.unique_id == "001122334455"
async def test_attributes(hass: HomeAssistant) -> None:
"""Test the alarm control panel attributes are correct."""
await setup_platform(hass, ALARM_DOMAIN)
state = hass.states.get(DEVICE_ID)
assert state.state == AlarmControlPanelState.DISARMED
assert state.attributes.get(ATTR_DEVICE_ID) == "area_1"
assert not state.attributes.get("battery_backup")
assert not state.attributes.get("cellular_backup")
assert state.attributes.get(ATTR_FRIENDLY_NAME) == "Abode Alarm"
assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 3
async def test_set_alarm_away(hass: HomeAssistant) -> None:
"""Test the alarm control panel can be set to away."""
with patch(
"jaraco.abode.event_controller.EventController.add_device_callback"
) as mock_callback:
with patch("jaraco.abode.devices.alarm.Alarm.set_away") as mock_set_away:
await setup_platform(hass, ALARM_DOMAIN)
await hass.services.async_call(
ALARM_DOMAIN,
SERVICE_ALARM_ARM_AWAY,
{ATTR_ENTITY_ID: DEVICE_ID},
blocking=True,
)
await hass.async_block_till_done()
mock_set_away.assert_called_once()
with patch(
"jaraco.abode.devices.alarm.Alarm.mode",
new_callable=PropertyMock,
) as mock_mode:
mock_mode.return_value = "away"
update_callback = mock_callback.call_args[0][1]
await hass.async_add_executor_job(update_callback, "area_1")
await hass.async_block_till_done()
state = hass.states.get(DEVICE_ID)
assert state.state == AlarmControlPanelState.ARMED_AWAY
async def test_set_alarm_home(hass: HomeAssistant) -> None:
"""Test the alarm control panel can be set to home."""
with patch(
"jaraco.abode.event_controller.EventController.add_device_callback"
) as mock_callback:
with patch("jaraco.abode.devices.alarm.Alarm.set_home") as mock_set_home:
await setup_platform(hass, ALARM_DOMAIN)
await hass.services.async_call(
ALARM_DOMAIN,
SERVICE_ALARM_ARM_HOME,
{ATTR_ENTITY_ID: DEVICE_ID},
blocking=True,
)
await hass.async_block_till_done()
mock_set_home.assert_called_once()
with patch(
"jaraco.abode.devices.alarm.Alarm.mode", new_callable=PropertyMock
) as mock_mode:
mock_mode.return_value = "home"
update_callback = mock_callback.call_args[0][1]
await hass.async_add_executor_job(update_callback, "area_1")
await hass.async_block_till_done()
state = hass.states.get(DEVICE_ID)
assert state.state == AlarmControlPanelState.ARMED_HOME
async def test_set_alarm_standby(hass: HomeAssistant) -> None:
"""Test the alarm control panel can be set to standby."""
with patch(
"jaraco.abode.event_controller.EventController.add_device_callback"
) as mock_callback:
with patch("jaraco.abode.devices.alarm.Alarm.set_standby") as mock_set_standby:
await setup_platform(hass, ALARM_DOMAIN)
await hass.services.async_call(
ALARM_DOMAIN,
SERVICE_ALARM_DISARM,
{ATTR_ENTITY_ID: DEVICE_ID},
blocking=True,
)
await hass.async_block_till_done()
mock_set_standby.assert_called_once()
with patch(
"jaraco.abode.devices.alarm.Alarm.mode", new_callable=PropertyMock
) as mock_mode:
mock_mode.return_value = "standby"
update_callback = mock_callback.call_args[0][1]
await hass.async_add_executor_job(update_callback, "area_1")
await hass.async_block_till_done()
state = hass.states.get(DEVICE_ID)
assert state.state == AlarmControlPanelState.DISARMED
async def test_state_unknown(hass: HomeAssistant) -> None:
"""Test an unknown alarm control panel state."""
with patch(
"jaraco.abode.devices.alarm.Alarm.mode", new_callable=PropertyMock
) as mock_mode:
await setup_platform(hass, ALARM_DOMAIN)
await hass.async_block_till_done()
mock_mode.return_value = None
state = hass.states.get(DEVICE_ID)
assert state.state == "unknown"

View File

@@ -0,0 +1,43 @@
"""Tests for the Abode binary sensor device."""
from homeassistant.components.abode import ATTR_DEVICE_ID
from homeassistant.components.abode.const import ATTRIBUTION
from homeassistant.components.binary_sensor import (
DOMAIN as BINARY_SENSOR_DOMAIN,
BinarySensorDeviceClass,
)
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_DEVICE_CLASS,
ATTR_FRIENDLY_NAME,
STATE_OFF,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .common import setup_platform
async def test_entity_registry(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Tests that the devices are registered in the entity registry."""
await setup_platform(hass, BINARY_SENSOR_DOMAIN)
entry = entity_registry.async_get("binary_sensor.front_door")
assert entry.unique_id == "2834013428b6035fba7d4054aa7b25a3"
async def test_attributes(hass: HomeAssistant) -> None:
"""Test the binary sensor attributes are correct."""
await setup_platform(hass, BINARY_SENSOR_DOMAIN)
state = hass.states.get("binary_sensor.front_door")
assert state.state == STATE_OFF
assert state.attributes.get(ATTR_ATTRIBUTION) == ATTRIBUTION
assert state.attributes.get(ATTR_DEVICE_ID) == "RF:01430030"
assert not state.attributes.get("battery_low")
assert not state.attributes.get("no_response")
assert state.attributes.get("device_type") == "Door Contact"
assert state.attributes.get(ATTR_FRIENDLY_NAME) == "Front Door"
assert state.attributes.get(ATTR_DEVICE_CLASS) == BinarySensorDeviceClass.WINDOW

View File

@@ -0,0 +1,74 @@
"""Tests for the Abode camera device."""
from unittest.mock import patch
from homeassistant.components.abode.const import DOMAIN as ABODE_DOMAIN
from homeassistant.components.camera import DOMAIN as CAMERA_DOMAIN, CameraState
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .common import setup_platform
async def test_entity_registry(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Tests that the devices are registered in the entity registry."""
await setup_platform(hass, CAMERA_DOMAIN)
entry = entity_registry.async_get("camera.test_cam")
assert entry.unique_id == "d0a3a1c316891ceb00c20118aae2a133"
async def test_attributes(hass: HomeAssistant) -> None:
"""Test the camera attributes are correct."""
await setup_platform(hass, CAMERA_DOMAIN)
state = hass.states.get("camera.test_cam")
assert state.state == CameraState.IDLE
async def test_capture_image(hass: HomeAssistant) -> None:
"""Test the camera capture image service."""
await setup_platform(hass, CAMERA_DOMAIN)
with patch("jaraco.abode.devices.camera.Camera.capture") as mock_capture:
await hass.services.async_call(
ABODE_DOMAIN,
"capture_image",
{ATTR_ENTITY_ID: "camera.test_cam"},
blocking=True,
)
await hass.async_block_till_done()
mock_capture.assert_called_once()
async def test_camera_on(hass: HomeAssistant) -> None:
"""Test the camera turn on service."""
await setup_platform(hass, CAMERA_DOMAIN)
with patch("jaraco.abode.devices.camera.Camera.privacy_mode") as mock_capture:
await hass.services.async_call(
CAMERA_DOMAIN,
"turn_on",
{ATTR_ENTITY_ID: "camera.test_cam"},
blocking=True,
)
await hass.async_block_till_done()
mock_capture.assert_called_once_with(False)
async def test_camera_off(hass: HomeAssistant) -> None:
"""Test the camera turn off service."""
await setup_platform(hass, CAMERA_DOMAIN)
with patch("jaraco.abode.devices.camera.Camera.privacy_mode") as mock_capture:
await hass.services.async_call(
CAMERA_DOMAIN,
"turn_off",
{ATTR_ENTITY_ID: "camera.test_cam"},
blocking=True,
)
await hass.async_block_till_done()
mock_capture.assert_called_once_with(True)

View File

@@ -0,0 +1,186 @@
"""Tests for the Abode config flow."""
from http import HTTPStatus
from unittest.mock import patch
from jaraco.abode.exceptions import (
AuthenticationException as AbodeAuthenticationException,
)
from jaraco.abode.helpers.errors import MFA_CODE_REQUIRED
import pytest
from requests.exceptions import ConnectTimeout
from homeassistant.components.abode.const import CONF_POLLING, DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
pytestmark = pytest.mark.usefixtures("mock_setup_entry")
async def test_one_config_allowed(hass: HomeAssistant) -> None:
"""Test that only one Abode configuration is allowed."""
MockConfigEntry(
domain=DOMAIN,
data={CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"},
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "single_instance_allowed"
async def test_user_flow(hass: HomeAssistant) -> None:
"""Test user flow, with various errors."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
# Test that invalid credentials throws an error.
with patch(
"homeassistant.components.abode.config_flow.Abode",
side_effect=AbodeAuthenticationException(
(HTTPStatus.BAD_REQUEST, "auth error")
),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": "invalid_auth"}
# Test other than invalid credentials throws an error.
with patch(
"homeassistant.components.abode.config_flow.Abode",
side_effect=AbodeAuthenticationException(
(HTTPStatus.INTERNAL_SERVER_ERROR, "connection error")
),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": "cannot_connect"}
# Test login throws an error if connection times out.
with patch(
"homeassistant.components.abode.config_flow.Abode",
side_effect=ConnectTimeout,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": "cannot_connect"}
# Test success
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
with patch("homeassistant.components.abode.config_flow.Abode"):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "user@email.com"
assert result["data"] == {
CONF_USERNAME: "user@email.com",
CONF_PASSWORD: "password",
CONF_POLLING: False,
}
async def test_step_mfa(hass: HomeAssistant) -> None:
"""Test that the MFA step works."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
with patch(
"homeassistant.components.abode.config_flow.Abode",
side_effect=AbodeAuthenticationException(MFA_CODE_REQUIRED),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "mfa"
with patch(
"homeassistant.components.abode.config_flow.Abode",
side_effect=AbodeAuthenticationException(
(HTTPStatus.BAD_REQUEST, "invalid mfa")
),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={"mfa_code": "123456"}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "mfa"
assert result["errors"] == {"base": "invalid_mfa_code"}
with patch("homeassistant.components.abode.config_flow.Abode"):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={"mfa_code": "123456"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "user@email.com"
assert result["data"] == {
CONF_USERNAME: "user@email.com",
CONF_PASSWORD: "password",
CONF_POLLING: False,
}
async def test_step_reauth(hass: HomeAssistant) -> None:
"""Test the reauth flow."""
entry = MockConfigEntry(
domain=DOMAIN,
unique_id="user@email.com",
data={CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"},
)
entry.add_to_hass(hass)
result = await entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
with (
patch("homeassistant.components.abode.config_flow.Abode"),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_USERNAME: "user@email.com",
CONF_PASSWORD: "new_password",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert len(hass.config_entries.async_entries()) == 1
assert entry.data[CONF_PASSWORD] == "new_password"

View File

@@ -0,0 +1,68 @@
"""Tests for the Abode cover device."""
from unittest.mock import patch
from homeassistant.components.abode import ATTR_DEVICE_ID
from homeassistant.components.cover import DOMAIN as COVER_DOMAIN, CoverState
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
SERVICE_CLOSE_COVER,
SERVICE_OPEN_COVER,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .common import setup_platform
DEVICE_ID = "cover.garage_door"
async def test_entity_registry(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Tests that the devices are registered in the entity registry."""
await setup_platform(hass, COVER_DOMAIN)
entry = entity_registry.async_get(DEVICE_ID)
assert entry.unique_id == "61cbz3b542d2o33ed2fz02721bda3324"
async def test_attributes(hass: HomeAssistant) -> None:
"""Test the cover attributes are correct."""
await setup_platform(hass, COVER_DOMAIN)
state = hass.states.get(DEVICE_ID)
assert state.state == CoverState.CLOSED
assert state.attributes.get(ATTR_DEVICE_ID) == "ZW:00000007"
assert not state.attributes.get("battery_low")
assert not state.attributes.get("no_response")
assert state.attributes.get("device_type") == "Secure Barrier"
assert state.attributes.get(ATTR_FRIENDLY_NAME) == "Garage Door"
async def test_open(hass: HomeAssistant) -> None:
"""Test the cover can be opened."""
await setup_platform(hass, COVER_DOMAIN)
with patch("jaraco.abode.devices.cover.Cover.open_cover") as mock_open:
await hass.services.async_call(
COVER_DOMAIN, SERVICE_OPEN_COVER, {ATTR_ENTITY_ID: DEVICE_ID}, blocking=True
)
await hass.async_block_till_done()
mock_open.assert_called_once()
async def test_close(hass: HomeAssistant) -> None:
"""Test the cover can be closed."""
await setup_platform(hass, COVER_DOMAIN)
with patch("jaraco.abode.devices.cover.Cover.close_cover") as mock_close:
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_CLOSE_COVER,
{ATTR_ENTITY_ID: DEVICE_ID},
blocking=True,
)
await hass.async_block_till_done()
mock_close.assert_called_once()

View File

@@ -0,0 +1,95 @@
"""Tests for the Abode module."""
from http import HTTPStatus
from unittest.mock import patch
from jaraco.abode.exceptions import (
AuthenticationException as AbodeAuthenticationException,
Exception as AbodeException,
)
from homeassistant.components.abode import DOMAIN as ABODE_DOMAIN, SERVICE_SETTINGS
from homeassistant.components.alarm_control_panel import DOMAIN as ALARM_DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_USERNAME
from homeassistant.core import HomeAssistant
from .common import setup_platform
async def test_change_settings(hass: HomeAssistant) -> None:
"""Test change_setting service."""
await setup_platform(hass, ALARM_DOMAIN)
with patch("jaraco.abode.client.Client.set_setting") as mock_set_setting:
await hass.services.async_call(
ABODE_DOMAIN,
SERVICE_SETTINGS,
{"setting": "confirm_snd", "value": "loud"},
blocking=True,
)
await hass.async_block_till_done()
mock_set_setting.assert_called_once()
async def test_add_unique_id(hass: HomeAssistant) -> None:
"""Test unique_id is set to Abode username."""
mock_entry = await setup_platform(hass, ALARM_DOMAIN)
# Set unique_id to None to match previous config entries
hass.config_entries.async_update_entry(entry=mock_entry, unique_id=None)
await hass.async_block_till_done()
assert mock_entry.unique_id is None
await hass.config_entries.async_reload(mock_entry.entry_id)
await hass.async_block_till_done()
assert mock_entry.unique_id == mock_entry.data[CONF_USERNAME]
async def test_unload_entry(hass: HomeAssistant) -> None:
"""Test unloading the Abode entry."""
mock_entry = await setup_platform(hass, ALARM_DOMAIN)
with (
patch("jaraco.abode.client.Client.logout") as mock_logout,
patch("jaraco.abode.event_controller.EventController.stop") as mock_events_stop,
):
assert await hass.config_entries.async_unload(mock_entry.entry_id)
mock_logout.assert_called_once()
mock_events_stop.assert_called_once()
async def test_invalid_credentials(hass: HomeAssistant) -> None:
"""Test Abode credentials changing."""
with patch(
"homeassistant.components.abode.Abode",
side_effect=AbodeAuthenticationException(
(HTTPStatus.BAD_REQUEST, "auth error")
),
):
config_entry = await setup_platform(hass, ALARM_DOMAIN)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.SETUP_ERROR
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
assert flows[0]["step_id"] == "reauth_confirm"
hass.config_entries.flow.async_abort(flows[0]["flow_id"])
assert not hass.config_entries.flow.async_progress()
async def test_raise_config_entry_not_ready_when_offline(hass: HomeAssistant) -> None:
"""Config entry state is SETUP_RETRY when abode is offline."""
with patch(
"homeassistant.components.abode.Abode",
side_effect=AbodeException("any"),
):
config_entry = await setup_platform(hass, ALARM_DOMAIN)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.SETUP_RETRY
assert hass.config_entries.flow.async_progress() == []

View File

@@ -0,0 +1,133 @@
"""Tests for the Abode light device."""
from unittest.mock import patch
from homeassistant.components.abode import ATTR_DEVICE_ID
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_MODE,
ATTR_COLOR_TEMP_KELVIN,
ATTR_RGB_COLOR,
ATTR_SUPPORTED_COLOR_MODES,
DOMAIN as LIGHT_DOMAIN,
ColorMode,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
ATTR_SUPPORTED_FEATURES,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_ON,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .common import setup_platform
DEVICE_ID = "light.living_room_lamp"
async def test_entity_registry(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Tests that the devices are registered in the entity registry."""
await setup_platform(hass, LIGHT_DOMAIN)
entry = entity_registry.async_get(DEVICE_ID)
assert entry.unique_id == "741385f4388b2637df4c6b398fe50581"
async def test_attributes(hass: HomeAssistant) -> None:
"""Test the light attributes are correct."""
await setup_platform(hass, LIGHT_DOMAIN)
state = hass.states.get(DEVICE_ID)
assert state.state == STATE_ON
assert state.attributes.get(ATTR_BRIGHTNESS) == 204
assert state.attributes.get(ATTR_RGB_COLOR) == (0, 64, 255)
assert state.attributes.get(ATTR_COLOR_TEMP_KELVIN) is None
assert state.attributes.get(ATTR_DEVICE_ID) == "ZB:db5b1a"
assert not state.attributes.get("battery_low")
assert not state.attributes.get("no_response")
assert state.attributes.get("device_type") == "RGB Dimmer"
assert state.attributes.get(ATTR_FRIENDLY_NAME) == "Living Room Lamp"
assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 0
assert state.attributes.get(ATTR_COLOR_MODE) == ColorMode.HS
assert state.attributes.get(ATTR_SUPPORTED_COLOR_MODES) == [
ColorMode.COLOR_TEMP,
ColorMode.HS,
]
async def test_switch_off(hass: HomeAssistant) -> None:
"""Test the light can be turned off."""
await setup_platform(hass, LIGHT_DOMAIN)
with patch("jaraco.abode.devices.light.Light.switch_off") as mock_switch_off:
await hass.services.async_call(
LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: DEVICE_ID}, blocking=True
)
await hass.async_block_till_done()
mock_switch_off.assert_called_once()
async def test_switch_on(hass: HomeAssistant) -> None:
"""Test the light can be turned on."""
await setup_platform(hass, LIGHT_DOMAIN)
with patch("jaraco.abode.devices.light.Light.switch_on") as mock_switch_on:
await hass.services.async_call(
LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: DEVICE_ID}, blocking=True
)
await hass.async_block_till_done()
mock_switch_on.assert_called_once()
async def test_set_brightness(hass: HomeAssistant) -> None:
"""Test the brightness can be set."""
await setup_platform(hass, LIGHT_DOMAIN)
with patch("jaraco.abode.devices.light.Light.set_level") as mock_set_level:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: DEVICE_ID, "brightness": 100},
blocking=True,
)
await hass.async_block_till_done()
# Brightness is converted in abode.light.AbodeLight.turn_on
mock_set_level.assert_called_once_with(39)
async def test_set_color(hass: HomeAssistant) -> None:
"""Test the color can be set."""
await setup_platform(hass, LIGHT_DOMAIN)
with patch("jaraco.abode.devices.light.Light.set_color") as mock_set_color:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: DEVICE_ID, "hs_color": [240, 100]},
blocking=True,
)
await hass.async_block_till_done()
mock_set_color.assert_called_once_with((240.0, 100.0))
async def test_set_color_temp(hass: HomeAssistant) -> None:
"""Test the color temp can be set."""
await setup_platform(hass, LIGHT_DOMAIN)
with patch(
"jaraco.abode.devices.light.Light.set_color_temp"
) as mock_set_color_temp:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: DEVICE_ID, "color_temp": 309},
blocking=True,
)
await hass.async_block_till_done()
# Color temp is converted in abode.light.AbodeLight.turn_on
mock_set_color_temp.assert_called_once_with(3236)

View File

@@ -0,0 +1,65 @@
"""Tests for the Abode lock device."""
from unittest.mock import patch
from homeassistant.components.abode import ATTR_DEVICE_ID
from homeassistant.components.lock import DOMAIN as LOCK_DOMAIN, LockState
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
SERVICE_LOCK,
SERVICE_UNLOCK,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .common import setup_platform
DEVICE_ID = "lock.test_lock"
async def test_entity_registry(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Tests that the devices are registered in the entity registry."""
await setup_platform(hass, LOCK_DOMAIN)
entry = entity_registry.async_get(DEVICE_ID)
assert entry.unique_id == "51cab3b545d2o34ed7fz02731bda5324"
async def test_attributes(hass: HomeAssistant) -> None:
"""Test the lock attributes are correct."""
await setup_platform(hass, LOCK_DOMAIN)
state = hass.states.get(DEVICE_ID)
assert state.state == LockState.LOCKED
assert state.attributes.get(ATTR_DEVICE_ID) == "ZW:00000004"
assert not state.attributes.get("battery_low")
assert not state.attributes.get("no_response")
assert state.attributes.get("device_type") == "Door Lock"
assert state.attributes.get(ATTR_FRIENDLY_NAME) == "Test Lock"
async def test_lock(hass: HomeAssistant) -> None:
"""Test the lock can be locked."""
await setup_platform(hass, LOCK_DOMAIN)
with patch("jaraco.abode.devices.lock.Lock.lock") as mock_lock:
await hass.services.async_call(
LOCK_DOMAIN, SERVICE_LOCK, {ATTR_ENTITY_ID: DEVICE_ID}, blocking=True
)
await hass.async_block_till_done()
mock_lock.assert_called_once()
async def test_unlock(hass: HomeAssistant) -> None:
"""Test the lock can be unlocked."""
await setup_platform(hass, LOCK_DOMAIN)
with patch("jaraco.abode.devices.lock.Lock.unlock") as mock_unlock:
await hass.services.async_call(
LOCK_DOMAIN, SERVICE_UNLOCK, {ATTR_ENTITY_ID: DEVICE_ID}, blocking=True
)
await hass.async_block_till_done()
mock_unlock.assert_called_once()

View File

@@ -0,0 +1,49 @@
"""Tests for the Abode sensor device."""
from homeassistant.components.abode import ATTR_DEVICE_ID
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN, SensorDeviceClass
from homeassistant.const import (
ATTR_DEVICE_CLASS,
ATTR_FRIENDLY_NAME,
ATTR_UNIT_OF_MEASUREMENT,
PERCENTAGE,
UnitOfTemperature,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .common import setup_platform
async def test_entity_registry(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Tests that the devices are registered in the entity registry."""
await setup_platform(hass, SENSOR_DOMAIN)
entry = entity_registry.async_get("sensor.environment_sensor_humidity")
assert entry.unique_id == "13545b21f4bdcd33d9abd461f8443e65-humidity"
async def test_attributes(hass: HomeAssistant) -> None:
"""Test the sensor attributes are correct."""
await setup_platform(hass, SENSOR_DOMAIN)
state = hass.states.get("sensor.environment_sensor_humidity")
assert state.state == "32.0"
assert state.attributes.get(ATTR_DEVICE_ID) == "RF:02148e70"
assert not state.attributes.get("battery_low")
assert not state.attributes.get("no_response")
assert state.attributes.get("device_type") == "LM"
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == PERCENTAGE
assert state.attributes.get(ATTR_FRIENDLY_NAME) == "Environment Sensor Humidity"
assert state.attributes.get(ATTR_DEVICE_CLASS) == SensorDeviceClass.HUMIDITY
state = hass.states.get("sensor.environment_sensor_illuminance")
assert state.state == "1.0"
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == "lx"
state = hass.states.get("sensor.environment_sensor_temperature")
# Abodepy device JSON reports 19.5, but Home Assistant shows 19.4
assert state.state == "19.4"
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == UnitOfTemperature.CELSIUS

View File

@@ -0,0 +1,129 @@
"""Tests for the Abode switch device."""
from unittest.mock import patch
from homeassistant.components.abode import (
DOMAIN as ABODE_DOMAIN,
SERVICE_TRIGGER_AUTOMATION,
)
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .common import setup_platform
AUTOMATION_ID = "switch.test_automation"
AUTOMATION_UID = "47fae27488f74f55b964a81a066c3a01"
DEVICE_ID = "switch.test_switch"
DEVICE_UID = "0012a4d3614cb7e2b8c9abea31d2fb2a"
async def test_entity_registry(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Tests that the devices are registered in the entity registry."""
await setup_platform(hass, SWITCH_DOMAIN)
entry = entity_registry.async_get(AUTOMATION_ID)
assert entry.unique_id == AUTOMATION_UID
entry = entity_registry.async_get(DEVICE_ID)
assert entry.unique_id == DEVICE_UID
async def test_attributes(hass: HomeAssistant) -> None:
"""Test the switch attributes are correct."""
await setup_platform(hass, SWITCH_DOMAIN)
state = hass.states.get(DEVICE_ID)
assert state.state == STATE_OFF
async def test_switch_on(hass: HomeAssistant) -> None:
"""Test the switch can be turned on."""
await setup_platform(hass, SWITCH_DOMAIN)
with patch("jaraco.abode.devices.switch.Switch.switch_on") as mock_switch_on:
await hass.services.async_call(
SWITCH_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: DEVICE_ID}, blocking=True
)
await hass.async_block_till_done()
mock_switch_on.assert_called_once()
async def test_switch_off(hass: HomeAssistant) -> None:
"""Test the switch can be turned off."""
await setup_platform(hass, SWITCH_DOMAIN)
with patch("jaraco.abode.devices.switch.Switch.switch_off") as mock_switch_off:
await hass.services.async_call(
SWITCH_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: DEVICE_ID}, blocking=True
)
await hass.async_block_till_done()
mock_switch_off.assert_called_once()
async def test_automation_attributes(hass: HomeAssistant) -> None:
"""Test the automation attributes are correct."""
await setup_platform(hass, SWITCH_DOMAIN)
state = hass.states.get(AUTOMATION_ID)
# State is set based on "enabled" key in automation JSON.
assert state.state == STATE_ON
async def test_turn_automation_off(hass: HomeAssistant) -> None:
"""Test the automation can be turned off."""
with patch("jaraco.abode.automation.Automation.enable") as mock_trigger:
await setup_platform(hass, SWITCH_DOMAIN)
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: AUTOMATION_ID},
blocking=True,
)
await hass.async_block_till_done()
mock_trigger.assert_called_once_with(False)
async def test_turn_automation_on(hass: HomeAssistant) -> None:
"""Test the automation can be turned on."""
with patch("jaraco.abode.automation.Automation.enable") as mock_trigger:
await setup_platform(hass, SWITCH_DOMAIN)
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: AUTOMATION_ID},
blocking=True,
)
await hass.async_block_till_done()
mock_trigger.assert_called_once_with(True)
async def test_trigger_automation(hass: HomeAssistant) -> None:
"""Test the trigger automation service."""
await setup_platform(hass, SWITCH_DOMAIN)
with patch("jaraco.abode.automation.Automation.trigger") as mock:
await hass.services.async_call(
ABODE_DOMAIN,
SERVICE_TRIGGER_AUTOMATION,
{ATTR_ENTITY_ID: AUTOMATION_ID},
blocking=True,
)
await hass.async_block_till_done()
mock.assert_called_once()

View File

@@ -0,0 +1,14 @@
"""Common test tools for the acaia integration."""
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def setup_integration(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Set up the acaia integration for testing."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()

View File

@@ -0,0 +1,84 @@
"""Common fixtures for the acaia tests."""
from collections.abc import Generator
from unittest.mock import AsyncMock, MagicMock, patch
from aioacaia.acaiascale import AcaiaDeviceState
from aioacaia.const import UnitMass as AcaiaUnitOfMass
import pytest
from homeassistant.components.acaia.const import CONF_IS_NEW_STYLE_SCALE, DOMAIN
from homeassistant.const import CONF_ADDRESS
from homeassistant.core import HomeAssistant
from . import setup_integration
from tests.common import MockConfigEntry
@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock]:
"""Override async_setup_entry."""
with patch(
"homeassistant.components.acaia.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry
@pytest.fixture
def mock_verify() -> Generator[AsyncMock]:
"""Override is_new_scale check."""
with patch(
"homeassistant.components.acaia.config_flow.is_new_scale", return_value=True
) as mock_verify:
yield mock_verify
@pytest.fixture
def mock_config_entry(hass: HomeAssistant) -> MockConfigEntry:
"""Return the default mocked config entry."""
return MockConfigEntry(
title="LUNAR-DDEEFF",
domain=DOMAIN,
version=1,
data={
CONF_ADDRESS: "aa:bb:cc:dd:ee:ff",
CONF_IS_NEW_STYLE_SCALE: True,
},
unique_id="aa:bb:cc:dd:ee:ff",
)
@pytest.fixture
async def init_integration(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_scale: MagicMock
) -> MockConfigEntry:
"""Set up the acaia integration for testing."""
await setup_integration(hass, mock_config_entry)
return mock_config_entry
@pytest.fixture
def mock_scale() -> Generator[MagicMock]:
"""Return a mocked acaia scale client."""
with (
patch(
"homeassistant.components.acaia.coordinator.AcaiaScale",
autospec=True,
) as scale_mock,
):
scale = scale_mock.return_value
scale.connected = True
scale.mac = "aa:bb:cc:dd:ee:ff"
scale.model = "Lunar"
scale.last_disconnect_time = "1732181388.1895587"
scale.timer_running = True
scale.heartbeat_task = None
scale.process_queue_task = None
scale.device_state = AcaiaDeviceState(
battery_level=42, units=AcaiaUnitOfMass.OUNCES
)
scale.weight = 123.45
scale.timer = 23
scale.flow_rate = 1.23
yield scale

View File

@@ -0,0 +1,48 @@
# serializer version: 1
# name: test_binary_sensors[binary_sensor.lunar_ddeeff_timer_running-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'binary_sensor',
'entity_category': None,
'entity_id': 'binary_sensor.lunar_ddeeff_timer_running',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <BinarySensorDeviceClass.RUNNING: 'running'>,
'original_icon': None,
'original_name': 'Timer running',
'platform': 'acaia',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'timer_running',
'unique_id': 'aa:bb:cc:dd:ee:ff_timer_running',
'unit_of_measurement': None,
})
# ---
# name: test_binary_sensors[binary_sensor.lunar_ddeeff_timer_running-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'running',
'friendly_name': 'LUNAR-DDEEFF Timer running',
}),
'context': <ANY>,
'entity_id': 'binary_sensor.lunar_ddeeff_timer_running',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---

View File

@@ -0,0 +1,139 @@
# serializer version: 1
# name: test_buttons[button.lunar_ddeeff_reset_timer-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'button',
'entity_category': None,
'entity_id': 'button.lunar_ddeeff_reset_timer',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'Reset timer',
'platform': 'acaia',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'reset_timer',
'unique_id': 'aa:bb:cc:dd:ee:ff_reset_timer',
'unit_of_measurement': None,
})
# ---
# name: test_buttons[button.lunar_ddeeff_reset_timer-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'LUNAR-DDEEFF Reset timer',
}),
'context': <ANY>,
'entity_id': 'button.lunar_ddeeff_reset_timer',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'unknown',
})
# ---
# name: test_buttons[button.lunar_ddeeff_start_stop_timer-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'button',
'entity_category': None,
'entity_id': 'button.lunar_ddeeff_start_stop_timer',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'Start/stop timer',
'platform': 'acaia',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'start_stop',
'unique_id': 'aa:bb:cc:dd:ee:ff_start_stop',
'unit_of_measurement': None,
})
# ---
# name: test_buttons[button.lunar_ddeeff_start_stop_timer-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'LUNAR-DDEEFF Start/stop timer',
}),
'context': <ANY>,
'entity_id': 'button.lunar_ddeeff_start_stop_timer',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'unknown',
})
# ---
# name: test_buttons[button.lunar_ddeeff_tare-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'button',
'entity_category': None,
'entity_id': 'button.lunar_ddeeff_tare',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'Tare',
'platform': 'acaia',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'tare',
'unique_id': 'aa:bb:cc:dd:ee:ff_tare',
'unit_of_measurement': None,
})
# ---
# name: test_buttons[button.lunar_ddeeff_tare-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'LUNAR-DDEEFF Tare',
}),
'context': <ANY>,
'entity_id': 'button.lunar_ddeeff_tare',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'unknown',
})
# ---

View File

@@ -0,0 +1,16 @@
# serializer version: 1
# name: test_diagnostics
dict({
'device_state': dict({
'auto_off_time': 0,
'battery_level': 42,
'beeps': True,
'units': 'ounces',
}),
'last_disconnect_time': '1732181388.1895587',
'mac': 'aa:bb:cc:dd:ee:ff',
'model': 'Lunar',
'timer': 23,
'weight': 123.45,
})
# ---

View File

@@ -0,0 +1,37 @@
# serializer version: 1
# name: test_device
DeviceRegistryEntrySnapshot({
'area_id': 'kitchen',
'config_entries': <ANY>,
'configuration_url': None,
'connections': set({
tuple(
'bluetooth',
'aa:bb:cc:dd:ee:ff',
),
}),
'disabled_by': None,
'entry_type': None,
'hw_version': None,
'id': <ANY>,
'identifiers': set({
tuple(
'acaia',
'aa:bb:cc:dd:ee:ff',
),
}),
'is_new': False,
'labels': set({
}),
'manufacturer': 'Acaia',
'model': 'Lunar',
'model_id': None,
'name': 'LUNAR-DDEEFF',
'name_by_user': None,
'primary_config_entry': <ANY>,
'serial_number': None,
'suggested_area': 'Kitchen',
'sw_version': None,
'via_device_id': None,
})
# ---

View File

@@ -0,0 +1,157 @@
# serializer version: 1
# name: test_sensors[sensor.lunar_ddeeff_battery-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': dict({
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
}),
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'sensor',
'entity_category': None,
'entity_id': 'sensor.lunar_ddeeff_battery',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <SensorDeviceClass.BATTERY: 'battery'>,
'original_icon': None,
'original_name': 'Battery',
'platform': 'acaia',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': None,
'unique_id': 'aa:bb:cc:dd:ee:ff_battery',
'unit_of_measurement': '%',
})
# ---
# name: test_sensors[sensor.lunar_ddeeff_battery-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'battery',
'friendly_name': 'LUNAR-DDEEFF Battery',
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
'unit_of_measurement': '%',
}),
'context': <ANY>,
'entity_id': 'sensor.lunar_ddeeff_battery',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '42',
})
# ---
# name: test_sensors[sensor.lunar_ddeeff_volume_flow_rate-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': dict({
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
}),
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'sensor',
'entity_category': None,
'entity_id': 'sensor.lunar_ddeeff_volume_flow_rate',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
'sensor': dict({
'suggested_display_precision': 1,
}),
}),
'original_device_class': <SensorDeviceClass.VOLUME_FLOW_RATE: 'volume_flow_rate'>,
'original_icon': None,
'original_name': 'Volume flow rate',
'platform': 'acaia',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': None,
'unique_id': 'aa:bb:cc:dd:ee:ff_flow_rate',
'unit_of_measurement': <UnitOfVolumeFlowRate.MILLILITERS_PER_SECOND: 'mL/s'>,
})
# ---
# name: test_sensors[sensor.lunar_ddeeff_volume_flow_rate-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'volume_flow_rate',
'friendly_name': 'LUNAR-DDEEFF Volume flow rate',
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
'unit_of_measurement': <UnitOfVolumeFlowRate.MILLILITERS_PER_SECOND: 'mL/s'>,
}),
'context': <ANY>,
'entity_id': 'sensor.lunar_ddeeff_volume_flow_rate',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '1.23',
})
# ---
# name: test_sensors[sensor.lunar_ddeeff_weight-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': dict({
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
}),
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'sensor',
'entity_category': None,
'entity_id': 'sensor.lunar_ddeeff_weight',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <SensorDeviceClass.WEIGHT: 'weight'>,
'original_icon': None,
'original_name': 'Weight',
'platform': 'acaia',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': None,
'unique_id': 'aa:bb:cc:dd:ee:ff_weight',
'unit_of_measurement': <UnitOfMass.OUNCES: 'oz'>,
})
# ---
# name: test_sensors[sensor.lunar_ddeeff_weight-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'weight',
'friendly_name': 'LUNAR-DDEEFF Weight',
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
'unit_of_measurement': <UnitOfMass.OUNCES: 'oz'>,
}),
'context': <ANY>,
'entity_id': 'sensor.lunar_ddeeff_weight',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '123.45',
})
# ---

View File

@@ -0,0 +1,28 @@
"""Test binary sensors for acaia integration."""
from unittest.mock import MagicMock, patch
from syrupy import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
async def test_binary_sensors(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_scale: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the acaia binary sensors."""
with patch("homeassistant.components.acaia.PLATFORMS", [Platform.BINARY_SENSOR]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)

View File

@@ -0,0 +1,90 @@
"""Tests for the acaia buttons."""
from datetime import timedelta
from unittest.mock import MagicMock, patch
from freezegun.api import FrozenDateTimeFactory
from syrupy import SnapshotAssertion
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS
from homeassistant.const import (
ATTR_ENTITY_ID,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
BUTTONS = (
"tare",
"reset_timer",
"start_stop_timer",
)
async def test_buttons(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_scale: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the acaia buttons."""
with patch("homeassistant.components.acaia.PLATFORMS", [Platform.BUTTON]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_button_presses(
hass: HomeAssistant,
mock_scale: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the acaia button presses."""
await setup_integration(hass, mock_config_entry)
for button in BUTTONS:
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{
ATTR_ENTITY_ID: f"button.lunar_ddeeff_{button}",
},
blocking=True,
)
function = getattr(mock_scale, button)
function.assert_called_once()
async def test_buttons_unavailable_on_disconnected_scale(
hass: HomeAssistant,
mock_scale: MagicMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test the acaia buttons are unavailable when the scale is disconnected."""
await setup_integration(hass, mock_config_entry)
for button in BUTTONS:
state = hass.states.get(f"button.lunar_ddeeff_{button}")
assert state
assert state.state == STATE_UNKNOWN
mock_scale.connected = False
freezer.tick(timedelta(minutes=10))
async_fire_time_changed(hass)
await hass.async_block_till_done()
for button in BUTTONS:
state = hass.states.get(f"button.lunar_ddeeff_{button}")
assert state
assert state.state == STATE_UNAVAILABLE

View File

@@ -0,0 +1,242 @@
"""Test the acaia config flow."""
from collections.abc import Generator
from unittest.mock import AsyncMock, patch
from aioacaia.exceptions import AcaiaDeviceNotFound, AcaiaError, AcaiaUnknownDevice
import pytest
from homeassistant.components.acaia.const import CONF_IS_NEW_STYLE_SCALE, DOMAIN
from homeassistant.config_entries import SOURCE_BLUETOOTH, SOURCE_USER
from homeassistant.const import CONF_ADDRESS
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.service_info.bluetooth import BluetoothServiceInfo
from tests.common import MockConfigEntry
service_info = BluetoothServiceInfo(
name="LUNAR-DDEEFF",
address="aa:bb:cc:dd:ee:ff",
rssi=-63,
manufacturer_data={},
service_data={},
service_uuids=[],
source="local",
)
@pytest.fixture
def mock_discovered_service_info() -> Generator[AsyncMock]:
"""Override getting Bluetooth service info."""
with patch(
"homeassistant.components.acaia.config_flow.async_discovered_service_info",
return_value=[service_info],
) as mock_discovered_service_info:
yield mock_discovered_service_info
async def test_form(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_verify: AsyncMock,
mock_discovered_service_info: AsyncMock,
) -> None:
"""Test we get the form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
user_input = {
CONF_ADDRESS: "aa:bb:cc:dd:ee:ff",
}
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=user_input,
)
assert result2["type"] is FlowResultType.CREATE_ENTRY
assert result2["title"] == "LUNAR-DDEEFF"
assert result2["data"] == {
**user_input,
CONF_IS_NEW_STYLE_SCALE: True,
}
async def test_bluetooth_discovery(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_verify: AsyncMock,
) -> None:
"""Test we can discover a device."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_BLUETOOTH}, data=service_info
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "bluetooth_confirm"
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={},
)
assert result2["type"] is FlowResultType.CREATE_ENTRY
assert result2["title"] == service_info.name
assert result2["data"] == {
CONF_ADDRESS: service_info.address,
CONF_IS_NEW_STYLE_SCALE: True,
}
@pytest.mark.parametrize(
("exception", "error"),
[
(AcaiaDeviceNotFound("Error"), "device_not_found"),
(AcaiaError, "unknown"),
(AcaiaUnknownDevice, "unsupported_device"),
],
)
async def test_bluetooth_discovery_errors(
hass: HomeAssistant,
mock_verify: AsyncMock,
exception: Exception,
error: str,
) -> None:
"""Test abortions of Bluetooth discovery."""
mock_verify.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_BLUETOOTH}, data=service_info
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == error
async def test_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_verify: AsyncMock,
mock_discovered_service_info: AsyncMock,
) -> None:
"""Ensure we can't add the same device twice."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_ADDRESS: "aa:bb:cc:dd:ee:ff",
},
)
await hass.async_block_till_done()
assert result2["type"] is FlowResultType.ABORT
assert result2["reason"] == "already_configured"
async def test_already_configured_bluetooth_discovery(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Ensure configure device is not discovered again."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_BLUETOOTH}, data=service_info
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.parametrize(
("exception", "error"),
[
(AcaiaDeviceNotFound("Error"), "device_not_found"),
(AcaiaError, "unknown"),
],
)
async def test_recoverable_config_flow_errors(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_verify: AsyncMock,
mock_discovered_service_info: AsyncMock,
exception: Exception,
error: str,
) -> None:
"""Test recoverable errors."""
mock_verify.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_ADDRESS: "aa:bb:cc:dd:ee:ff",
},
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"] == {"base": error}
# recover
mock_verify.side_effect = None
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
CONF_ADDRESS: "aa:bb:cc:dd:ee:ff",
},
)
assert result3["type"] is FlowResultType.CREATE_ENTRY
async def test_unsupported_device(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_verify: AsyncMock,
mock_discovered_service_info: AsyncMock,
) -> None:
"""Test flow aborts on unsupported device."""
mock_verify.side_effect = AcaiaUnknownDevice
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_ADDRESS: "aa:bb:cc:dd:ee:ff",
},
)
assert result2["type"] is FlowResultType.ABORT
assert result2["reason"] == "unsupported_device"
async def test_no_bluetooth_devices(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_discovered_service_info: AsyncMock,
) -> None:
"""Test flow aborts on unsupported device."""
mock_discovered_service_info.return_value = []
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "no_devices_found"

View File

@@ -0,0 +1,22 @@
"""Tests for the diagnostics data provided by the Acaia integration."""
from syrupy import SnapshotAssertion
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
init_integration: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test diagnostics."""
assert (
await get_diagnostics_for_config_entry(hass, hass_client, init_integration)
== snapshot
)

View File

@@ -0,0 +1,65 @@
"""Test init of acaia integration."""
from datetime import timedelta
from unittest.mock import MagicMock
from aioacaia.exceptions import AcaiaDeviceNotFound, AcaiaError
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy import SnapshotAssertion
from homeassistant.components.acaia.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from tests.common import MockConfigEntry, async_fire_time_changed
pytestmark = pytest.mark.usefixtures("init_integration")
async def test_load_unload_config_entry(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test loading and unloading the integration."""
assert mock_config_entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
@pytest.mark.parametrize(
"exception", [AcaiaError, AcaiaDeviceNotFound("Boom"), TimeoutError]
)
async def test_update_exception_leads_to_active_disconnect(
hass: HomeAssistant,
mock_scale: MagicMock,
freezer: FrozenDateTimeFactory,
exception: Exception,
) -> None:
"""Test scale gets disconnected on exception."""
mock_scale.connect.side_effect = exception
mock_scale.connected = False
freezer.tick(timedelta(minutes=10))
async_fire_time_changed(hass)
await hass.async_block_till_done()
mock_scale.device_disconnected_handler.assert_called_once()
async def test_device(
mock_scale: MagicMock,
device_registry: dr.DeviceRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Snapshot the device from registry."""
device = device_registry.async_get_device({(DOMAIN, mock_scale.mac)})
assert device
assert device == snapshot

View File

@@ -0,0 +1,63 @@
"""Test sensors for acaia integration."""
from unittest.mock import MagicMock, patch
from syrupy import SnapshotAssertion
from homeassistant.const import PERCENTAGE, Platform
from homeassistant.core import HomeAssistant, State
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import (
MockConfigEntry,
mock_restore_cache_with_extra_data,
snapshot_platform,
)
async def test_sensors(
hass: HomeAssistant,
mock_scale: MagicMock,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the Acaia sensors."""
with patch("homeassistant.components.acaia.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_restore_state(
hass: HomeAssistant,
mock_scale: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test battery sensor restore state."""
mock_scale.device_state = None
entity_id = "sensor.lunar_ddeeff_battery"
mock_restore_cache_with_extra_data(
hass,
(
(
State(
entity_id,
"1",
),
{
"native_value": 65,
"native_unit_of_measurement": PERCENTAGE,
},
),
),
)
await setup_integration(hass, mock_config_entry)
state = hass.states.get(entity_id)
assert state
assert state.state == "65"

View File

@@ -0,0 +1,27 @@
"""Tests for AccuWeather."""
from homeassistant.components.accuweather.const import DOMAIN
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def init_integration(hass: HomeAssistant) -> MockConfigEntry:
"""Set up the AccuWeather integration in Home Assistant."""
entry = MockConfigEntry(
domain=DOMAIN,
title="Home",
unique_id="0123456",
data={
"api_key": "32-character-string-1234567890qw",
"latitude": 55.55,
"longitude": 122.12,
"name": "Home",
},
)
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
return entry

View File

@@ -0,0 +1,36 @@
"""Common fixtures for the AccuWeather tests."""
from collections.abc import Generator
from unittest.mock import AsyncMock, patch
import pytest
from homeassistant.components.accuweather.const import DOMAIN
from tests.common import load_json_array_fixture, load_json_object_fixture
@pytest.fixture
def mock_accuweather_client() -> Generator[AsyncMock]:
"""Mock a AccuWeather client."""
current = load_json_object_fixture("current_conditions_data.json", DOMAIN)
forecast = load_json_array_fixture("forecast_data.json", DOMAIN)
location = load_json_object_fixture("location_data.json", DOMAIN)
with (
patch(
"homeassistant.components.accuweather.AccuWeather", autospec=True
) as mock_client,
patch(
"homeassistant.components.accuweather.config_flow.AccuWeather",
new=mock_client,
),
):
client = mock_client.return_value
client.async_get_location.return_value = location
client.async_get_current_conditions.return_value = current
client.async_get_daily_forecast.return_value = forecast
client.location_key = "0123456"
client.requests_remaining = 10
yield client

View File

@@ -0,0 +1,291 @@
{
"WeatherText": "Sunny",
"WeatherIcon": 1,
"HasPrecipitation": false,
"PrecipitationType": null,
"Temperature": {
"Metric": {
"Value": 22.6,
"Unit": "C",
"UnitType": 17
},
"Imperial": {
"Value": 73.0,
"Unit": "F",
"UnitType": 18
}
},
"RealFeelTemperature": {
"Metric": {
"Value": 25.1,
"Unit": "C",
"UnitType": 17
},
"Imperial": {
"Value": 77.0,
"Unit": "F",
"UnitType": 18
}
},
"RealFeelTemperatureShade": {
"Metric": {
"Value": 21.1,
"Unit": "C",
"UnitType": 17
},
"Imperial": {
"Value": 70.0,
"Unit": "F",
"UnitType": 18
}
},
"RelativeHumidity": 67,
"IndoorRelativeHumidity": 67,
"DewPoint": {
"Metric": {
"Value": 16.2,
"Unit": "C",
"UnitType": 17
},
"Imperial": {
"Value": 61.0,
"Unit": "F",
"UnitType": 18
}
},
"Wind": {
"Direction": {
"Degrees": 180,
"Localized": "S",
"English": "S"
},
"Speed": {
"Metric": {
"Value": 14.5,
"Unit": "km/h",
"UnitType": 7
},
"Imperial": {
"Value": 9.0,
"Unit": "mi/h",
"UnitType": 9
}
}
},
"WindGust": {
"Speed": {
"Metric": {
"Value": 20.3,
"Unit": "km/h",
"UnitType": 7
},
"Imperial": {
"Value": 12.6,
"Unit": "mi/h",
"UnitType": 9
}
}
},
"UVIndex": 6,
"UVIndexText": "High",
"Visibility": {
"Metric": {
"Value": 16.1,
"Unit": "km",
"UnitType": 6
},
"Imperial": {
"Value": 10.0,
"Unit": "mi",
"UnitType": 2
}
},
"ObstructionsToVisibility": "",
"CloudCover": 10,
"Ceiling": {
"Metric": {
"Value": 3200.0,
"Unit": "m",
"UnitType": 5
},
"Imperial": {
"Value": 10500.0,
"Unit": "ft",
"UnitType": 0
}
},
"Pressure": {
"Metric": {
"Value": 1012.0,
"Unit": "mb",
"UnitType": 14
},
"Imperial": {
"Value": 29.88,
"Unit": "inHg",
"UnitType": 12
}
},
"PressureTendency": {
"LocalizedText": "Falling",
"Code": "F"
},
"Past24HourTemperatureDeparture": {
"Metric": {
"Value": 0.3,
"Unit": "C",
"UnitType": 17
},
"Imperial": {
"Value": 0.0,
"Unit": "F",
"UnitType": 18
}
},
"ApparentTemperature": {
"Metric": {
"Value": 22.8,
"Unit": "C",
"UnitType": 17
},
"Imperial": {
"Value": 73.0,
"Unit": "F",
"UnitType": 18
}
},
"WindChillTemperature": {
"Metric": {
"Value": 22.8,
"Unit": "C",
"UnitType": 17
},
"Imperial": {
"Value": 73.0,
"Unit": "F",
"UnitType": 18
}
},
"WetBulbTemperature": {
"Metric": {
"Value": 18.6,
"Unit": "C",
"UnitType": 17
},
"Imperial": {
"Value": 65.0,
"Unit": "F",
"UnitType": 18
}
},
"Precip1hr": {
"Metric": {
"Value": 0.0,
"Unit": "mm",
"UnitType": 3
},
"Imperial": {
"Value": 0.0,
"Unit": "in",
"UnitType": 1
}
},
"PrecipitationSummary": {
"Precipitation": {
"Metric": {
"Value": 0.0,
"Unit": "mm",
"UnitType": 3
},
"Imperial": {
"Value": 0.0,
"Unit": "in",
"UnitType": 1
}
},
"PastHour": {
"Metric": {
"Value": 0.0,
"Unit": "mm",
"UnitType": 3
},
"Imperial": {
"Value": 0.0,
"Unit": "in",
"UnitType": 1
}
},
"Past3Hours": {
"Metric": {
"Value": 1.3,
"Unit": "mm",
"UnitType": 3
},
"Imperial": {
"Value": 0.05,
"Unit": "in",
"UnitType": 1
}
},
"Past6Hours": {
"Metric": {
"Value": 1.3,
"Unit": "mm",
"UnitType": 3
},
"Imperial": {
"Value": 0.05,
"Unit": "in",
"UnitType": 1
}
},
"Past9Hours": {
"Metric": {
"Value": 2.5,
"Unit": "mm",
"UnitType": 3
},
"Imperial": {
"Value": 0.1,
"Unit": "in",
"UnitType": 1
}
},
"Past12Hours": {
"Metric": {
"Value": 3.8,
"Unit": "mm",
"UnitType": 3
},
"Imperial": {
"Value": 0.15,
"Unit": "in",
"UnitType": 1
}
},
"Past18Hours": {
"Metric": {
"Value": 5.1,
"Unit": "mm",
"UnitType": 3
},
"Imperial": {
"Value": 0.2,
"Unit": "in",
"UnitType": 1
}
},
"Past24Hours": {
"Metric": {
"Value": 7.6,
"Unit": "mm",
"UnitType": 3
},
"Imperial": {
"Value": 0.3,
"Unit": "in",
"UnitType": 1
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,49 @@
{
"Version": 1,
"Key": "268068",
"Type": "City",
"Rank": 85,
"LocalizedName": "Piątek",
"EnglishName": "Piątek",
"PrimaryPostalCode": "",
"Region": { "ID": "EUR", "LocalizedName": "Europe", "EnglishName": "Europe" },
"Country": { "ID": "PL", "LocalizedName": "Poland", "EnglishName": "Poland" },
"AdministrativeArea": {
"ID": "10",
"LocalizedName": "Łódź",
"EnglishName": "Łódź",
"Level": 1,
"LocalizedType": "Voivodship",
"EnglishType": "Voivodship",
"CountryID": "PL"
},
"TimeZone": {
"Code": "CEST",
"Name": "Europe/Warsaw",
"GmtOffset": 2.0,
"IsDaylightSaving": true,
"NextOffsetChange": "2020-10-25T01:00:00Z"
},
"GeoPosition": {
"Latitude": 52.069,
"Longitude": 19.479,
"Elevation": {
"Metric": { "Value": 94.0, "Unit": "m", "UnitType": 5 },
"Imperial": { "Value": 308.0, "Unit": "ft", "UnitType": 0 }
}
},
"IsAlias": false,
"SupplementalAdminAreas": [
{ "Level": 2, "LocalizedName": "Łęczyca", "EnglishName": "Łęczyca" },
{ "Level": 3, "LocalizedName": "Piątek", "EnglishName": "Piątek" }
],
"DataSets": [
"AirQualityCurrentConditions",
"AirQualityForecasts",
"Alerts",
"ForecastConfidence",
"FutureRadar",
"MinuteCast",
"Radar"
]
}

View File

@@ -0,0 +1,302 @@
# serializer version: 1
# name: test_entry_diagnostics
dict({
'config_entry_data': dict({
'api_key': '**REDACTED**',
'latitude': '**REDACTED**',
'longitude': '**REDACTED**',
'name': 'Home',
}),
'observation_data': dict({
'ApparentTemperature': dict({
'Imperial': dict({
'Unit': 'F',
'UnitType': 18,
'Value': 73.0,
}),
'Metric': dict({
'Unit': 'C',
'UnitType': 17,
'Value': 22.8,
}),
}),
'Ceiling': dict({
'Imperial': dict({
'Unit': 'ft',
'UnitType': 0,
'Value': 10500.0,
}),
'Metric': dict({
'Unit': 'm',
'UnitType': 5,
'Value': 3200.0,
}),
}),
'CloudCover': 10,
'DewPoint': dict({
'Imperial': dict({
'Unit': 'F',
'UnitType': 18,
'Value': 61.0,
}),
'Metric': dict({
'Unit': 'C',
'UnitType': 17,
'Value': 16.2,
}),
}),
'HasPrecipitation': False,
'IndoorRelativeHumidity': 67,
'ObstructionsToVisibility': '',
'Past24HourTemperatureDeparture': dict({
'Imperial': dict({
'Unit': 'F',
'UnitType': 18,
'Value': 0.0,
}),
'Metric': dict({
'Unit': 'C',
'UnitType': 17,
'Value': 0.3,
}),
}),
'Precip1hr': dict({
'Imperial': dict({
'Unit': 'in',
'UnitType': 1,
'Value': 0.0,
}),
'Metric': dict({
'Unit': 'mm',
'UnitType': 3,
'Value': 0.0,
}),
}),
'PrecipitationSummary': dict({
'Past12Hours': dict({
'Imperial': dict({
'Unit': 'in',
'UnitType': 1,
'Value': 0.15,
}),
'Metric': dict({
'Unit': 'mm',
'UnitType': 3,
'Value': 3.8,
}),
}),
'Past18Hours': dict({
'Imperial': dict({
'Unit': 'in',
'UnitType': 1,
'Value': 0.2,
}),
'Metric': dict({
'Unit': 'mm',
'UnitType': 3,
'Value': 5.1,
}),
}),
'Past24Hours': dict({
'Imperial': dict({
'Unit': 'in',
'UnitType': 1,
'Value': 0.3,
}),
'Metric': dict({
'Unit': 'mm',
'UnitType': 3,
'Value': 7.6,
}),
}),
'Past3Hours': dict({
'Imperial': dict({
'Unit': 'in',
'UnitType': 1,
'Value': 0.05,
}),
'Metric': dict({
'Unit': 'mm',
'UnitType': 3,
'Value': 1.3,
}),
}),
'Past6Hours': dict({
'Imperial': dict({
'Unit': 'in',
'UnitType': 1,
'Value': 0.05,
}),
'Metric': dict({
'Unit': 'mm',
'UnitType': 3,
'Value': 1.3,
}),
}),
'Past9Hours': dict({
'Imperial': dict({
'Unit': 'in',
'UnitType': 1,
'Value': 0.1,
}),
'Metric': dict({
'Unit': 'mm',
'UnitType': 3,
'Value': 2.5,
}),
}),
'PastHour': dict({
'Imperial': dict({
'Unit': 'in',
'UnitType': 1,
'Value': 0.0,
}),
'Metric': dict({
'Unit': 'mm',
'UnitType': 3,
'Value': 0.0,
}),
}),
'Precipitation': dict({
'Imperial': dict({
'Unit': 'in',
'UnitType': 1,
'Value': 0.0,
}),
'Metric': dict({
'Unit': 'mm',
'UnitType': 3,
'Value': 0.0,
}),
}),
}),
'PrecipitationType': None,
'Pressure': dict({
'Imperial': dict({
'Unit': 'inHg',
'UnitType': 12,
'Value': 29.88,
}),
'Metric': dict({
'Unit': 'mb',
'UnitType': 14,
'Value': 1012.0,
}),
}),
'PressureTendency': dict({
'Code': 'F',
'LocalizedText': 'Falling',
}),
'RealFeelTemperature': dict({
'Imperial': dict({
'Unit': 'F',
'UnitType': 18,
'Value': 77.0,
}),
'Metric': dict({
'Unit': 'C',
'UnitType': 17,
'Value': 25.1,
}),
}),
'RealFeelTemperatureShade': dict({
'Imperial': dict({
'Unit': 'F',
'UnitType': 18,
'Value': 70.0,
}),
'Metric': dict({
'Unit': 'C',
'UnitType': 17,
'Value': 21.1,
}),
}),
'RelativeHumidity': 67,
'Temperature': dict({
'Imperial': dict({
'Unit': 'F',
'UnitType': 18,
'Value': 73.0,
}),
'Metric': dict({
'Unit': 'C',
'UnitType': 17,
'Value': 22.6,
}),
}),
'UVIndex': 6,
'UVIndexText': 'High',
'Visibility': dict({
'Imperial': dict({
'Unit': 'mi',
'UnitType': 2,
'Value': 10.0,
}),
'Metric': dict({
'Unit': 'km',
'UnitType': 6,
'Value': 16.1,
}),
}),
'WeatherIcon': 1,
'WeatherText': 'Sunny',
'WetBulbTemperature': dict({
'Imperial': dict({
'Unit': 'F',
'UnitType': 18,
'Value': 65.0,
}),
'Metric': dict({
'Unit': 'C',
'UnitType': 17,
'Value': 18.6,
}),
}),
'Wind': dict({
'Direction': dict({
'Degrees': 180,
'English': 'S',
'Localized': 'S',
}),
'Speed': dict({
'Imperial': dict({
'Unit': 'mi/h',
'UnitType': 9,
'Value': 9.0,
}),
'Metric': dict({
'Unit': 'km/h',
'UnitType': 7,
'Value': 14.5,
}),
}),
}),
'WindChillTemperature': dict({
'Imperial': dict({
'Unit': 'F',
'UnitType': 18,
'Value': 73.0,
}),
'Metric': dict({
'Unit': 'C',
'UnitType': 17,
'Value': 22.8,
}),
}),
'WindGust': dict({
'Speed': dict({
'Imperial': dict({
'Unit': 'mi/h',
'UnitType': 9,
'Value': 12.6,
}),
'Metric': dict({
'Unit': 'km/h',
'UnitType': 7,
'Value': 20.3,
}),
}),
}),
}),
})
# ---

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,306 @@
# serializer version: 1
# name: test_forecast_service[get_forecasts]
dict({
'weather.home': dict({
'forecast': list([
dict({
'apparent_temperature': 29.8,
'cloud_coverage': 58,
'condition': 'lightning-rainy',
'datetime': '2020-07-26T05:00:00+00:00',
'humidity': 60,
'precipitation': 2.5,
'precipitation_probability': 60,
'temperature': 29.5,
'templow': 15.4,
'uv_index': 5,
'wind_bearing': 166,
'wind_gust_speed': 29.6,
'wind_speed': 13.0,
}),
dict({
'apparent_temperature': 28.9,
'cloud_coverage': 52,
'condition': 'partlycloudy',
'datetime': '2020-07-27T05:00:00+00:00',
'humidity': 58,
'precipitation': 0.0,
'precipitation_probability': 25,
'temperature': 26.2,
'templow': 15.9,
'uv_index': 7,
'wind_bearing': 297,
'wind_gust_speed': 14.8,
'wind_speed': 9.3,
}),
dict({
'apparent_temperature': 31.6,
'cloud_coverage': 65,
'condition': 'partlycloudy',
'datetime': '2020-07-28T05:00:00+00:00',
'humidity': 52,
'precipitation': 0.0,
'precipitation_probability': 10,
'temperature': 31.7,
'templow': 16.8,
'uv_index': 7,
'wind_bearing': 198,
'wind_gust_speed': 24.1,
'wind_speed': 16.7,
}),
dict({
'apparent_temperature': 26.5,
'cloud_coverage': 45,
'condition': 'partlycloudy',
'datetime': '2020-07-29T05:00:00+00:00',
'humidity': 65,
'precipitation': 0.0,
'precipitation_probability': 9,
'temperature': 24.0,
'templow': 11.7,
'uv_index': 6,
'wind_bearing': 293,
'wind_gust_speed': 24.1,
'wind_speed': 13.0,
}),
dict({
'apparent_temperature': 22.2,
'cloud_coverage': 50,
'condition': 'partlycloudy',
'datetime': '2020-07-30T05:00:00+00:00',
'humidity': 55,
'precipitation': 0.0,
'precipitation_probability': 1,
'temperature': 21.4,
'templow': 12.2,
'uv_index': 7,
'wind_bearing': 280,
'wind_gust_speed': 27.8,
'wind_speed': 18.5,
}),
]),
}),
})
# ---
# name: test_forecast_subscription
list([
dict({
'apparent_temperature': 29.8,
'cloud_coverage': 58,
'condition': 'lightning-rainy',
'datetime': '2020-07-26T05:00:00+00:00',
'humidity': 60,
'precipitation': 2.5,
'precipitation_probability': 60,
'temperature': 29.5,
'templow': 15.4,
'uv_index': 5,
'wind_bearing': 166,
'wind_gust_speed': 29.6,
'wind_speed': 13.0,
}),
dict({
'apparent_temperature': 28.9,
'cloud_coverage': 52,
'condition': 'partlycloudy',
'datetime': '2020-07-27T05:00:00+00:00',
'humidity': 58,
'precipitation': 0.0,
'precipitation_probability': 25,
'temperature': 26.2,
'templow': 15.9,
'uv_index': 7,
'wind_bearing': 297,
'wind_gust_speed': 14.8,
'wind_speed': 9.3,
}),
dict({
'apparent_temperature': 31.6,
'cloud_coverage': 65,
'condition': 'partlycloudy',
'datetime': '2020-07-28T05:00:00+00:00',
'humidity': 52,
'precipitation': 0.0,
'precipitation_probability': 10,
'temperature': 31.7,
'templow': 16.8,
'uv_index': 7,
'wind_bearing': 198,
'wind_gust_speed': 24.1,
'wind_speed': 16.7,
}),
dict({
'apparent_temperature': 26.5,
'cloud_coverage': 45,
'condition': 'partlycloudy',
'datetime': '2020-07-29T05:00:00+00:00',
'humidity': 65,
'precipitation': 0.0,
'precipitation_probability': 9,
'temperature': 24.0,
'templow': 11.7,
'uv_index': 6,
'wind_bearing': 293,
'wind_gust_speed': 24.1,
'wind_speed': 13.0,
}),
dict({
'apparent_temperature': 22.2,
'cloud_coverage': 50,
'condition': 'partlycloudy',
'datetime': '2020-07-30T05:00:00+00:00',
'humidity': 55,
'precipitation': 0.0,
'precipitation_probability': 1,
'temperature': 21.4,
'templow': 12.2,
'uv_index': 7,
'wind_bearing': 280,
'wind_gust_speed': 27.8,
'wind_speed': 18.5,
}),
])
# ---
# name: test_forecast_subscription.1
list([
dict({
'apparent_temperature': 29.8,
'cloud_coverage': 58,
'condition': 'lightning-rainy',
'datetime': '2020-07-26T05:00:00+00:00',
'humidity': 60,
'precipitation': 2.5,
'precipitation_probability': 60,
'temperature': 29.5,
'templow': 15.4,
'uv_index': 5,
'wind_bearing': 166,
'wind_gust_speed': 29.6,
'wind_speed': 13.0,
}),
dict({
'apparent_temperature': 28.9,
'cloud_coverage': 52,
'condition': 'partlycloudy',
'datetime': '2020-07-27T05:00:00+00:00',
'humidity': 58,
'precipitation': 0.0,
'precipitation_probability': 25,
'temperature': 26.2,
'templow': 15.9,
'uv_index': 7,
'wind_bearing': 297,
'wind_gust_speed': 14.8,
'wind_speed': 9.3,
}),
dict({
'apparent_temperature': 31.6,
'cloud_coverage': 65,
'condition': 'partlycloudy',
'datetime': '2020-07-28T05:00:00+00:00',
'humidity': 52,
'precipitation': 0.0,
'precipitation_probability': 10,
'temperature': 31.7,
'templow': 16.8,
'uv_index': 7,
'wind_bearing': 198,
'wind_gust_speed': 24.1,
'wind_speed': 16.7,
}),
dict({
'apparent_temperature': 26.5,
'cloud_coverage': 45,
'condition': 'partlycloudy',
'datetime': '2020-07-29T05:00:00+00:00',
'humidity': 65,
'precipitation': 0.0,
'precipitation_probability': 9,
'temperature': 24.0,
'templow': 11.7,
'uv_index': 6,
'wind_bearing': 293,
'wind_gust_speed': 24.1,
'wind_speed': 13.0,
}),
dict({
'apparent_temperature': 22.2,
'cloud_coverage': 50,
'condition': 'partlycloudy',
'datetime': '2020-07-30T05:00:00+00:00',
'humidity': 55,
'precipitation': 0.0,
'precipitation_probability': 1,
'temperature': 21.4,
'templow': 12.2,
'uv_index': 7,
'wind_bearing': 280,
'wind_gust_speed': 27.8,
'wind_speed': 18.5,
}),
])
# ---
# name: test_weather[weather.home-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'weather',
'entity_category': None,
'entity_id': 'weather.home',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': None,
'platform': 'accuweather',
'previous_unique_id': None,
'supported_features': <WeatherEntityFeature: 1>,
'translation_key': None,
'unique_id': '0123456',
'unit_of_measurement': None,
})
# ---
# name: test_weather[weather.home-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'apparent_temperature': 22.8,
'attribution': 'Data provided by AccuWeather',
'cloud_coverage': 10,
'dew_point': 16.2,
'friendly_name': 'Home',
'humidity': 67,
'precipitation_unit': <UnitOfPrecipitationDepth.MILLIMETERS: 'mm'>,
'pressure': 1012.0,
'pressure_unit': <UnitOfPressure.HPA: 'hPa'>,
'supported_features': <WeatherEntityFeature: 1>,
'temperature': 22.6,
'temperature_unit': <UnitOfTemperature.CELSIUS: '°C'>,
'uv_index': 6,
'visibility': 16.1,
'visibility_unit': <UnitOfLength.KILOMETERS: 'km'>,
'wind_bearing': 180,
'wind_gust_speed': 20.3,
'wind_speed': 14.5,
'wind_speed_unit': <UnitOfSpeed.KILOMETERS_PER_HOUR: 'km/h'>,
}),
'context': <ANY>,
'entity_id': 'weather.home',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'sunny',
})
# ---

View File

@@ -0,0 +1,137 @@
"""Define tests for the AccuWeather config flow."""
from unittest.mock import AsyncMock
from accuweather import ApiError, InvalidApiKeyError, RequestsExceededError
from homeassistant.components.accuweather.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
VALID_CONFIG = {
CONF_NAME: "abcd",
CONF_API_KEY: "32-character-string-1234567890qw",
CONF_LATITUDE: 55.55,
CONF_LONGITUDE: 122.12,
}
async def test_show_form(hass: HomeAssistant) -> None:
"""Test that the form is served with no input."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
async def test_api_key_too_short(hass: HomeAssistant) -> None:
"""Test that errors are shown when API key is too short."""
# The API key length check is done by the library without polling the AccuWeather
# server so we don't need to patch the library method.
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
data={
CONF_NAME: "abcd",
CONF_API_KEY: "foo",
CONF_LATITUDE: 55.55,
CONF_LONGITUDE: 122.12,
},
)
assert result["errors"] == {CONF_API_KEY: "invalid_api_key"}
async def test_invalid_api_key(
hass: HomeAssistant, mock_accuweather_client: AsyncMock
) -> None:
"""Test that errors are shown when API key is invalid."""
mock_accuweather_client.async_get_location.side_effect = InvalidApiKeyError(
"Invalid API key"
)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
data=VALID_CONFIG,
)
assert result["errors"] == {CONF_API_KEY: "invalid_api_key"}
async def test_api_error(
hass: HomeAssistant, mock_accuweather_client: AsyncMock
) -> None:
"""Test API error."""
mock_accuweather_client.async_get_location.side_effect = ApiError(
"Invalid response from AccuWeather API"
)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
data=VALID_CONFIG,
)
assert result["errors"] == {"base": "cannot_connect"}
async def test_requests_exceeded_error(
hass: HomeAssistant, mock_accuweather_client: AsyncMock
) -> None:
"""Test requests exceeded error."""
mock_accuweather_client.async_get_location.side_effect = RequestsExceededError(
"The allowed number of requests has been exceeded"
)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
data=VALID_CONFIG,
)
assert result["errors"] == {CONF_API_KEY: "requests_exceeded"}
async def test_integration_already_exists(
hass: HomeAssistant, mock_accuweather_client: AsyncMock
) -> None:
"""Test we only allow a single config flow."""
MockConfigEntry(
domain=DOMAIN,
unique_id="123456",
data=VALID_CONFIG,
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
data=VALID_CONFIG,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "single_instance_allowed"
async def test_create_entry(
hass: HomeAssistant, mock_accuweather_client: AsyncMock
) -> None:
"""Test that the user step works."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
data=VALID_CONFIG,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "abcd"
assert result["data"][CONF_NAME] == "abcd"
assert result["data"][CONF_LATITUDE] == 55.55
assert result["data"][CONF_LONGITUDE] == 122.12
assert result["data"][CONF_API_KEY] == "32-character-string-1234567890qw"

View File

@@ -0,0 +1,26 @@
"""Test AccuWeather diagnostics."""
from unittest.mock import AsyncMock
from syrupy import SnapshotAssertion
from homeassistant.core import HomeAssistant
from . import init_integration
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_entry_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_accuweather_client: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test config entry diagnostics."""
entry = await init_integration(hass)
result = await get_diagnostics_for_config_entry(hass, hass_client, entry)
assert result == snapshot

View File

@@ -0,0 +1,120 @@
"""Test init of AccuWeather integration."""
from unittest.mock import AsyncMock
from accuweather import ApiError
from freezegun.api import FrozenDateTimeFactory
from homeassistant.components.accuweather.const import (
DOMAIN,
UPDATE_INTERVAL_DAILY_FORECAST,
UPDATE_INTERVAL_OBSERVATION,
)
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import init_integration
from tests.common import MockConfigEntry, async_fire_time_changed
async def test_async_setup_entry(
hass: HomeAssistant, mock_accuweather_client: AsyncMock
) -> None:
"""Test a successful setup entry."""
await init_integration(hass)
state = hass.states.get("weather.home")
assert state is not None
assert state.state != STATE_UNAVAILABLE
assert state.state == "sunny"
async def test_config_not_ready(
hass: HomeAssistant, mock_accuweather_client: AsyncMock
) -> None:
"""Test for setup failure if connection to AccuWeather is missing."""
entry = MockConfigEntry(
domain=DOMAIN,
title="Home",
unique_id="0123456",
data={
"api_key": "32-character-string-1234567890qw",
"latitude": 55.55,
"longitude": 122.12,
"name": "Home",
},
)
mock_accuweather_client.async_get_current_conditions.side_effect = ApiError(
"API Error"
)
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
assert entry.state is ConfigEntryState.SETUP_RETRY
async def test_unload_entry(
hass: HomeAssistant, mock_accuweather_client: AsyncMock
) -> None:
"""Test successful unload of entry."""
entry = await init_integration(hass)
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
assert entry.state is ConfigEntryState.LOADED
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.NOT_LOADED
assert not hass.data.get(DOMAIN)
async def test_update_interval(
hass: HomeAssistant,
mock_accuweather_client: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test correct update interval."""
entry = await init_integration(hass)
assert entry.state is ConfigEntryState.LOADED
assert mock_accuweather_client.async_get_current_conditions.call_count == 1
assert mock_accuweather_client.async_get_daily_forecast.call_count == 1
freezer.tick(UPDATE_INTERVAL_OBSERVATION)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert mock_accuweather_client.async_get_current_conditions.call_count == 2
freezer.tick(UPDATE_INTERVAL_DAILY_FORECAST)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert mock_accuweather_client.async_get_daily_forecast.call_count == 2
async def test_remove_ozone_sensors(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_accuweather_client: AsyncMock,
) -> None:
"""Test remove ozone sensors from registry."""
entity_registry.async_get_or_create(
SENSOR_DOMAIN,
DOMAIN,
"0123456-ozone-0",
suggested_object_id="home_ozone_0d",
disabled_by=None,
)
await init_integration(hass)
entry = entity_registry.async_get("sensor.home_ozone_0d")
assert entry is None

View File

@@ -0,0 +1,203 @@
"""Test sensor of AccuWeather integration."""
from unittest.mock import AsyncMock, patch
from accuweather import ApiError, InvalidApiKeyError, RequestsExceededError
from aiohttp.client_exceptions import ClientConnectorError
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy import SnapshotAssertion
from homeassistant.components.accuweather.const import (
UPDATE_INTERVAL_DAILY_FORECAST,
UPDATE_INTERVAL_OBSERVATION,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_UNIT_OF_MEASUREMENT,
STATE_UNAVAILABLE,
Platform,
UnitOfLength,
UnitOfSpeed,
UnitOfTemperature,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM
from . import init_integration
from tests.common import async_fire_time_changed, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensor(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_accuweather_client: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test states of the sensor."""
with patch("homeassistant.components.accuweather.PLATFORMS", [Platform.SENSOR]):
entry = await init_integration(hass)
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
async def test_availability(
hass: HomeAssistant,
mock_accuweather_client: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Ensure that we mark the entities unavailable correctly when service is offline."""
entity_id = "sensor.home_cloud_ceiling"
await init_integration(hass)
state = hass.states.get(entity_id)
assert state
assert state.state != STATE_UNAVAILABLE
assert state.state == "3200.0"
mock_accuweather_client.async_get_current_conditions.side_effect = ConnectionError
freezer.tick(UPDATE_INTERVAL_OBSERVATION)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_UNAVAILABLE
mock_accuweather_client.async_get_current_conditions.side_effect = None
freezer.tick(UPDATE_INTERVAL_OBSERVATION)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state != STATE_UNAVAILABLE
assert state.state == "3200.0"
@pytest.mark.parametrize(
"exception",
[
ApiError("API Error"),
ConnectionError,
ClientConnectorError,
InvalidApiKeyError("Invalid API key"),
RequestsExceededError("Requests exceeded"),
],
)
async def test_availability_forecast(
hass: HomeAssistant,
exception: Exception,
mock_accuweather_client: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Ensure that we mark the entities unavailable correctly when service is offline."""
entity_id = "sensor.home_hours_of_sun_day_2"
await init_integration(hass)
state = hass.states.get(entity_id)
assert state
assert state.state != STATE_UNAVAILABLE
assert state.state == "5.7"
mock_accuweather_client.async_get_daily_forecast.side_effect = exception
freezer.tick(UPDATE_INTERVAL_DAILY_FORECAST)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_UNAVAILABLE
mock_accuweather_client.async_get_daily_forecast.side_effect = None
freezer.tick(UPDATE_INTERVAL_DAILY_FORECAST)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state != STATE_UNAVAILABLE
assert state.state == "5.7"
async def test_manual_update_entity(
hass: HomeAssistant, mock_accuweather_client: AsyncMock
) -> None:
"""Test manual update entity via service homeassistant/update_entity."""
await init_integration(hass)
await async_setup_component(hass, "homeassistant", {})
assert mock_accuweather_client.async_get_current_conditions.call_count == 1
await hass.services.async_call(
"homeassistant",
"update_entity",
{ATTR_ENTITY_ID: ["sensor.home_cloud_ceiling"]},
blocking=True,
)
assert mock_accuweather_client.async_get_current_conditions.call_count == 2
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensor_imperial_units(
hass: HomeAssistant, mock_accuweather_client: AsyncMock
) -> None:
"""Test states of the sensor without forecast."""
hass.config.units = US_CUSTOMARY_SYSTEM
await init_integration(hass)
state = hass.states.get("sensor.home_cloud_ceiling")
assert state
assert state.state == "10498.687664042"
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == UnitOfLength.FEET
state = hass.states.get("sensor.home_wind_speed")
assert state
assert state.state == "9.0"
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == UnitOfSpeed.MILES_PER_HOUR
state = hass.states.get("sensor.home_realfeel_temperature")
assert state
assert state.state == "77.2"
assert (
state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == UnitOfTemperature.FAHRENHEIT
)
async def test_state_update(
hass: HomeAssistant,
mock_accuweather_client: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Ensure the sensor state changes after updating the data."""
entity_id = "sensor.home_cloud_ceiling"
await init_integration(hass)
state = hass.states.get(entity_id)
assert state
assert state.state != STATE_UNAVAILABLE
assert state.state == "3200.0"
mock_accuweather_client.async_get_current_conditions.return_value["Ceiling"][
"Metric"
]["Value"] = 3300
freezer.tick(UPDATE_INTERVAL_OBSERVATION)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state != STATE_UNAVAILABLE
assert state.state == "3300"

View File

@@ -0,0 +1,63 @@
"""Test AccuWeather system health."""
import asyncio
from unittest.mock import AsyncMock
from aiohttp import ClientError
from homeassistant.components.accuweather.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from . import init_integration
from tests.common import get_system_health_info
from tests.test_util.aiohttp import AiohttpClientMocker
async def test_accuweather_system_health(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
mock_accuweather_client: AsyncMock,
) -> None:
"""Test AccuWeather system health."""
aioclient_mock.get("https://dataservice.accuweather.com/", text="")
await init_integration(hass)
assert await async_setup_component(hass, "system_health", {})
await hass.async_block_till_done()
info = await get_system_health_info(hass, DOMAIN)
for key, val in info.items():
if asyncio.iscoroutine(val):
info[key] = await val
assert info == {
"can_reach_server": "ok",
"remaining_requests": 10,
}
async def test_accuweather_system_health_fail(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
mock_accuweather_client: AsyncMock,
) -> None:
"""Test AccuWeather system health."""
aioclient_mock.get("https://dataservice.accuweather.com/", exc=ClientError)
await init_integration(hass)
assert await async_setup_component(hass, "system_health", {})
await hass.async_block_till_done()
info = await get_system_health_info(hass, DOMAIN)
for key, val in info.items():
if asyncio.iscoroutine(val):
info[key] = await val
assert info == {
"can_reach_server": {"type": "failed", "error": "unreachable"},
"remaining_requests": 10,
}

View File

@@ -0,0 +1,176 @@
"""Test weather of AccuWeather integration."""
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.accuweather.const import UPDATE_INTERVAL_DAILY_FORECAST
from homeassistant.components.weather import (
ATTR_FORECAST_CONDITION,
DOMAIN as WEATHER_DOMAIN,
SERVICE_GET_FORECASTS,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from . import init_integration
from tests.common import async_fire_time_changed, snapshot_platform
from tests.typing import WebSocketGenerator
async def test_weather(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_accuweather_client: AsyncMock,
) -> None:
"""Test states of the weather without forecast."""
with patch("homeassistant.components.accuweather.PLATFORMS", [Platform.WEATHER]):
entry = await init_integration(hass)
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
async def test_availability(
hass: HomeAssistant,
mock_accuweather_client: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Ensure that we mark the entities unavailable correctly when service is offline."""
entity_id = "weather.home"
await init_integration(hass)
state = hass.states.get(entity_id)
assert state
assert state.state != STATE_UNAVAILABLE
assert state.state == "sunny"
mock_accuweather_client.async_get_current_conditions.side_effect = ConnectionError
freezer.tick(UPDATE_INTERVAL_DAILY_FORECAST)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_UNAVAILABLE
mock_accuweather_client.async_get_current_conditions.side_effect = None
freezer.tick(UPDATE_INTERVAL_DAILY_FORECAST)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state != STATE_UNAVAILABLE
assert state.state == "sunny"
async def test_manual_update_entity(
hass: HomeAssistant, mock_accuweather_client: AsyncMock
) -> None:
"""Test manual update entity via service homeassistant/update_entity."""
await init_integration(hass)
await async_setup_component(hass, "homeassistant", {})
assert mock_accuweather_client.async_get_current_conditions.call_count == 1
await hass.services.async_call(
"homeassistant",
"update_entity",
{ATTR_ENTITY_ID: ["weather.home"]},
blocking=True,
)
assert mock_accuweather_client.async_get_current_conditions.call_count == 2
async def test_unsupported_condition_icon_data(
hass: HomeAssistant, mock_accuweather_client: AsyncMock
) -> None:
"""Test with unsupported condition icon data."""
mock_accuweather_client.async_get_current_conditions.return_value["WeatherIcon"] = (
999
)
await init_integration(hass)
state = hass.states.get("weather.home")
assert state.attributes.get(ATTR_FORECAST_CONDITION) is None
@pytest.mark.parametrize(
("service"),
[SERVICE_GET_FORECASTS],
)
async def test_forecast_service(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_accuweather_client: AsyncMock,
service: str,
) -> None:
"""Test multiple forecast."""
await init_integration(hass)
response = await hass.services.async_call(
WEATHER_DOMAIN,
service,
{
"entity_id": "weather.home",
"type": "daily",
},
blocking=True,
return_response=True,
)
assert response == snapshot
async def test_forecast_subscription(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
freezer: FrozenDateTimeFactory,
snapshot: SnapshotAssertion,
mock_accuweather_client: AsyncMock,
) -> None:
"""Test multiple forecast."""
client = await hass_ws_client(hass)
await init_integration(hass)
await client.send_json_auto_id(
{
"type": "weather/subscribe_forecast",
"forecast_type": "daily",
"entity_id": "weather.home",
}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] is None
subscription_id = msg["id"]
msg = await client.receive_json()
assert msg["id"] == subscription_id
assert msg["type"] == "event"
forecast1 = msg["event"]["forecast"]
assert forecast1 != []
assert forecast1 == snapshot
freezer.tick(UPDATE_INTERVAL_DAILY_FORECAST + timedelta(seconds=1))
await hass.async_block_till_done()
msg = await client.receive_json()
assert msg["id"] == subscription_id
assert msg["type"] == "event"
forecast2 = msg["event"]["forecast"]
assert forecast2 != []
assert forecast2 == snapshot

View File

@@ -0,0 +1 @@
"""Tests for the Rollease Acmeda Automate integration."""

View File

@@ -0,0 +1,20 @@
"""Define fixtures available for all Acmeda tests."""
import pytest
from homeassistant.components.acmeda.const import DOMAIN
from homeassistant.const import CONF_HOST
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
@pytest.fixture
def mock_config_entry(hass: HomeAssistant) -> MockConfigEntry:
"""Return the default mocked config entry."""
mock_config_entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_HOST: "127.0.0.1"},
)
mock_config_entry.add_to_hass(hass)
return mock_config_entry

View File

@@ -0,0 +1,150 @@
"""Define tests for the Acmeda config flow."""
from unittest.mock import patch
import aiopulse
import pytest
from homeassistant.components.acmeda.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_HOST
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
DUMMY_HOST1 = "127.0.0.1"
DUMMY_HOST2 = "127.0.0.2"
CONFIG = {
CONF_HOST: DUMMY_HOST1,
}
@pytest.fixture
def mock_hub_discover():
"""Mock the hub discover method."""
with patch("aiopulse.Hub.discover") as mock_discover:
yield mock_discover
@pytest.fixture
def mock_hub_run():
"""Mock the hub run method."""
with patch("aiopulse.Hub.run") as mock_run:
yield mock_run
async def async_generator(items):
"""Async yields items provided in a list."""
for item in items:
yield item
async def test_show_form_no_hubs(hass: HomeAssistant, mock_hub_discover) -> None:
"""Test that flow aborts if no hubs are discovered."""
mock_hub_discover.return_value = async_generator([])
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "no_devices_found"
# Check we performed the discovery
assert len(mock_hub_discover.mock_calls) == 1
async def test_show_form_one_hub(
hass: HomeAssistant, mock_hub_discover, mock_hub_run
) -> None:
"""Test that a config is created when one hub discovered."""
dummy_hub_1 = aiopulse.Hub(DUMMY_HOST1)
dummy_hub_1.id = "ABC123"
mock_hub_discover.return_value = async_generator([dummy_hub_1])
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == dummy_hub_1.id
assert result["result"].data == {
CONF_HOST: DUMMY_HOST1,
}
# Check we performed the discovery
assert len(mock_hub_discover.mock_calls) == 1
async def test_show_form_two_hubs(hass: HomeAssistant, mock_hub_discover) -> None:
"""Test that the form is served when more than one hub discovered."""
dummy_hub_1 = aiopulse.Hub(DUMMY_HOST1)
dummy_hub_1.id = "ABC123"
dummy_hub_2 = aiopulse.Hub(DUMMY_HOST1)
dummy_hub_2.id = "DEF456"
mock_hub_discover.return_value = async_generator([dummy_hub_1, dummy_hub_2])
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
# Check we performed the discovery
assert len(mock_hub_discover.mock_calls) == 1
async def test_create_second_entry(
hass: HomeAssistant, mock_hub_run, mock_hub_discover
) -> None:
"""Test that a config is created when a second hub is discovered."""
dummy_hub_1 = aiopulse.Hub(DUMMY_HOST1)
dummy_hub_1.id = "ABC123"
dummy_hub_2 = aiopulse.Hub(DUMMY_HOST2)
dummy_hub_2.id = "DEF456"
mock_hub_discover.return_value = async_generator([dummy_hub_1, dummy_hub_2])
MockConfigEntry(domain=DOMAIN, unique_id=dummy_hub_1.id, data=CONFIG).add_to_hass(
hass
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == dummy_hub_2.id
assert result["result"].data == {
CONF_HOST: DUMMY_HOST2,
}
async def test_already_configured(hass: HomeAssistant, mock_hub_discover) -> None:
"""Test that flow aborts when all hubs are configured."""
dummy_hub_1 = aiopulse.Hub(DUMMY_HOST1)
dummy_hub_1.id = "ABC123"
mock_hub_discover.return_value = async_generator([dummy_hub_1])
MockConfigEntry(domain=DOMAIN, unique_id=dummy_hub_1.id, data=CONFIG).add_to_hass(
hass
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "no_devices_found"

View File

@@ -0,0 +1,28 @@
"""Define tests for the Acmeda config flow."""
from homeassistant.components.acmeda.const import DOMAIN
from homeassistant.components.cover import DOMAIN as COVER_DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry
async def test_cover_id_migration(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test migrating unique id."""
mock_config_entry.add_to_hass(hass)
entity_registry.async_get_or_create(
COVER_DOMAIN, DOMAIN, 1234567890123, config_entry=mock_config_entry
)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
entities = er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
)
assert len(entities) == 1
assert entities[0].unique_id == "1234567890123"

View File

@@ -0,0 +1,27 @@
"""Define tests for the Acmeda config flow."""
from homeassistant.components.acmeda.const import DOMAIN
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry
async def test_sensor_id_migration(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test migrating unique id."""
mock_config_entry.add_to_hass(hass)
entity_registry.async_get_or_create(
SENSOR_DOMAIN, DOMAIN, 1234567890123, config_entry=mock_config_entry
)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
entities = er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
)
assert len(entities) == 1
assert entities[0].unique_id == "1234567890123"

View File

@@ -0,0 +1 @@
"""Tests for the Adax integration."""

View File

@@ -0,0 +1,373 @@
"""Test the Adax config flow."""
from unittest.mock import patch
import adax_local
from homeassistant import config_entries
from homeassistant.components.adax.const import (
ACCOUNT_ID,
CLOUD,
CONNECTION_TYPE,
DOMAIN,
LOCAL,
WIFI_PSWD,
WIFI_SSID,
)
from homeassistant.const import CONF_PASSWORD
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
TEST_DATA = {
ACCOUNT_ID: 12345,
CONF_PASSWORD: "pswd",
}
async def test_form(hass: HomeAssistant) -> None:
"""Test we get the form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] is None
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONNECTION_TYPE: CLOUD,
},
)
assert result2["type"] is FlowResultType.FORM
with (
patch(
"adax.get_adax_token",
return_value="test_token",
),
patch(
"homeassistant.components.adax.async_setup_entry",
return_value=True,
) as mock_setup_entry,
):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
TEST_DATA,
)
await hass.async_block_till_done()
assert result3["type"] is FlowResultType.CREATE_ENTRY
assert result3["title"] == str(TEST_DATA["account_id"])
assert result3["data"] == {
ACCOUNT_ID: TEST_DATA["account_id"],
CONF_PASSWORD: TEST_DATA["password"],
CONNECTION_TYPE: CLOUD,
}
assert len(mock_setup_entry.mock_calls) == 1
async def test_form_cannot_connect(hass: HomeAssistant) -> None:
"""Test we handle cannot connect error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONNECTION_TYPE: CLOUD,
},
)
assert result2["type"] is FlowResultType.FORM
with patch(
"adax.get_adax_token",
return_value=None,
):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
TEST_DATA,
)
assert result3["type"] is FlowResultType.FORM
assert result3["errors"] == {"base": "cannot_connect"}
async def test_flow_entry_already_exists(hass: HomeAssistant) -> None:
"""Test user input for config_entry that already exists."""
first_entry = MockConfigEntry(
domain="adax",
data=TEST_DATA,
unique_id=str(TEST_DATA[ACCOUNT_ID]),
)
first_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
)
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONNECTION_TYPE: CLOUD,
},
)
assert result2["type"] is FlowResultType.FORM
with patch("adax.get_adax_token", return_value="token"):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
TEST_DATA,
)
await hass.async_block_till_done()
assert result3["type"] is FlowResultType.ABORT
assert result3["reason"] == "already_configured"
# local API:
async def test_local_create_entry(hass: HomeAssistant) -> None:
"""Test create entry from user input."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] is None
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONNECTION_TYPE: LOCAL,
},
)
assert result2["type"] is FlowResultType.FORM
test_data = {
WIFI_SSID: "ssid",
WIFI_PSWD: "pswd",
}
with (
patch(
"homeassistant.components.adax.async_setup_entry",
return_value=True,
),
patch(
"homeassistant.components.adax.config_flow.adax_local.AdaxConfig",
autospec=True,
) as mock_client_class,
):
client = mock_client_class.return_value
client.configure_device.return_value = True
client.device_ip = "192.168.1.4"
client.access_token = "token"
client.mac_id = "8383838"
result = await hass.config_entries.flow.async_configure(
result2["flow_id"],
test_data,
)
test_data[CONNECTION_TYPE] = LOCAL
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "8383838"
assert result["data"] == {
"connection_type": "Local",
"ip_address": "192.168.1.4",
"token": "token",
"unique_id": "8383838",
}
async def test_local_flow_entry_already_exists(hass: HomeAssistant) -> None:
"""Test user input for config_entry that already exists."""
test_data = {
WIFI_SSID: "ssid",
WIFI_PSWD: "pswd",
}
first_entry = MockConfigEntry(
domain="adax",
data=test_data,
unique_id="8383838",
)
first_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] is None
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONNECTION_TYPE: LOCAL,
},
)
assert result2["type"] is FlowResultType.FORM
test_data = {
WIFI_SSID: "ssid",
WIFI_PSWD: "pswd",
}
with patch("adax_local.AdaxConfig", autospec=True) as mock_client_class:
client = mock_client_class.return_value
client.configure_device.return_value = True
client.device_ip = "192.168.1.4"
client.access_token = "token"
client.mac_id = "8383838"
result = await hass.config_entries.flow.async_configure(
result2["flow_id"],
test_data,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_local_connection_error(hass: HomeAssistant) -> None:
"""Test connection error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] is None
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONNECTION_TYPE: LOCAL,
},
)
assert result2["type"] is FlowResultType.FORM
test_data = {
WIFI_SSID: "ssid",
WIFI_PSWD: "pswd",
}
with patch(
"homeassistant.components.adax.config_flow.adax_local.AdaxConfig.configure_device",
return_value=False,
):
result = await hass.config_entries.flow.async_configure(
result2["flow_id"],
test_data,
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "cannot_connect"}
async def test_local_heater_not_available(hass: HomeAssistant) -> None:
"""Test connection error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] is None
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONNECTION_TYPE: LOCAL,
},
)
assert result2["type"] is FlowResultType.FORM
test_data = {
WIFI_SSID: "ssid",
WIFI_PSWD: "pswd",
}
with patch(
"homeassistant.components.adax.config_flow.adax_local.AdaxConfig.configure_device",
side_effect=adax_local.HeaterNotAvailable,
):
result = await hass.config_entries.flow.async_configure(
result2["flow_id"],
test_data,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "heater_not_available"
async def test_local_heater_not_found(hass: HomeAssistant) -> None:
"""Test connection error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] is None
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONNECTION_TYPE: LOCAL,
},
)
assert result2["type"] is FlowResultType.FORM
test_data = {
WIFI_SSID: "ssid",
WIFI_PSWD: "pswd",
}
with patch(
"homeassistant.components.adax.config_flow.adax_local.AdaxConfig.configure_device",
side_effect=adax_local.HeaterNotFound,
):
result = await hass.config_entries.flow.async_configure(
result2["flow_id"],
test_data,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "heater_not_found"
async def test_local_invalid_wifi_cred(hass: HomeAssistant) -> None:
"""Test connection error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] is None
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONNECTION_TYPE: LOCAL,
},
)
assert result2["type"] is FlowResultType.FORM
test_data = {
WIFI_SSID: "ssid",
WIFI_PSWD: "pswd",
}
with patch(
"homeassistant.components.adax.config_flow.adax_local.AdaxConfig.configure_device",
side_effect=adax_local.InvalidWifiCred,
):
result = await hass.config_entries.flow.async_configure(
result2["flow_id"],
test_data,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "invalid_auth"

View File

@@ -0,0 +1 @@
"""Tests for the AdGuard Home integration."""

View File

@@ -0,0 +1,249 @@
"""Tests for the AdGuard Home config flow."""
import aiohttp
from homeassistant import config_entries
from homeassistant.components.adguard.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import (
CONF_HOST,
CONF_PASSWORD,
CONF_PORT,
CONF_SSL,
CONF_USERNAME,
CONF_VERIFY_SSL,
CONTENT_TYPE_JSON,
)
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.service_info.hassio import HassioServiceInfo
from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
FIXTURE_USER_INPUT = {
CONF_HOST: "127.0.0.1",
CONF_PORT: 3000,
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
CONF_SSL: True,
CONF_VERIFY_SSL: True,
}
async def test_show_authenticate_form(hass: HomeAssistant) -> None:
"""Test that the setup form is served."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
async def test_connection_error(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test we show user form on AdGuard Home connection error."""
aioclient_mock.get(
(
f"{'https' if FIXTURE_USER_INPUT[CONF_SSL] else 'http'}"
f"://{FIXTURE_USER_INPUT[CONF_HOST]}"
f":{FIXTURE_USER_INPUT[CONF_PORT]}/control/status"
),
exc=aiohttp.ClientError,
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=FIXTURE_USER_INPUT
)
assert result
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": "cannot_connect"}
async def test_full_flow_implementation(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test registering an integration and finishing flow works."""
aioclient_mock.get(
(
f"{'https' if FIXTURE_USER_INPUT[CONF_SSL] else 'http'}"
f"://{FIXTURE_USER_INPUT[CONF_HOST]}"
f":{FIXTURE_USER_INPUT[CONF_PORT]}/control/status"
),
json={"version": "v0.99.0"},
headers={"Content-Type": CONTENT_TYPE_JSON},
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result
assert result["flow_id"]
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=FIXTURE_USER_INPUT
)
assert result
assert result["type"] is FlowResultType.CREATE_ENTRY
config_entry = result["result"]
assert config_entry.title == FIXTURE_USER_INPUT[CONF_HOST]
assert config_entry.data == {
CONF_HOST: FIXTURE_USER_INPUT[CONF_HOST],
CONF_PASSWORD: FIXTURE_USER_INPUT[CONF_PASSWORD],
CONF_PORT: FIXTURE_USER_INPUT[CONF_PORT],
CONF_SSL: FIXTURE_USER_INPUT[CONF_SSL],
CONF_USERNAME: FIXTURE_USER_INPUT[CONF_USERNAME],
CONF_VERIFY_SSL: FIXTURE_USER_INPUT[CONF_VERIFY_SSL],
}
assert not config_entry.options
async def test_integration_already_exists(hass: HomeAssistant) -> None:
"""Test we only allow a single config flow."""
MockConfigEntry(
domain=DOMAIN, data={"host": "mock-adguard", "port": "3000"}
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
data={"host": "mock-adguard", "port": "3000"},
context={"source": config_entries.SOURCE_USER},
)
assert result
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_hassio_already_configured(hass: HomeAssistant) -> None:
"""Test we only allow a single config flow."""
MockConfigEntry(
domain=DOMAIN, data={"host": "mock-adguard", "port": "3000"}
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
data=HassioServiceInfo(
config={
"addon": "AdGuard Home Addon",
"host": "mock-adguard",
"port": "3000",
},
name="AdGuard Home Addon",
slug="adguard",
uuid="1234",
),
context={"source": config_entries.SOURCE_HASSIO},
)
assert result
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_hassio_ignored(hass: HomeAssistant) -> None:
"""Test we supervisor discovered instance can be ignored."""
MockConfigEntry(domain=DOMAIN, source=config_entries.SOURCE_IGNORE).add_to_hass(
hass
)
result = await hass.config_entries.flow.async_init(
DOMAIN,
data=HassioServiceInfo(
config={
"addon": "AdGuard Home Addon",
"host": "mock-adguard",
"port": "3000",
},
name="AdGuard Home Addon",
slug="adguard",
uuid="1234",
),
context={"source": config_entries.SOURCE_HASSIO},
)
assert result
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_hassio_confirm(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test we can finish a config flow."""
aioclient_mock.get(
"http://mock-adguard:3000/control/status",
json={"version": "v0.99.0"},
headers={"Content-Type": CONTENT_TYPE_JSON},
)
result = await hass.config_entries.flow.async_init(
DOMAIN,
data=HassioServiceInfo(
config={
"addon": "AdGuard Home Addon",
"host": "mock-adguard",
"port": 3000,
},
name="AdGuard Home Addon",
slug="adguard",
uuid="1234",
),
context={"source": config_entries.SOURCE_HASSIO},
)
assert result
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "hassio_confirm"
assert result["description_placeholders"] == {"addon": "AdGuard Home Addon"}
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result
assert result["type"] is FlowResultType.CREATE_ENTRY
config_entry = result["result"]
assert config_entry.title == "AdGuard Home Addon"
assert config_entry.data == {
CONF_HOST: "mock-adguard",
CONF_PASSWORD: None,
CONF_PORT: 3000,
CONF_SSL: False,
CONF_USERNAME: None,
CONF_VERIFY_SSL: True,
}
async def test_hassio_connection_error(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test we show Hass.io confirm form on AdGuard Home connection error."""
aioclient_mock.get(
"http://mock-adguard:3000/control/status", exc=aiohttp.ClientError
)
result = await hass.config_entries.flow.async_init(
DOMAIN,
data=HassioServiceInfo(
config={
"addon": "AdGuard Home Addon",
"host": "mock-adguard",
"port": 3000,
},
name="AdGuard Home Addon",
slug="adguard",
uuid="1234",
),
context={"source": config_entries.SOURCE_HASSIO},
)
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "hassio_confirm"
assert result["errors"] == {"base": "cannot_connect"}

View File

@@ -0,0 +1,59 @@
"""Tests for the Advantage Air component."""
from unittest.mock import AsyncMock, patch
from homeassistant.components.advantage_air.const import DOMAIN
from homeassistant.const import CONF_IP_ADDRESS, CONF_PORT
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry, load_json_object_fixture
TEST_SYSTEM_DATA = load_json_object_fixture("getSystemData.json", DOMAIN)
TEST_SET_RESPONSE = None
USER_INPUT = {
CONF_IP_ADDRESS: "1.2.3.4",
CONF_PORT: 2025,
}
TEST_SYSTEM_URL = (
f"http://{USER_INPUT[CONF_IP_ADDRESS]}:{USER_INPUT[CONF_PORT]}/getSystemData"
)
TEST_SET_URL = f"http://{USER_INPUT[CONF_IP_ADDRESS]}:{USER_INPUT[CONF_PORT]}/setAircon"
TEST_SET_LIGHT_URL = (
f"http://{USER_INPUT[CONF_IP_ADDRESS]}:{USER_INPUT[CONF_PORT]}/setLights"
)
TEST_SET_THING_URL = (
f"http://{USER_INPUT[CONF_IP_ADDRESS]}:{USER_INPUT[CONF_PORT]}/setThings"
)
def patch_get(return_value=TEST_SYSTEM_DATA, side_effect=None):
"""Patch the Advantage Air async_get method."""
return patch(
"homeassistant.components.advantage_air.advantage_air.async_get",
new=AsyncMock(return_value=return_value, side_effect=side_effect),
)
def patch_update(return_value=True, side_effect=None):
"""Patch the Advantage Air async_set method."""
return patch(
"homeassistant.components.advantage_air.advantage_air._endpoint.async_update",
new=AsyncMock(return_value=return_value, side_effect=side_effect),
)
async def add_mock_config(hass: HomeAssistant) -> MockConfigEntry:
"""Create a fake Advantage Air Config Entry."""
entry = MockConfigEntry(
domain=DOMAIN,
title="test entry",
unique_id="0123456",
data=USER_INPUT,
)
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
return entry

View File

@@ -0,0 +1,21 @@
"""Fixtures for advantage_air."""
from __future__ import annotations
import pytest
from . import patch_get, patch_update
@pytest.fixture
def mock_get():
"""Fixture to patch the Advantage Air async_get method."""
with patch_get() as mock_get:
yield mock_get
@pytest.fixture
def mock_update():
"""Fixture to patch the Advantage Air async_get method."""
with patch_update() as mock_get:
yield mock_get

View File

@@ -0,0 +1,289 @@
{
"aircons": {
"ac1": {
"info": {
"aaAutoFanModeEnabled": false,
"climateControlModeEnabled": false,
"climateControlModeIsRunning": false,
"countDownToOff": 10,
"countDownToOn": 0,
"fan": "high",
"filterCleanStatus": 0,
"freshAirStatus": "off",
"mode": "vent",
"myAutoModeEnabled": false,
"myAutoModeIsRunning": false,
"myZone": 1,
"name": "myzone",
"setTemp": 24,
"state": "on"
},
"zones": {
"z01": {
"error": 0,
"maxDamper": 100,
"measuredTemp": 25,
"minDamper": 0,
"motion": 20,
"motionConfig": 2,
"name": "Zone open with Sensor",
"number": 1,
"rssi": 40,
"setTemp": 24,
"state": "open",
"type": 1,
"value": 100
},
"z02": {
"error": 0,
"maxDamper": 100,
"measuredTemp": 25,
"minDamper": 0,
"motion": 21,
"motionConfig": 2,
"name": "Zone closed with Sensor",
"number": 2,
"rssi": 10,
"setTemp": 24,
"state": "close",
"type": 1,
"value": 0
},
"z03": {
"error": 0,
"maxDamper": 100,
"measuredTemp": 25,
"minDamper": 0,
"motion": 22,
"motionConfig": 2,
"name": "Zone 3",
"number": 3,
"rssi": 25,
"setTemp": 24,
"state": "close",
"type": 1,
"value": 0
},
"z04": {
"error": 0,
"maxDamper": 100,
"measuredTemp": 25,
"minDamper": 0,
"motion": 1,
"motionConfig": 1,
"name": "Zone 4",
"number": 4,
"rssi": 75,
"setTemp": 24,
"state": "close",
"type": 1,
"value": 0
},
"z05": {
"error": 0,
"maxDamper": 100,
"measuredTemp": 25,
"minDamper": 0,
"motion": 5,
"motionConfig": 1,
"name": "Zone 5",
"number": 5,
"rssi": 100,
"setTemp": 24,
"state": "close",
"type": 1,
"value": 0
}
}
},
"ac2": {
"info": {
"aaAutoFanModeEnabled": true,
"climateControlModeEnabled": true,
"climateControlModeIsRunning": false,
"countDownToOff": 0,
"countDownToOn": 20,
"fan": "autoAA",
"filterCleanStatus": 1,
"freshAirStatus": "none",
"mode": "cool",
"myAutoModeCurrentSetMode": "cool",
"myAutoModeEnabled": false,
"myAutoModeIsRunning": false,
"myZone": 1,
"name": "mytemp",
"setTemp": 24,
"state": "off"
},
"zones": {
"z01": {
"error": 0,
"maxDamper": 100,
"measuredTemp": 25,
"minDamper": 0,
"motion": 20,
"motionConfig": 2,
"name": "Zone A",
"number": 1,
"rssi": 40,
"setTemp": 24,
"state": "open",
"type": 1,
"value": 100
},
"z02": {
"error": 0,
"maxDamper": 100,
"measuredTemp": 26,
"minDamper": 0,
"motion": 21,
"motionConfig": 2,
"name": "Zone B",
"number": 2,
"rssi": 10,
"setTemp": 23,
"state": "open",
"type": 1,
"value": 50
}
}
},
"ac3": {
"info": {
"aaAutoFanModeEnabled": true,
"climateControlModeEnabled": false,
"climateControlModeIsRunning": false,
"countDownToOff": 0,
"countDownToOn": 0,
"fan": "autoAA",
"filterCleanStatus": 1,
"freshAirStatus": "none",
"mode": "myauto",
"myAutoModeCurrentSetMode": "cool",
"myAutoModeEnabled": true,
"myAutoModeIsRunning": true,
"myAutoCoolTargetTemp": 24,
"myAutoHeatTargetTemp": 20,
"myZone": 0,
"name": "myauto",
"setTemp": 24,
"state": "on"
},
"zones": {
"z01": {
"error": 0,
"maxDamper": 100,
"measuredTemp": 0,
"minDamper": 0,
"motion": 0,
"motionConfig": 0,
"name": "Zone Y",
"number": 1,
"rssi": 0,
"setTemp": 24,
"state": "open",
"type": 0,
"value": 100
},
"z02": {
"error": 0,
"maxDamper": 100,
"measuredTemp": 0,
"minDamper": 0,
"motion": 0,
"motionConfig": 0,
"name": "Zone Z",
"number": 2,
"rssi": 0,
"setTemp": 24,
"state": "close",
"type": 0,
"value": 0
}
}
}
},
"myLights": {
"lights": {
"100": {
"id": "100",
"moduleType": "RM2",
"name": "Light A",
"relay": true,
"state": "off"
},
"101": {
"id": "101",
"name": "Light B",
"value": 50,
"state": "on"
}
}
},
"myThings": {
"things": {
"200": {
"buttonType": "upDown",
"channelDipState": 1,
"id": "200",
"name": "Blind 1",
"value": 100
},
"201": {
"buttonType": "upDown",
"channelDipState": 2,
"id": "201",
"name": "Blind 2",
"value": 0
},
"202": {
"buttonType": "openClose",
"channelDipState": 3,
"id": "202",
"name": "Garage",
"value": 100
},
"203": {
"buttonType": "onOff",
"channelDipState": 4,
"id": "203",
"name": "Thing Light",
"value": 100
},
"204": {
"buttonType": "upDown",
"channelDipState": 5,
"id": "204",
"name": "Thing Light Dimmable",
"value": 100
},
"205": {
"buttonType": "onOff",
"channelDipState": 8,
"id": "205",
"name": "Relay",
"value": 100
},
"206": {
"buttonType": "onOff",
"channelDipState": 9,
"id": "206",
"name": "Fan",
"value": 100
}
}
},
"system": {
"hasAircons": true,
"hasLights": true,
"hasSensors": false,
"hasThings": true,
"hasThingsBOG": false,
"hasThingsLight": false,
"needsUpdate": false,
"name": "testname",
"rid": "uniqueid",
"sysType": "e-zone",
"myAppRev": "1.234"
}
}

View File

@@ -0,0 +1,49 @@
{
"aircons": {
"ac1": {
"info": {
"climateControlModeIsRunning": false,
"countDownToOff": 10,
"countDownToOn": 0,
"fan": "high",
"filterCleanStatus": 0,
"freshAirStatus": "off",
"mode": "vent",
"myZone": 1,
"name": "AC One",
"setTemp": 24,
"state": "on"
},
"zones": {
"z01": {
"error": 0,
"maxDamper": 100,
"measuredTemp": 25,
"minDamper": 0,
"motion": 20,
"motionConfig": 2,
"name": "Zone open with Sensor",
"number": 1,
"rssi": 40,
"setTemp": 24,
"state": "open",
"type": 1,
"value": 100
}
}
}
},
"system": {
"hasAircons": false,
"hasLights": false,
"hasSensors": false,
"hasThings": false,
"hasThingsBOG": false,
"hasThingsLight": false,
"needsUpdate": true,
"name": "testname",
"rid": "uniqueid",
"sysType": "e-zone",
"myAppRev": "1.234"
}
}

View File

@@ -0,0 +1,4 @@
{
"ack": true,
"request": "setAircon"
}

View File

@@ -0,0 +1,71 @@
# serializer version: 1
# name: test_climate_myauto_main[climate.myauto-fanmode]
dict({
'ac3': dict({
'info': dict({
'fan': 'autoAA',
}),
}),
})
# ---
# name: test_climate_myauto_main[climate.myauto-settemp]
dict({
'ac3': dict({
'info': dict({
'myAutoCoolTargetTemp': 23.0,
'myAutoHeatTargetTemp': 21.0,
}),
}),
})
# ---
# name: test_climate_myauto_main[climate.myauto]
StateSnapshot({
'attributes': ReadOnlyDict({
'current_temperature': None,
'fan_mode': 'auto',
'fan_modes': list([
'low',
'medium',
'high',
'auto',
]),
'friendly_name': 'myauto',
'hvac_modes': list([
<HVACMode.OFF: 'off'>,
<HVACMode.COOL: 'cool'>,
<HVACMode.HEAT: 'heat'>,
<HVACMode.FAN_ONLY: 'fan_only'>,
<HVACMode.DRY: 'dry'>,
<HVACMode.HEAT_COOL: 'heat_cool'>,
]),
'max_temp': 32,
'min_temp': 16,
'preset_mode': 'MyAuto',
'preset_modes': list([
'MyZone',
'MyTemp',
'MyAuto',
]),
'supported_features': <ClimateEntityFeature: 410>,
'target_temp_high': 24,
'target_temp_low': 20,
'target_temp_step': 1,
}),
'context': <ANY>,
'entity_id': 'climate.myauto',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'heat_cool',
})
# ---
# name: test_climate_myzone_main[climate.myzone-preset]
dict({
'ac1': dict({
'info': dict({
'climateControlModeEnabled': False,
'myAutoModeEnabled': True,
}),
}),
})
# ---

View File

@@ -0,0 +1,292 @@
# serializer version: 1
# name: test_select_async_setup_entry
dict({
'aircons': dict({
'ac1': dict({
'info': dict({
'aaAutoFanModeEnabled': False,
'climateControlModeEnabled': False,
'climateControlModeIsRunning': False,
'countDownToOff': 10,
'countDownToOn': 0,
'fan': 'high',
'filterCleanStatus': 0,
'freshAirStatus': 'off',
'mode': 'vent',
'myAutoModeEnabled': False,
'myAutoModeIsRunning': False,
'myZone': 1,
'name': 'myzone',
'setTemp': 24,
'state': 'on',
}),
'zones': dict({
'z01': dict({
'error': 0,
'maxDamper': 100,
'measuredTemp': 25,
'minDamper': 0,
'motion': 20,
'motionConfig': 2,
'name': 'Zone open with Sensor',
'number': 1,
'rssi': 40,
'setTemp': 24,
'state': 'open',
'type': 1,
'value': 100,
}),
'z02': dict({
'error': 0,
'maxDamper': 100,
'measuredTemp': 25,
'minDamper': 0,
'motion': 21,
'motionConfig': 2,
'name': 'Zone closed with Sensor',
'number': 2,
'rssi': 10,
'setTemp': 24,
'state': 'close',
'type': 1,
'value': 0,
}),
'z03': dict({
'error': 0,
'maxDamper': 100,
'measuredTemp': 25,
'minDamper': 0,
'motion': 22,
'motionConfig': 2,
'name': 'Zone 3',
'number': 3,
'rssi': 25,
'setTemp': 24,
'state': 'close',
'type': 1,
'value': 0,
}),
'z04': dict({
'error': 0,
'maxDamper': 100,
'measuredTemp': 25,
'minDamper': 0,
'motion': 1,
'motionConfig': 1,
'name': 'Zone 4',
'number': 4,
'rssi': 75,
'setTemp': 24,
'state': 'close',
'type': 1,
'value': 0,
}),
'z05': dict({
'error': 0,
'maxDamper': 100,
'measuredTemp': 25,
'minDamper': 0,
'motion': 5,
'motionConfig': 1,
'name': 'Zone 5',
'number': 5,
'rssi': 100,
'setTemp': 24,
'state': 'close',
'type': 1,
'value': 0,
}),
}),
}),
'ac2': dict({
'info': dict({
'aaAutoFanModeEnabled': True,
'climateControlModeEnabled': True,
'climateControlModeIsRunning': False,
'countDownToOff': 0,
'countDownToOn': 20,
'fan': 'autoAA',
'filterCleanStatus': 1,
'freshAirStatus': 'none',
'mode': 'cool',
'myAutoModeCurrentSetMode': 'cool',
'myAutoModeEnabled': False,
'myAutoModeIsRunning': False,
'myZone': 1,
'name': 'mytemp',
'setTemp': 24,
'state': 'off',
}),
'zones': dict({
'z01': dict({
'error': 0,
'maxDamper': 100,
'measuredTemp': 25,
'minDamper': 0,
'motion': 20,
'motionConfig': 2,
'name': 'Zone A',
'number': 1,
'rssi': 40,
'setTemp': 24,
'state': 'open',
'type': 1,
'value': 100,
}),
'z02': dict({
'error': 0,
'maxDamper': 100,
'measuredTemp': 26,
'minDamper': 0,
'motion': 21,
'motionConfig': 2,
'name': 'Zone B',
'number': 2,
'rssi': 10,
'setTemp': 23,
'state': 'open',
'type': 1,
'value': 50,
}),
}),
}),
'ac3': dict({
'info': dict({
'aaAutoFanModeEnabled': True,
'climateControlModeEnabled': False,
'climateControlModeIsRunning': False,
'countDownToOff': 0,
'countDownToOn': 0,
'fan': 'autoAA',
'filterCleanStatus': 1,
'freshAirStatus': 'none',
'mode': 'myauto',
'myAutoCoolTargetTemp': 24,
'myAutoHeatTargetTemp': 20,
'myAutoModeCurrentSetMode': 'cool',
'myAutoModeEnabled': True,
'myAutoModeIsRunning': True,
'myZone': 0,
'name': 'myauto',
'setTemp': 24,
'state': 'on',
}),
'zones': dict({
'z01': dict({
'error': 0,
'maxDamper': 100,
'measuredTemp': 0,
'minDamper': 0,
'motion': 0,
'motionConfig': 0,
'name': 'Zone Y',
'number': 1,
'rssi': 0,
'setTemp': 24,
'state': 'open',
'type': 0,
'value': 100,
}),
'z02': dict({
'error': 0,
'maxDamper': 100,
'measuredTemp': 0,
'minDamper': 0,
'motion': 0,
'motionConfig': 0,
'name': 'Zone Z',
'number': 2,
'rssi': 0,
'setTemp': 24,
'state': 'close',
'type': 0,
'value': 0,
}),
}),
}),
}),
'myLights': dict({
'lights': dict({
'100': dict({
'id': '100',
'moduleType': 'RM2',
'name': 'Light A',
'relay': True,
'state': 'off',
}),
'101': dict({
'id': '101',
'name': 'Light B',
'state': 'on',
'value': 50,
}),
}),
}),
'myThings': dict({
'things': dict({
'200': dict({
'buttonType': 'upDown',
'channelDipState': 1,
'id': '200',
'name': 'Blind 1',
'value': 100,
}),
'201': dict({
'buttonType': 'upDown',
'channelDipState': 2,
'id': '201',
'name': 'Blind 2',
'value': 0,
}),
'202': dict({
'buttonType': 'openClose',
'channelDipState': 3,
'id': '202',
'name': 'Garage',
'value': 100,
}),
'203': dict({
'buttonType': 'onOff',
'channelDipState': 4,
'id': '203',
'name': 'Thing Light',
'value': 100,
}),
'204': dict({
'buttonType': 'upDown',
'channelDipState': 5,
'id': '204',
'name': 'Thing Light Dimmable',
'value': 100,
}),
'205': dict({
'buttonType': 'onOff',
'channelDipState': 8,
'id': '205',
'name': 'Relay',
'value': 100,
}),
'206': dict({
'buttonType': 'onOff',
'channelDipState': 9,
'id': '206',
'name': 'Fan',
'value': 100,
}),
}),
}),
'system': dict({
'hasAircons': True,
'hasLights': True,
'hasSensors': False,
'hasThings': True,
'hasThingsBOG': False,
'hasThingsLight': False,
'myAppRev': '1.234',
'name': 'testname',
'needsUpdate': False,
'rid': '**REDACTED**',
'sysType': 'e-zone',
}),
})
# ---

View File

@@ -0,0 +1,34 @@
# serializer version: 1
# name: test_cover_async_setup_entry[switch.myzone_myfan-turnoff]
dict({
'ac1': dict({
'info': dict({
'aaAutoFanModeEnabled': False,
}),
}),
})
# ---
# name: test_cover_async_setup_entry[switch.myzone_myfan-turnon]
dict({
'ac1': dict({
'info': dict({
'aaAutoFanModeEnabled': True,
}),
}),
})
# ---
# name: test_cover_async_setup_entry[switch.myzone_myfan]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'switch',
'friendly_name': 'myzone MyFan',
'icon': 'mdi:fan-auto',
}),
'context': <ANY>,
'entity_id': 'switch.myzone_myfan',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'off',
})
# ---

View File

@@ -0,0 +1,109 @@
"""Test the Advantage Air Binary Sensor Platform."""
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.util import dt as dt_util
from . import add_mock_config
from tests.common import async_fire_time_changed
async def test_binary_sensor_async_setup_entry(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_get: AsyncMock,
) -> None:
"""Test binary sensor setup."""
await add_mock_config(hass)
# Test First Air Filter
entity_id = "binary_sensor.myzone_filter"
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac1-filter"
# Test Second Air Filter
entity_id = "binary_sensor.mytemp_filter"
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_ON
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac2-filter"
# Test First Motion Sensor
entity_id = "binary_sensor.myzone_zone_open_with_sensor_motion"
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_ON
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac1-z01-motion"
# Test Second Motion Sensor
entity_id = "binary_sensor.myzone_zone_closed_with_sensor_motion"
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac1-z02-motion"
# Test First MyZone Sensor (disabled by default)
entity_id = "binary_sensor.myzone_zone_open_with_sensor_myzone"
assert not hass.states.get(entity_id)
mock_get.reset_mock()
with patch("homeassistant.config_entries.RELOAD_AFTER_UPDATE_DELAY", 1):
entity_registry.async_update_entity(entity_id=entity_id, disabled_by=None)
await hass.async_block_till_done()
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=2))
await hass.async_block_till_done(wait_background_tasks=True)
assert len(mock_get.mock_calls) == 1
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_ON
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac1-z01-myzone"
# Test Second Motion Sensor (disabled by default)
entity_id = "binary_sensor.myzone_zone_closed_with_sensor_myzone"
assert not hass.states.get(entity_id)
mock_get.reset_mock()
with patch("homeassistant.config_entries.RELOAD_AFTER_UPDATE_DELAY", 1):
entity_registry.async_update_entity(entity_id=entity_id, disabled_by=None)
await hass.async_block_till_done()
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=2))
await hass.async_block_till_done(wait_background_tasks=True)
assert len(mock_get.mock_calls) == 1
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac1-z02-myzone"

View File

@@ -0,0 +1,267 @@
"""Test the Advantage Air Climate Platform."""
from unittest.mock import AsyncMock
from advantage_air import ApiError
import pytest
from syrupy import SnapshotAssertion
from homeassistant.components.advantage_air.climate import ADVANTAGE_AIR_MYAUTO
from homeassistant.components.climate import (
ATTR_CURRENT_TEMPERATURE,
ATTR_FAN_MODE,
ATTR_HVAC_MODE,
ATTR_MAX_TEMP,
ATTR_MIN_TEMP,
ATTR_PRESET_MODE,
ATTR_TARGET_TEMP_HIGH,
ATTR_TARGET_TEMP_LOW,
DOMAIN as CLIMATE_DOMAIN,
FAN_AUTO,
FAN_LOW,
SERVICE_SET_FAN_MODE,
SERVICE_SET_HVAC_MODE,
SERVICE_SET_PRESET_MODE,
SERVICE_SET_TEMPERATURE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
HVACMode,
)
from homeassistant.const import ATTR_ENTITY_ID, ATTR_TEMPERATURE
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.helpers import entity_registry as er
from . import add_mock_config
async def test_climate_myzone_main(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_get: AsyncMock,
mock_update: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test climate platform main entity."""
await add_mock_config(hass)
# Test MyZone main climate entity
entity_id = "climate.myzone"
state = hass.states.get(entity_id)
assert state
assert state.state == HVACMode.FAN_ONLY
assert state.attributes.get(ATTR_MIN_TEMP) == 16
assert state.attributes.get(ATTR_MAX_TEMP) == 32
assert state.attributes.get(ATTR_TEMPERATURE) == 24
assert state.attributes.get(ATTR_CURRENT_TEMPERATURE) == 25
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac1"
# Test setting HVAC Mode
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: [entity_id], ATTR_HVAC_MODE: HVACMode.COOL},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: [entity_id], ATTR_HVAC_MODE: HVACMode.FAN_ONLY},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
# Test Turning Off with HVAC Mode
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: [entity_id], ATTR_HVAC_MODE: HVACMode.OFF},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_FAN_MODE,
{ATTR_ENTITY_ID: [entity_id], ATTR_FAN_MODE: FAN_LOW},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
# Test changing Temperature
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
{ATTR_ENTITY_ID: [entity_id], ATTR_TEMPERATURE: 25},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
# Test Turning On
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
# Test Turning Off
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
# Change Preset
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_PRESET_MODE,
{ATTR_ENTITY_ID: [entity_id], ATTR_PRESET_MODE: ADVANTAGE_AIR_MYAUTO},
blocking=True,
)
mock_update.assert_called_once()
assert mock_update.call_args[0][0] == snapshot(name=f"{entity_id}-preset")
mock_update.reset_mock()
# Test setting HEAT COOL when its not supported
with pytest.raises(ServiceValidationError):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: [entity_id], ATTR_HVAC_MODE: HVACMode.HEAT_COOL},
blocking=True,
)
async def test_climate_myzone_zone(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_get: AsyncMock,
mock_update: AsyncMock,
) -> None:
"""Test climate platform myzone zone entity."""
await add_mock_config(hass)
# Test Climate Zone Entity
entity_id = "climate.myzone_zone_open_with_sensor"
state = hass.states.get(entity_id)
assert state
assert state.attributes.get(ATTR_MIN_TEMP) == 16
assert state.attributes.get(ATTR_MAX_TEMP) == 32
assert state.attributes.get(ATTR_TEMPERATURE) == 24
assert state.attributes.get(ATTR_CURRENT_TEMPERATURE) == 25
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac1-z01"
# Test Climate Zone On
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: [entity_id], ATTR_HVAC_MODE: HVACMode.FAN_ONLY},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
# Test Climate Zone Off
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: [entity_id], ATTR_HVAC_MODE: HVACMode.OFF},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
{ATTR_ENTITY_ID: [entity_id], ATTR_TEMPERATURE: 25},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
async def test_climate_myauto_main(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_get: AsyncMock,
mock_update: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test climate platform zone entity."""
await add_mock_config(hass)
# Test MyAuto Climate Entity
entity_id = "climate.myauto"
assert hass.states.get(entity_id) == snapshot(name=entity_id)
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac3"
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
{
ATTR_ENTITY_ID: [entity_id],
ATTR_TARGET_TEMP_LOW: 21,
ATTR_TARGET_TEMP_HIGH: 23,
},
blocking=True,
)
mock_update.assert_called_once()
assert mock_update.call_args[0][0] == snapshot(name=f"{entity_id}-settemp")
mock_update.reset_mock()
# Test AutoFanMode
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_FAN_MODE,
{ATTR_ENTITY_ID: [entity_id], ATTR_FAN_MODE: FAN_AUTO},
blocking=True,
)
mock_update.assert_called_once()
assert mock_update.call_args[0][0] == snapshot(name=f"{entity_id}-fanmode")
async def test_climate_async_failed_update(
hass: HomeAssistant,
mock_get: AsyncMock,
mock_update: AsyncMock,
) -> None:
"""Test climate change failure."""
mock_update.side_effect = ApiError
await add_mock_config(hass)
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
{ATTR_ENTITY_ID: ["climate.myzone"], ATTR_TEMPERATURE: 25},
blocking=True,
)
mock_update.assert_called_once()

View File

@@ -0,0 +1,80 @@
"""Test the Advantage Air config flow."""
from unittest.mock import AsyncMock, patch
from advantage_air import ApiError
from homeassistant import config_entries
from homeassistant.components.advantage_air.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from . import TEST_SYSTEM_DATA, USER_INPUT
async def test_form(hass: HomeAssistant) -> None:
"""Test that form shows up."""
result1 = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result1["type"] is FlowResultType.FORM
assert result1["step_id"] == "user"
assert result1["errors"] == {}
with (
patch(
"homeassistant.components.advantage_air.config_flow.advantage_air.async_get",
new=AsyncMock(return_value=TEST_SYSTEM_DATA),
) as mock_get,
patch(
"homeassistant.components.advantage_air.async_setup_entry",
return_value=True,
) as mock_setup_entry,
):
result2 = await hass.config_entries.flow.async_configure(
result1["flow_id"],
USER_INPUT,
)
await hass.async_block_till_done()
mock_setup_entry.assert_called_once()
mock_get.assert_called_once()
assert result2["type"] is FlowResultType.CREATE_ENTRY
assert result2["title"] == "testname"
assert result2["data"] == USER_INPUT
# Test Duplicate Config Flow
result3 = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.advantage_air.config_flow.advantage_air.async_get",
new=AsyncMock(return_value=TEST_SYSTEM_DATA),
) as mock_get:
result4 = await hass.config_entries.flow.async_configure(
result3["flow_id"],
USER_INPUT,
)
assert result4["type"] is FlowResultType.ABORT
async def test_form_cannot_connect(hass: HomeAssistant) -> None:
"""Test we handle cannot connect error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.advantage_air.config_flow.advantage_air.async_get",
new=AsyncMock(side_effect=ApiError),
) as mock_get:
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
USER_INPUT,
)
mock_get.assert_called_once()
assert result2["type"] is FlowResultType.FORM
assert result2["step_id"] == "user"
assert result2["errors"] == {"base": "cannot_connect"}

View File

@@ -0,0 +1,146 @@
"""Test the Advantage Air Cover Platform."""
from unittest.mock import AsyncMock
from homeassistant.components.cover import (
ATTR_POSITION,
DOMAIN as COVER_DOMAIN,
SERVICE_CLOSE_COVER,
SERVICE_OPEN_COVER,
SERVICE_SET_COVER_POSITION,
CoverDeviceClass,
CoverState,
)
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import add_mock_config
async def test_ac_cover(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_get: AsyncMock,
mock_update: AsyncMock,
) -> None:
"""Test cover platform."""
await add_mock_config(hass)
# Test Cover Zone Entity
entity_id = "cover.myauto_zone_y"
state = hass.states.get(entity_id)
assert state
assert state.state == CoverState.OPEN
assert state.attributes.get("device_class") == CoverDeviceClass.DAMPER
assert state.attributes.get("current_position") == 100
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac3-z01"
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_CLOSE_COVER,
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_OPEN_COVER,
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_SET_COVER_POSITION,
{ATTR_ENTITY_ID: [entity_id], ATTR_POSITION: 50},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_SET_COVER_POSITION,
{ATTR_ENTITY_ID: [entity_id], ATTR_POSITION: 0},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
# Test controlling multiple Cover Zone Entity
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_CLOSE_COVER,
{
ATTR_ENTITY_ID: [
"cover.myauto_zone_y",
"cover.myauto_zone_z",
]
},
blocking=True,
)
assert len(mock_update.mock_calls) == 2
mock_update.reset_mock()
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_OPEN_COVER,
{
ATTR_ENTITY_ID: [
"cover.myauto_zone_y",
"cover.myauto_zone_z",
]
},
blocking=True,
)
assert len(mock_update.mock_calls) == 2
async def test_things_cover(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_get: AsyncMock,
mock_update: AsyncMock,
) -> None:
"""Test cover platform."""
await add_mock_config(hass)
# Test Blind 1 Entity
entity_id = "cover.blind_1"
thing_id = "200"
state = hass.states.get(entity_id)
assert state
assert state.state == CoverState.OPEN
assert state.attributes.get("device_class") == CoverDeviceClass.BLIND
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == f"uniqueid-{thing_id}"
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_CLOSE_COVER,
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_OPEN_COVER,
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_update.assert_called_once()

View File

@@ -0,0 +1,25 @@
"""Test the Advantage Air Diagnostics."""
from unittest.mock import AsyncMock
from syrupy.assertion import SnapshotAssertion
from homeassistant.core import HomeAssistant
from . import add_mock_config
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_select_async_setup_entry(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
snapshot: SnapshotAssertion,
mock_get: AsyncMock,
) -> None:
"""Test select platform."""
entry = await add_mock_config(hass)
diag = await get_diagnostics_for_config_entry(hass, hass_client, entry)
assert diag == snapshot

View File

@@ -0,0 +1,29 @@
"""Test the Advantage Air Initialization."""
from unittest.mock import AsyncMock
from advantage_air import ApiError
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from . import add_mock_config, patch_get
async def test_async_setup_entry(hass: HomeAssistant, mock_get: AsyncMock) -> None:
"""Test a successful setup entry and unload."""
entry = await add_mock_config(hass)
assert entry.state is ConfigEntryState.LOADED
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.NOT_LOADED
async def test_async_setup_entry_failure(hass: HomeAssistant) -> None:
"""Test a unsuccessful setup entry."""
with patch_get(side_effect=ApiError):
entry = await add_mock_config(hass)
assert entry.state is ConfigEntryState.SETUP_RETRY

View File

@@ -0,0 +1,120 @@
"""Test the Advantage Air Switch Platform."""
from unittest.mock import AsyncMock
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
DOMAIN as LIGHT_DOMAIN,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import add_mock_config
async def test_light(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_get: AsyncMock,
mock_update: AsyncMock,
) -> None:
"""Test light setup."""
await add_mock_config(hass)
# Test Light Entity
entity_id = "light.light_a"
light_id = "100"
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == f"uniqueid-{light_id}"
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
# Test Dimmable Light Entity
entity_id = "light.light_b"
light_id = "101"
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == f"uniqueid-{light_id}"
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: [entity_id], ATTR_BRIGHTNESS: 128},
blocking=True,
)
mock_update.assert_called_once()
async def test_things_light(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_get: AsyncMock,
mock_update: AsyncMock,
) -> None:
"""Test things lights."""
await add_mock_config(hass)
# Test Switch Entity
entity_id = "light.thing_light_dimmable"
light_id = "204"
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_ON
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == f"uniqueid-{light_id}"
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: [entity_id], ATTR_BRIGHTNESS: 128},
blocking=True,
)
mock_update.assert_called_once()

View File

@@ -0,0 +1,43 @@
"""Test the Advantage Air Select Platform."""
from unittest.mock import AsyncMock
from homeassistant.components.select import (
ATTR_OPTION,
DOMAIN as SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
)
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import add_mock_config
async def test_select_async_setup_entry(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_get: AsyncMock,
mock_update: AsyncMock,
) -> None:
"""Test select platform."""
await add_mock_config(hass)
# Test MyZone Select Entity
entity_id = "select.myzone_myzone"
state = hass.states.get(entity_id)
assert state
assert state.state == "Zone open with Sensor"
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac1-myzone"
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{ATTR_ENTITY_ID: entity_id, ATTR_OPTION: "Zone 3"},
blocking=True,
)
mock_update.assert_called_once()

View File

@@ -0,0 +1,141 @@
"""Test the Advantage Air Sensor Platform."""
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from homeassistant.components.advantage_air.const import DOMAIN as ADVANTAGE_AIR_DOMAIN
from homeassistant.components.advantage_air.sensor import (
ADVANTAGE_AIR_SERVICE_SET_TIME_TO,
ADVANTAGE_AIR_SET_COUNTDOWN_VALUE,
)
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.util import dt as dt_util
from . import add_mock_config
from tests.common import async_fire_time_changed
async def test_sensor_platform(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_get: AsyncMock,
mock_update: AsyncMock,
) -> None:
"""Test sensor platform."""
await add_mock_config(hass)
# Test First TimeToOn Sensor
entity_id = "sensor.myzone_time_to_on"
state = hass.states.get(entity_id)
assert state
assert int(state.state) == 0
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac1-timetoOn"
value = 20
await hass.services.async_call(
ADVANTAGE_AIR_DOMAIN,
ADVANTAGE_AIR_SERVICE_SET_TIME_TO,
{ATTR_ENTITY_ID: [entity_id], ADVANTAGE_AIR_SET_COUNTDOWN_VALUE: value},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
# Test First TimeToOff Sensor
entity_id = "sensor.myzone_time_to_off"
state = hass.states.get(entity_id)
assert state
assert int(state.state) == 10
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac1-timetoOff"
value = 0
await hass.services.async_call(
ADVANTAGE_AIR_DOMAIN,
ADVANTAGE_AIR_SERVICE_SET_TIME_TO,
{ATTR_ENTITY_ID: [entity_id], ADVANTAGE_AIR_SET_COUNTDOWN_VALUE: value},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
# Test First Zone Vent Sensor
entity_id = "sensor.myzone_zone_open_with_sensor_vent"
state = hass.states.get(entity_id)
assert state
assert int(state.state) == 100
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac1-z01-vent"
# Test Second Zone Vent Sensor
entity_id = "sensor.myzone_zone_closed_with_sensor_vent"
state = hass.states.get(entity_id)
assert state
assert int(state.state) == 0
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac1-z02-vent"
# Test First Zone Signal Sensor
entity_id = "sensor.myzone_zone_open_with_sensor_signal"
state = hass.states.get(entity_id)
assert state
assert int(state.state) == 40
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac1-z01-signal"
# Test Second Zone Signal Sensor
entity_id = "sensor.myzone_zone_closed_with_sensor_signal"
state = hass.states.get(entity_id)
assert state
assert int(state.state) == 10
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac1-z02-signal"
async def test_sensor_platform_disabled_entity(
hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_get: AsyncMock
) -> None:
"""Test sensor platform disabled entity."""
await add_mock_config(hass)
# Test First Zone Temp Sensor (disabled by default)
entity_id = "sensor.myzone_zone_open_with_sensor_temperature"
assert not hass.states.get(entity_id)
mock_get.reset_mock()
with patch("homeassistant.config_entries.RELOAD_AFTER_UPDATE_DELAY", 1):
entity_registry.async_update_entity(entity_id=entity_id, disabled_by=None)
await hass.async_block_till_done(wait_background_tasks=True)
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=2))
await hass.async_block_till_done(wait_background_tasks=True)
assert len(mock_get.mock_calls) == 1
state = hass.states.get(entity_id)
assert state
assert int(state.state) == 25
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac1-z01-temp"

View File

@@ -0,0 +1,122 @@
"""Test the Advantage Air Switch Platform."""
from unittest.mock import AsyncMock
from syrupy import SnapshotAssertion
from homeassistant.components.switch import (
DOMAIN as SWITCH_DOMAIN,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import add_mock_config
async def test_cover_async_setup_entry(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_get: AsyncMock,
mock_update: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test switch platform."""
await add_mock_config(hass)
# Test Fresh Air Switch Entity
entity_id = "switch.myzone_fresh_air"
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac1-freshair"
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
# Test MyFan Switch Entity
entity_id = "switch.myzone_myfan"
assert hass.states.get(entity_id) == snapshot(name=entity_id)
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid-ac1-myfan"
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_update.assert_called_once()
assert mock_update.call_args[0][0] == snapshot(name=f"{entity_id}-turnon")
mock_update.reset_mock()
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_update.assert_called_once()
assert mock_update.call_args[0][0] == snapshot(name=f"{entity_id}-turnoff")
async def test_things_switch(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_get: AsyncMock,
mock_update: AsyncMock,
) -> None:
"""Test things switches."""
await add_mock_config(hass)
# Test Switch Entity
entity_id = "switch.relay"
thing_id = "205"
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_ON
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == f"uniqueid-{thing_id}"
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_update.assert_called_once()
mock_update.reset_mock()
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_update.assert_called_once()

View File

@@ -0,0 +1,33 @@
"""Test the Advantage Air Update Platform."""
from unittest.mock import AsyncMock
from homeassistant.components.advantage_air.const import DOMAIN
from homeassistant.const import STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import add_mock_config
from tests.common import load_json_object_fixture
TEST_NEEDS_UPDATE = load_json_object_fixture("needsUpdate.json", DOMAIN)
async def test_update_platform(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_get: AsyncMock,
) -> None:
"""Test update platform."""
mock_get.return_value = TEST_NEEDS_UPDATE
await add_mock_config(hass)
entity_id = "update.testname_app"
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_ON
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == "uniqueid"

View File

@@ -0,0 +1 @@
"""Tests for the AEMET OpenData integration."""

View File

@@ -0,0 +1,15 @@
"""Test fixtures for aemet."""
from collections.abc import Generator
from unittest.mock import AsyncMock, patch
import pytest
@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock]:
"""Override async_setup_entry."""
with patch(
"homeassistant.components.aemet.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry

Some files were not shown because too many files have changed in this diff Show More