mirror of
https://github.com/home-assistant/core.git
synced 2025-06-25 01:21:51 +02:00
Add Snoo integration (#134243)
Co-authored-by: Joost Lekkerkerker <joostlek@outlook.com>
This commit is contained in:
2
CODEOWNERS
generated
2
CODEOWNERS
generated
@ -1413,6 +1413,8 @@ build.json @home-assistant/supervisor
|
||||
/tests/components/snapcast/ @luar123
|
||||
/homeassistant/components/snmp/ @nmaggioni
|
||||
/tests/components/snmp/ @nmaggioni
|
||||
/homeassistant/components/snoo/ @Lash-L
|
||||
/tests/components/snoo/ @Lash-L
|
||||
/homeassistant/components/snooz/ @AustinBrunkhorst
|
||||
/tests/components/snooz/ @AustinBrunkhorst
|
||||
/homeassistant/components/solaredge/ @frenck @bdraco
|
||||
|
63
homeassistant/components/snoo/__init__.py
Normal file
63
homeassistant/components/snoo/__init__.py
Normal file
@ -0,0 +1,63 @@
|
||||
"""The Happiest Baby Snoo integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from python_snoo.exceptions import InvalidSnooAuth, SnooAuthException, SnooDeviceError
|
||||
from python_snoo.snoo import Snoo
|
||||
|
||||
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ConfigEntryNotReady
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
|
||||
from .coordinator import SnooConfigEntry, SnooCoordinator
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
PLATFORMS: list[Platform] = [Platform.SENSOR]
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: SnooConfigEntry) -> bool:
|
||||
"""Set up Happiest Baby Snoo from a config entry."""
|
||||
|
||||
snoo = Snoo(
|
||||
email=entry.data[CONF_USERNAME],
|
||||
password=entry.data[CONF_PASSWORD],
|
||||
clientsession=async_get_clientsession(hass),
|
||||
)
|
||||
|
||||
try:
|
||||
await snoo.authorize()
|
||||
except (SnooAuthException, InvalidSnooAuth) as ex:
|
||||
raise ConfigEntryNotReady from ex
|
||||
try:
|
||||
devices = await snoo.get_devices()
|
||||
except SnooDeviceError as ex:
|
||||
raise ConfigEntryNotReady from ex
|
||||
coordinators: dict[str, SnooCoordinator] = {}
|
||||
tasks = []
|
||||
for device in devices:
|
||||
coordinators[device.serialNumber] = SnooCoordinator(hass, device, snoo)
|
||||
tasks.append(coordinators[device.serialNumber].setup())
|
||||
await asyncio.gather(*tasks)
|
||||
entry.runtime_data = coordinators
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: SnooConfigEntry) -> bool:
|
||||
"""Unload a config entry."""
|
||||
disconnects = await asyncio.gather(
|
||||
*(coordinator.snoo.disconnect() for coordinator in entry.runtime_data.values()),
|
||||
return_exceptions=True,
|
||||
)
|
||||
for disconnect in disconnects:
|
||||
if isinstance(disconnect, Exception):
|
||||
_LOGGER.warning(
|
||||
"Failed to disconnect a logger with exception: %s", disconnect
|
||||
)
|
||||
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
68
homeassistant/components/snoo/config_flow.py
Normal file
68
homeassistant/components/snoo/config_flow.py
Normal file
@ -0,0 +1,68 @@
|
||||
"""Config flow for the Happiest Baby Snoo integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import jwt
|
||||
from python_snoo.exceptions import InvalidSnooAuth, SnooAuthException
|
||||
from python_snoo.snoo import Snoo
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
|
||||
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
|
||||
from .const import DOMAIN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
STEP_USER_DATA_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Required(CONF_USERNAME): str,
|
||||
vol.Required(CONF_PASSWORD): str,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class SnooConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
"""Handle a config flow for Happiest Baby Snoo."""
|
||||
|
||||
VERSION = 1
|
||||
|
||||
async def async_step_user(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle the initial step."""
|
||||
errors: dict[str, str] = {}
|
||||
if user_input is not None:
|
||||
hub = Snoo(
|
||||
email=user_input[CONF_USERNAME],
|
||||
password=user_input[CONF_PASSWORD],
|
||||
clientsession=async_get_clientsession(self.hass),
|
||||
)
|
||||
|
||||
try:
|
||||
tokens = await hub.authorize()
|
||||
except SnooAuthException:
|
||||
errors["base"] = "cannot_connect"
|
||||
except InvalidSnooAuth:
|
||||
errors["base"] = "invalid_auth"
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception %s")
|
||||
errors["base"] = "unknown"
|
||||
else:
|
||||
user_uuid = jwt.decode(
|
||||
tokens.aws_access, options={"verify_signature": False}
|
||||
)["username"]
|
||||
await self.async_set_unique_id(user_uuid)
|
||||
self._abort_if_unique_id_configured()
|
||||
|
||||
return self.async_create_entry(
|
||||
title=user_input[CONF_USERNAME], data=user_input
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
|
||||
)
|
3
homeassistant/components/snoo/const.py
Normal file
3
homeassistant/components/snoo/const.py
Normal file
@ -0,0 +1,3 @@
|
||||
"""Constants for the Happiest Baby Snoo integration."""
|
||||
|
||||
DOMAIN = "snoo"
|
39
homeassistant/components/snoo/coordinator.py
Normal file
39
homeassistant/components/snoo/coordinator.py
Normal file
@ -0,0 +1,39 @@
|
||||
"""Support for Snoo Coordinators."""
|
||||
|
||||
import logging
|
||||
|
||||
from python_snoo.containers import SnooData, SnooDevice
|
||||
from python_snoo.snoo import Snoo
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
|
||||
|
||||
type SnooConfigEntry = ConfigEntry[dict[str, SnooCoordinator]]
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SnooCoordinator(DataUpdateCoordinator[SnooData]):
|
||||
"""Snoo coordinator."""
|
||||
|
||||
config_entry: SnooConfigEntry
|
||||
|
||||
def __init__(self, hass: HomeAssistant, device: SnooDevice, snoo: Snoo) -> None:
|
||||
"""Set up Snoo Coordinator."""
|
||||
super().__init__(
|
||||
hass,
|
||||
name=device.name,
|
||||
logger=_LOGGER,
|
||||
)
|
||||
self.device_unique_id = device.serialNumber
|
||||
self.device = device
|
||||
self.sensor_data_set: bool = False
|
||||
self.snoo = snoo
|
||||
|
||||
async def setup(self) -> None:
|
||||
"""Perform setup needed on every coordintaor creation."""
|
||||
await self.snoo.subscribe(self.device, self.async_set_updated_data)
|
||||
# After we subscribe - get the status so that we have something to start with.
|
||||
# We only need to do this once. The device will auto update otherwise.
|
||||
await self.snoo.get_status(self.device)
|
37
homeassistant/components/snoo/entity.py
Normal file
37
homeassistant/components/snoo/entity.py
Normal file
@ -0,0 +1,37 @@
|
||||
"""Base entity for the Snoo integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.helpers.device_registry import DeviceInfo
|
||||
from homeassistant.helpers.entity import EntityDescription
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
|
||||
from .const import DOMAIN
|
||||
from .coordinator import SnooCoordinator
|
||||
|
||||
|
||||
class SnooDescriptionEntity(CoordinatorEntity[SnooCoordinator]):
|
||||
"""Defines an Snoo entity that uses a description."""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
|
||||
def __init__(
|
||||
self, coordinator: SnooCoordinator, description: EntityDescription
|
||||
) -> None:
|
||||
"""Initialize the Snoo entity."""
|
||||
super().__init__(coordinator)
|
||||
self.device = coordinator.device
|
||||
self.entity_description = description
|
||||
self._attr_unique_id = f"{coordinator.device_unique_id}_{description.key}"
|
||||
self._attr_device_info = DeviceInfo(
|
||||
identifiers={(DOMAIN, coordinator.device_unique_id)},
|
||||
name=self.device.name,
|
||||
manufacturer="Happiest Baby",
|
||||
model="Snoo",
|
||||
serial_number=self.device.serialNumber,
|
||||
)
|
||||
|
||||
@property
|
||||
def available(self) -> bool:
|
||||
"""Return if entity is available."""
|
||||
return self.coordinator.data is not None and super().available
|
11
homeassistant/components/snoo/manifest.json
Normal file
11
homeassistant/components/snoo/manifest.json
Normal file
@ -0,0 +1,11 @@
|
||||
{
|
||||
"domain": "snoo",
|
||||
"name": "Happiest Baby Snoo",
|
||||
"codeowners": ["@Lash-L"],
|
||||
"config_flow": true,
|
||||
"documentation": "https://www.home-assistant.io/integrations/snoo",
|
||||
"iot_class": "cloud_push",
|
||||
"loggers": ["snoo"],
|
||||
"quality_scale": "bronze",
|
||||
"requirements": ["python-snoo==0.6.0"]
|
||||
}
|
72
homeassistant/components/snoo/quality_scale.yaml
Normal file
72
homeassistant/components/snoo/quality_scale.yaml
Normal file
@ -0,0 +1,72 @@
|
||||
rules:
|
||||
# Bronze
|
||||
action-setup:
|
||||
status: exempt
|
||||
comment: |
|
||||
This integration does not provide additional actions.
|
||||
appropriate-polling:
|
||||
status: exempt
|
||||
comment: |
|
||||
This integration does not poll.
|
||||
brands: done
|
||||
common-modules:
|
||||
status: done
|
||||
comment: |
|
||||
There are no common patterns currenty.
|
||||
config-flow-test-coverage: done
|
||||
config-flow: done
|
||||
dependency-transparency: done
|
||||
docs-actions:
|
||||
status: exempt
|
||||
comment: |
|
||||
This integration does not provide additional actions.
|
||||
docs-high-level-description: done
|
||||
docs-installation-instructions: done
|
||||
docs-removal-instructions: done
|
||||
entity-event-setup: done
|
||||
entity-unique-id: done
|
||||
has-entity-name: done
|
||||
runtime-data: done
|
||||
test-before-configure: done
|
||||
test-before-setup: done
|
||||
unique-config-entry: done
|
||||
|
||||
# Silver
|
||||
action-exceptions: todo
|
||||
config-entry-unloading: done
|
||||
docs-configuration-parameters: todo
|
||||
docs-installation-parameters: todo
|
||||
entity-unavailable: todo
|
||||
integration-owner: done
|
||||
log-when-unavailable: todo
|
||||
parallel-updates: todo
|
||||
reauthentication-flow: todo
|
||||
test-coverage: todo
|
||||
|
||||
# Gold
|
||||
devices: done
|
||||
diagnostics: todo
|
||||
discovery-update-info: todo
|
||||
discovery: todo
|
||||
docs-data-update: todo
|
||||
docs-examples: todo
|
||||
docs-known-limitations: todo
|
||||
docs-supported-devices: todo
|
||||
docs-supported-functions: todo
|
||||
docs-troubleshooting: todo
|
||||
docs-use-cases: todo
|
||||
dynamic-devices: todo
|
||||
entity-category: done
|
||||
entity-device-class: done
|
||||
entity-disabled-by-default: todo
|
||||
entity-translations: done
|
||||
exception-translations: todo
|
||||
icon-translations: todo
|
||||
reconfiguration-flow: todo
|
||||
repair-issues: todo
|
||||
stale-devices: todo
|
||||
|
||||
# Platinum
|
||||
async-dependency: done
|
||||
inject-websession: done
|
||||
strict-typing: todo
|
71
homeassistant/components/snoo/sensor.py
Normal file
71
homeassistant/components/snoo/sensor.py
Normal file
@ -0,0 +1,71 @@
|
||||
"""Support for Snoo Sensors."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
|
||||
from python_snoo.containers import SnooData, SnooStates
|
||||
|
||||
from homeassistant.components.sensor import (
|
||||
EntityCategory,
|
||||
SensorDeviceClass,
|
||||
SensorEntity,
|
||||
SensorEntityDescription,
|
||||
StateType,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
|
||||
from .coordinator import SnooConfigEntry
|
||||
from .entity import SnooDescriptionEntity
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class SnooSensorEntityDescription(SensorEntityDescription):
|
||||
"""Describes a Snoo sensor."""
|
||||
|
||||
value_fn: Callable[[SnooData], StateType]
|
||||
|
||||
|
||||
SENSOR_DESCRIPTIONS: list[SnooSensorEntityDescription] = [
|
||||
SnooSensorEntityDescription(
|
||||
key="state",
|
||||
translation_key="state",
|
||||
value_fn=lambda data: data.state_machine.state.name,
|
||||
device_class=SensorDeviceClass.ENUM,
|
||||
options=[e.name for e in SnooStates],
|
||||
),
|
||||
SnooSensorEntityDescription(
|
||||
key="time_left",
|
||||
translation_key="time_left",
|
||||
value_fn=lambda data: data.state_machine.time_left_timestamp,
|
||||
device_class=SensorDeviceClass.TIMESTAMP,
|
||||
entity_category=EntityCategory.DIAGNOSTIC,
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: SnooConfigEntry,
|
||||
async_add_entities: AddConfigEntryEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up Snoo device."""
|
||||
coordinators = entry.runtime_data
|
||||
async_add_entities(
|
||||
SnooSensor(coordinator, description)
|
||||
for coordinator in coordinators.values()
|
||||
for description in SENSOR_DESCRIPTIONS
|
||||
)
|
||||
|
||||
|
||||
class SnooSensor(SnooDescriptionEntity, SensorEntity):
|
||||
"""A sensor using Snoo coordinator."""
|
||||
|
||||
entity_description: SnooSensorEntityDescription
|
||||
|
||||
@property
|
||||
def native_value(self) -> StateType:
|
||||
"""Return the value reported by the sensor."""
|
||||
return self.entity_description.value_fn(self.coordinator.data)
|
44
homeassistant/components/snoo/strings.json
Normal file
44
homeassistant/components/snoo/strings.json
Normal file
@ -0,0 +1,44 @@
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"user": {
|
||||
"data": {
|
||||
"username": "[%key:common::config_flow::data::username%]",
|
||||
"password": "[%key:common::config_flow::data::password%]"
|
||||
},
|
||||
"data_description": {
|
||||
"username": "Your Snoo username or email",
|
||||
"password": "Your Snoo password"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
|
||||
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]",
|
||||
"unknown": "[%key:common::config_flow::error::unknown%]"
|
||||
},
|
||||
"abort": {
|
||||
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]"
|
||||
}
|
||||
},
|
||||
"entity": {
|
||||
"sensor": {
|
||||
"state": {
|
||||
"name": "State",
|
||||
"state": {
|
||||
"baseline": "Baseline",
|
||||
"level1": "Level 1",
|
||||
"level2": "Level 2",
|
||||
"level3": "Level 3",
|
||||
"level4": "Level 4",
|
||||
"stop": "Stopped",
|
||||
"pretimeout": "Pre-timeout",
|
||||
"timeout": "Timeout"
|
||||
}
|
||||
},
|
||||
"time_left": {
|
||||
"name": "Time left"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
1
homeassistant/generated/config_flows.py
generated
1
homeassistant/generated/config_flows.py
generated
@ -575,6 +575,7 @@ FLOWS = {
|
||||
"smlight",
|
||||
"sms",
|
||||
"snapcast",
|
||||
"snoo",
|
||||
"snooz",
|
||||
"solaredge",
|
||||
"solarlog",
|
||||
|
@ -5916,6 +5916,12 @@
|
||||
"config_flow": false,
|
||||
"iot_class": "local_polling"
|
||||
},
|
||||
"snoo": {
|
||||
"name": "Happiest Baby Snoo",
|
||||
"integration_type": "hub",
|
||||
"config_flow": true,
|
||||
"iot_class": "cloud_push"
|
||||
},
|
||||
"snooz": {
|
||||
"name": "Snooz",
|
||||
"integration_type": "hub",
|
||||
|
3
requirements_all.txt
generated
3
requirements_all.txt
generated
@ -2463,6 +2463,9 @@ python-roborock==2.11.1
|
||||
# homeassistant.components.smarttub
|
||||
python-smarttub==0.0.38
|
||||
|
||||
# homeassistant.components.snoo
|
||||
python-snoo==0.6.0
|
||||
|
||||
# homeassistant.components.songpal
|
||||
python-songpal==0.16.2
|
||||
|
||||
|
3
requirements_test_all.txt
generated
3
requirements_test_all.txt
generated
@ -1996,6 +1996,9 @@ python-roborock==2.11.1
|
||||
# homeassistant.components.smarttub
|
||||
python-smarttub==0.0.38
|
||||
|
||||
# homeassistant.components.snoo
|
||||
python-snoo==0.6.0
|
||||
|
||||
# homeassistant.components.songpal
|
||||
python-songpal==0.16.2
|
||||
|
||||
|
38
tests/components/snoo/__init__.py
Normal file
38
tests/components/snoo/__init__.py
Normal file
@ -0,0 +1,38 @@
|
||||
"""Tests for the Happiest Baby Snoo integration."""
|
||||
|
||||
from homeassistant.components.snoo.const import DOMAIN
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
def create_entry(
|
||||
hass: HomeAssistant,
|
||||
) -> ConfigEntry:
|
||||
"""Add config entry in Home Assistant."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
title="test-username",
|
||||
data={
|
||||
CONF_USERNAME: "test-username",
|
||||
CONF_PASSWORD: "sample",
|
||||
},
|
||||
# This is also gotten from the fake jwt
|
||||
unique_id="123e4567-e89b-12d3-a456-426614174000",
|
||||
version=1,
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
return entry
|
||||
|
||||
|
||||
async def async_init_integration(hass: HomeAssistant) -> ConfigEntry:
|
||||
"""Set up the Snoo integration in Home Assistant."""
|
||||
|
||||
entry = create_entry(hass)
|
||||
|
||||
await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
return entry
|
73
tests/components/snoo/conftest.py
Normal file
73
tests/components/snoo/conftest.py
Normal file
@ -0,0 +1,73 @@
|
||||
"""Common fixtures for the Happiest Baby Snoo tests."""
|
||||
|
||||
from collections.abc import Generator
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
from python_snoo.containers import SnooDevice
|
||||
from python_snoo.snoo import Snoo
|
||||
|
||||
from .const import MOCK_AMAZON_AUTH, MOCK_SNOO_AUTH, MOCK_SNOO_DEVICES
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_setup_entry() -> Generator[AsyncMock]:
|
||||
"""Override async_setup_entry."""
|
||||
with patch(
|
||||
"homeassistant.components.snoo.async_setup_entry", return_value=True
|
||||
) as mock_setup_entry:
|
||||
yield mock_setup_entry
|
||||
|
||||
|
||||
class MockedSnoo(Snoo):
|
||||
"""Mock the Snoo object."""
|
||||
|
||||
def __init__(self, email, password, clientsession) -> None:
|
||||
"""Set up a Mocked Snoo."""
|
||||
super().__init__(email, password, clientsession)
|
||||
self.auth_error = None
|
||||
|
||||
async def subscribe(self, device: SnooDevice, function):
|
||||
"""Mock the subscribe function."""
|
||||
return AsyncMock()
|
||||
|
||||
async def send_command(self, command: str, device: SnooDevice, **kwargs):
|
||||
"""Mock the send command function."""
|
||||
return AsyncMock()
|
||||
|
||||
async def authorize(self):
|
||||
"""Do normal auth flow unless error is patched."""
|
||||
if self.auth_error:
|
||||
raise self.auth_error
|
||||
return await super().authorize()
|
||||
|
||||
def set_auth_error(self, error: Exception | None):
|
||||
"""Set an error for authentication."""
|
||||
self.auth_error = error
|
||||
|
||||
async def auth_amazon(self):
|
||||
"""Mock the amazon auth."""
|
||||
return MOCK_AMAZON_AUTH
|
||||
|
||||
async def auth_snoo(self, id_token):
|
||||
"""Mock the snoo auth."""
|
||||
return MOCK_SNOO_AUTH
|
||||
|
||||
async def schedule_reauthorization(self, snoo_expiry: int):
|
||||
"""Mock scheduling reauth."""
|
||||
return AsyncMock()
|
||||
|
||||
async def get_devices(self) -> list[SnooDevice]:
|
||||
"""Move getting devices."""
|
||||
return [SnooDevice.from_dict(dev) for dev in MOCK_SNOO_DEVICES]
|
||||
|
||||
|
||||
@pytest.fixture(name="bypass_api")
|
||||
def bypass_api() -> MockedSnoo:
|
||||
"""Bypass the Snoo api."""
|
||||
api = MockedSnoo("email", "password", AsyncMock())
|
||||
with (
|
||||
patch("homeassistant.components.snoo.Snoo", return_value=api),
|
||||
patch("homeassistant.components.snoo.config_flow.Snoo", return_value=api),
|
||||
):
|
||||
yield api
|
34
tests/components/snoo/const.py
Normal file
34
tests/components/snoo/const.py
Normal file
@ -0,0 +1,34 @@
|
||||
"""Snoo constants for testing."""
|
||||
|
||||
MOCK_AMAZON_AUTH = {
|
||||
# This is a JWT with random values.
|
||||
"AccessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhMWIyYzNkNC1lNWY2"
|
||||
"LTQ3ODktOTBhYi1jZGVmMDEyMzQ1NjciLCJpc3MiOiJodHRwczovL2NvZ25pdG8taWRwLnVzLXdlc3Qt"
|
||||
"Mi5hbWF6b25hd3MuY29tL3VzLXdlc3QtMl9FeGFtcGxlVXNlclBvb2xJZCIsImNsaWVudF9pZCI6ImFiY"
|
||||
"2RlZmdoMTIzNDU2Nzg5MGFiY2RlZmdoMTIiLCJvcmlnaW5fanRpIjoiYjhkOWUwZjEtMmczaC00aTVqLT"
|
||||
"ZrN2wtOG05bjBvMXAycTNyIiwiZXZlbnRfaWQiOiJmMGcxaDJpMy00ajVrLTZsN20tOG45by0wcDFxMnI"
|
||||
"zczR0NXUiLCJ0b2tlbl91c2UiOiJhY2Nlc3MiLCJzY29wZSI6ImF3cy5jb2duaXRvLnNpZ25pbi51c2Vy"
|
||||
"LmFkbWluIiwiYXV0aF90aW1lIjoxNzAwMDAwMDAwLCJleHAiOjE3MDAwMDM2MDAsImlhdCI6MTcwMDAwM"
|
||||
"DAwMCwianRpIjoidjZ3N3g4eTktMHoxYS0yYjNjLTRkNWUtNmY3ZzhoOWkwajFrIiwidXNlcm5hbWUiOi"
|
||||
"IxMjNlNDU2Ny1lODliLTEyZDMtYTQ1Ni00MjY2MTQxNzQwMDAifQ.zH5vy5itWot_5-rdJgYoygeKx696"
|
||||
"Uge46zxXMhdn5RE",
|
||||
"IdToken": "random_id",
|
||||
"RefreshToken": "refresh_token",
|
||||
}
|
||||
|
||||
MOCK_SNOO_AUTH = {"expiresIn": 10800, "snoo": {"token": "random_snoo_token"}}
|
||||
|
||||
MOCK_SNOO_DEVICES = [
|
||||
{
|
||||
"serialNumber": "random_num",
|
||||
"deviceType": 1,
|
||||
"firmwareVersion": 1.0,
|
||||
"babyIds": ["35235-211235-dfasdf-32523"],
|
||||
"name": "Test Snoo",
|
||||
"presence": {},
|
||||
"presenceIoT": {},
|
||||
"awsIoT": {},
|
||||
"lastSSID": {},
|
||||
"provisionedAt": "random_time",
|
||||
}
|
||||
]
|
118
tests/components/snoo/test_config_flow.py
Normal file
118
tests/components/snoo/test_config_flow.py
Normal file
@ -0,0 +1,118 @@
|
||||
"""Test the Happiest Baby Snoo config flow."""
|
||||
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
from python_snoo.exceptions import InvalidSnooAuth, SnooAuthException
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.components.snoo.const import 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 . import create_entry
|
||||
from .conftest import MockedSnoo
|
||||
|
||||
|
||||
async def test_config_flow_success(
|
||||
hass: HomeAssistant, mock_setup_entry: AsyncMock, bypass_api: MockedSnoo
|
||||
) -> None:
|
||||
"""Test we create the entry successfully."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {}
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{
|
||||
CONF_USERNAME: "test-username",
|
||||
CONF_PASSWORD: "test-password",
|
||||
},
|
||||
)
|
||||
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == "test-username"
|
||||
assert result["data"] == {
|
||||
CONF_USERNAME: "test-username",
|
||||
CONF_PASSWORD: "test-password",
|
||||
}
|
||||
assert result["result"].unique_id == "123e4567-e89b-12d3-a456-426614174000"
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("exception", "error_msg"),
|
||||
[
|
||||
(InvalidSnooAuth, "invalid_auth"),
|
||||
(SnooAuthException, "cannot_connect"),
|
||||
(Exception, "unknown"),
|
||||
],
|
||||
)
|
||||
async def test_form_auth_issues(
|
||||
hass: HomeAssistant,
|
||||
mock_setup_entry: AsyncMock,
|
||||
bypass_api: MockedSnoo,
|
||||
exception,
|
||||
error_msg,
|
||||
) -> None:
|
||||
"""Test we handle invalid auth."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
# Set Authorize to fail.
|
||||
bypass_api.set_auth_error(exception)
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{
|
||||
CONF_USERNAME: "test-username",
|
||||
CONF_PASSWORD: "test-password",
|
||||
},
|
||||
)
|
||||
# Reset auth back to the original
|
||||
bypass_api.set_auth_error(None)
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["errors"] == {"base": error_msg}
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{
|
||||
CONF_USERNAME: "test-username",
|
||||
CONF_PASSWORD: "test-password",
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == "test-username"
|
||||
assert result["data"] == {
|
||||
CONF_USERNAME: "test-username",
|
||||
CONF_PASSWORD: "test-password",
|
||||
}
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
|
||||
|
||||
async def test_account_already_configured(
|
||||
hass: HomeAssistant, mock_setup_entry: AsyncMock, bypass_api
|
||||
) -> None:
|
||||
"""Ensure we abort if the config flow already exists."""
|
||||
create_entry(hass)
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {}
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{
|
||||
CONF_USERNAME: "test-username",
|
||||
CONF_PASSWORD: "test-password",
|
||||
},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "already_configured"
|
14
tests/components/snoo/test_init.py
Normal file
14
tests/components/snoo/test_init.py
Normal file
@ -0,0 +1,14 @@
|
||||
"""Test init for Snoo."""
|
||||
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from . import async_init_integration
|
||||
from .conftest import MockedSnoo
|
||||
|
||||
|
||||
async def test_async_setup_entry(hass: HomeAssistant, bypass_api: MockedSnoo) -> None:
|
||||
"""Test a successful setup entry."""
|
||||
entry = await async_init_integration(hass)
|
||||
assert len(hass.states.async_all("sensor")) == 2
|
||||
assert entry.state == ConfigEntryState.LOADED
|
Reference in New Issue
Block a user