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 @@
"""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

View File

@@ -0,0 +1,462 @@
[
{
"dv": 100.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-08T14:00:00",
"prec": 1.2,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 929.9,
"hr": 97.0,
"pres_nmar": 1009.9,
"tamin": -0.1,
"ta": 0.1,
"tamax": 0.2,
"tpr": -0.3,
"rviento": 132.0,
"vv": 1.0,
"vmax": 10.0
},
{
"dv": 101.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-08T15:00:00",
"prec": 1.5,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 929.0,
"hr": 98.0,
"pres_nmar": 1008.9,
"tamin": 0.1,
"ta": 0.2,
"tamax": 0.3,
"tpr": 0.0,
"rviento": 154.0,
"vv": 1.1,
"vmax": 10.1
},
{
"dv": 102.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-08T16:00:00",
"prec": 0.7,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 928.8,
"hr": 98.0,
"pres_nmar": 1008.6,
"tamin": 0.2,
"ta": 0.3,
"tamax": 0.3,
"tpr": 0.0,
"rviento": 177.0,
"vv": 1.2,
"vmax": 10.2
},
{
"dv": 103.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-08T17:00:00",
"prec": 1.7,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 928.6,
"hr": 99.0,
"pres_nmar": 1008.5,
"tamin": 0.1,
"ta": 0.1,
"tamax": 0.3,
"tpr": 0.0,
"rviento": 174.0,
"vv": 1.3,
"vmax": 10.3
},
{
"dv": 104.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-08T18:00:00",
"prec": 1.9,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 928.2,
"hr": 99.0,
"pres_nmar": 1008.1,
"tamin": -0.1,
"ta": -0.1,
"tamax": 0.1,
"tpr": -0.3,
"rviento": 163.0,
"vv": 1.4,
"vmax": 10.4
},
{
"dv": 105.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-08T19:00:00",
"prec": 3.0,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 928.4,
"hr": 99.0,
"pres_nmar": 1008.4,
"tamin": -0.3,
"ta": -0.3,
"tamax": 0.0,
"tpr": -0.5,
"rviento": 79.0,
"vv": 1.5,
"vmax": 10.5
},
{
"dv": 106.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-08T20:00:00",
"prec": 3.5,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 928.4,
"hr": 99.0,
"pres_nmar": 1008.5,
"tamin": -0.6,
"ta": -0.6,
"tamax": -0.3,
"tpr": -0.7,
"rviento": 0.0,
"vv": 1.6,
"vmax": 10.6
},
{
"dv": 107.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-08T21:00:00",
"prec": 2.6,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 928.1,
"hr": 99.0,
"pres_nmar": 1008.2,
"tamin": -0.7,
"ta": -0.7,
"tamax": -0.5,
"tpr": -0.7,
"rviento": 0.0,
"vv": 1.7,
"vmax": 10.7
},
{
"dv": 108.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-08T22:00:00",
"prec": 3.0,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 927.6,
"hr": 99.0,
"pres_nmar": 1007.7,
"tamin": -0.8,
"ta": -0.8,
"tamax": -0.7,
"tpr": -1.0,
"rviento": 0.0,
"vv": 1.8,
"vmax": 10.8
},
{
"dv": 109.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-08T23:00:00",
"prec": 2.9,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 926.9,
"hr": 99.0,
"pres_nmar": 1007.0,
"tamin": -0.9,
"ta": -0.9,
"tamax": -0.7,
"tpr": -1.0,
"rviento": 0.0,
"vv": 1.9,
"vmax": 10.9
},
{
"dv": 110.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-09T00:00:00",
"prec": 1.4,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 926.5,
"hr": 99.0,
"pres_nmar": 1006.6,
"tamin": -1.0,
"ta": -1.0,
"tamax": -0.8,
"tpr": -1.2,
"rviento": 0.0,
"vv": 2.0,
"vmax": 11.0
},
{
"dv": 111.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-09T01:00:00",
"prec": 2.0,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 925.9,
"hr": 99.0,
"pres_nmar": 1006.0,
"tamin": -1.3,
"ta": -1.3,
"tamax": -1.0,
"tpr": -1.4,
"rviento": 0.0,
"vv": 2.1,
"vmax": 11.1
},
{
"dv": 112.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-09T02:00:00",
"prec": 1.5,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 925.7,
"hr": 99.0,
"pres_nmar": 1005.8,
"tamin": -1.5,
"ta": -1.4,
"tamax": -1.3,
"tpr": -1.4,
"rviento": 0.0,
"vv": 2.2,
"vmax": 11.2
},
{
"dv": 113.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-09T03:00:00",
"prec": 1.2,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 925.6,
"hr": 99.0,
"pres_nmar": 1005.7,
"tamin": -1.5,
"ta": -1.4,
"tamax": -1.4,
"tpr": -1.4,
"rviento": 0.0,
"vv": 2.3,
"vmax": 11.3
},
{
"dv": 114.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-09T04:00:00",
"prec": 1.1,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 924.9,
"hr": 99.0,
"pres_nmar": 1005.0,
"tamin": -1.5,
"ta": -1.5,
"tamax": -1.4,
"tpr": -1.7,
"rviento": 0.0,
"vv": 2.4,
"vmax": 11.4
},
{
"dv": 115.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-09T05:00:00",
"prec": 0.7,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 924.6,
"hr": 99.0,
"pres_nmar": 1004.7,
"tamin": -1.5,
"ta": -1.5,
"tamax": -1.4,
"tpr": -1.7,
"rviento": 0.0,
"vv": 2.5,
"vmax": 11.5
},
{
"dv": 116.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-09T06:00:00",
"prec": 0.2,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 924.4,
"hr": 99.0,
"pres_nmar": 1004.5,
"tamin": -1.6,
"ta": -1.6,
"tamax": -1.5,
"tpr": -1.7,
"rviento": 0.0,
"vv": 2.6,
"vmax": 11.6
},
{
"dv": 117.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-09T07:00:00",
"prec": 0.0,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 924.4,
"hr": 99.0,
"pres_nmar": 1004.5,
"tamin": -1.6,
"ta": -1.6,
"tamax": -1.6,
"tpr": -1.7,
"rviento": 0.0,
"vv": 2.7,
"vmax": 11.7
},
{
"dv": 118.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-09T08:00:00",
"prec": 0.1,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 924.8,
"hr": 99.0,
"pres_nmar": 1004.9,
"tamin": -1.6,
"ta": -1.6,
"tamax": -1.5,
"tpr": -1.7,
"rviento": 0.0,
"vv": 2.8,
"vmax": 11.8
},
{
"dv": 119.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-09T09:00:00",
"prec": 0.0,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 925.0,
"hr": 99.0,
"pres_nmar": 1005.0,
"tamin": -1.6,
"ta": -1.3,
"tamax": -1.3,
"tpr": -1.4,
"rviento": 0.0,
"vv": 2.9,
"vmax": 11.9
},
{
"dv": 120.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-09T10:00:00",
"prec": 0.0,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 925.3,
"hr": 99.0,
"pres_nmar": 1005.3,
"tamin": -1.3,
"ta": -1.2,
"tamax": -1.1,
"tpr": -1.4,
"rviento": 0.0,
"vv": 3.0,
"vmax": 12.0
},
{
"dv": 121.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-09T11:00:00",
"prec": 4.4,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 925.4,
"hr": 99.0,
"pres_nmar": 1005.4,
"tamin": -1.2,
"ta": -1.0,
"tamax": -1.0,
"tpr": -1.2,
"rviento": 0.0,
"vv": 3.1,
"vmax": 12.1
},
{
"dv": 122.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-09T12:00:00",
"prec": 7.0,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 924.6,
"hr": 99.0,
"pres_nmar": 1004.4,
"tamin": -1.0,
"ta": -0.7,
"tamax": -0.6,
"tpr": -0.7,
"rviento": 0.0,
"vv": 3.2,
"vmax": 12.2
}
]

View File

@@ -0,0 +1,55 @@
[
{
"dv": 90.0,
"idema": "3194U",
"lon": -3.724167,
"fint": "2021-01-08T14:00:00",
"prec": 1.3,
"alt": 664.0,
"lat": 40.45167,
"ubi": "MADRID C. UNIVERSITARIA",
"hr": 98.0,
"tamin": 0.6,
"ta": 0.9,
"tamax": 1.0,
"tpr": 0.6,
"vv": 2.0,
"vmax": 2.5
},
{
"dv": 120.0,
"idema": "3194Y",
"lon": -3.813369,
"fint": "2021-01-08T14:00:00",
"prec": 0.2,
"alt": 665.0,
"lat": 40.448437,
"ubi": "POZUELO DE ALARCON (AUTOM<4F>TICA)",
"hr": 93.0,
"tamin": 0.5,
"ta": 0.6,
"tamax": 0.6,
"vv": 3.0,
"vmax": 3.5
},
{
"dv": 100.0,
"idema": "3195",
"lon": -3.678095,
"fint": "2021-01-08T14:00:00",
"prec": 1.2,
"alt": 667.0,
"lat": 40.411804,
"ubi": "MADRID RETIRO",
"pres": 929.9,
"hr": 97.0,
"pres_nmar": 1009.9,
"tamin": -0.1,
"ta": 0.1,
"tamax": 0.2,
"tpr": -0.3,
"rviento": 132.0,
"vv": 1.0,
"vmax": 10.0
}
]

View File

@@ -0,0 +1,815 @@
[
{
"origen": {
"productor": "Agencia Estatal de Meteorolog<6F>a - AEMET. Gobierno de Espa<70>a",
"web": "http://www.aemet.es",
"enlace": "http://www.aemet.es/es/eltiempo/prediccion/municipios/getafe-id28065",
"language": "es",
"copyright": "<22> AEMET. Autorizado el uso de la informaci<63>n y su reproducci<63>n citando a AEMET como autora de la misma.",
"notaLegal": "http://www.aemet.es/es/nota_legal"
},
"elaborado": "2021-01-09T11:54:00",
"nombre": "Getafe",
"provincia": "Madrid",
"prediccion": {
"dia": [
{
"probPrecipitacion": [
{
"value": 0,
"periodo": "00-24"
},
{
"value": 0,
"periodo": "00-12"
},
{
"value": 100,
"periodo": "12-24"
},
{
"value": 0,
"periodo": "00-06"
},
{
"value": 100,
"periodo": "06-12"
},
{
"value": 100,
"periodo": "12-18"
},
{
"value": 100,
"periodo": "18-24"
}
],
"cotaNieveProv": [
{
"value": "",
"periodo": "00-24"
},
{
"value": "",
"periodo": "00-12"
},
{
"value": "500",
"periodo": "12-24"
},
{
"value": "",
"periodo": "00-06"
},
{
"value": "400",
"periodo": "06-12"
},
{
"value": "500",
"periodo": "12-18"
},
{
"value": "600",
"periodo": "18-24"
}
],
"estadoCielo": [
{
"value": "",
"periodo": "00-24",
"descripcion": ""
},
{
"value": "",
"periodo": "00-12",
"descripcion": ""
},
{
"value": "36",
"periodo": "12-24",
"descripcion": "Cubierto con nieve"
},
{
"value": "",
"periodo": "00-06",
"descripcion": ""
},
{
"value": "36",
"periodo": "06-12",
"descripcion": "Cubierto con nieve"
},
{
"value": "36",
"periodo": "12-18",
"descripcion": "Cubierto con nieve"
},
{
"value": "34n",
"periodo": "18-24",
"descripcion": "Nuboso con nieve"
}
],
"viento": [
{
"direccion": "",
"velocidad": 0,
"periodo": "00-24"
},
{
"direccion": "",
"velocidad": 0,
"periodo": "00-12"
},
{
"direccion": "E",
"velocidad": 15,
"periodo": "12-24"
},
{
"direccion": "NE",
"velocidad": 30,
"periodo": "00-06"
},
{
"direccion": "E",
"velocidad": 15,
"periodo": "06-12"
},
{
"direccion": "E",
"velocidad": 5,
"periodo": "12-18"
},
{
"direccion": "NE",
"velocidad": 5,
"periodo": "18-24"
}
],
"rachaMax": [
{
"value": "",
"periodo": "00-24"
},
{
"value": "",
"periodo": "00-12"
},
{
"value": "",
"periodo": "12-24"
},
{
"value": "40",
"periodo": "00-06"
},
{
"value": "",
"periodo": "06-12"
},
{
"value": "",
"periodo": "12-18"
},
{
"value": "",
"periodo": "18-24"
}
],
"temperatura": {
"maxima": 2,
"minima": -1,
"dato": [
{
"value": -1,
"hora": 6
},
{
"value": 0,
"hora": 12
},
{
"value": 1,
"hora": 18
},
{
"value": 1,
"hora": 24
}
]
},
"sensTermica": {
"maxima": 1,
"minima": -9,
"dato": [
{
"value": -1,
"hora": 6
},
{
"value": -4,
"hora": 12
},
{
"value": 1,
"hora": 18
},
{
"value": 1,
"hora": 24
}
]
},
"humedadRelativa": {
"maxima": 100,
"minima": 75,
"dato": [
{
"value": 100,
"hora": 6
},
{
"value": 100,
"hora": 12
},
{
"value": 95,
"hora": 18
},
{
"value": 75,
"hora": 24
}
]
},
"uvMax": 1,
"fecha": "2021-01-09T00:00:00"
},
{
"probPrecipitacion": [
{
"value": 30,
"periodo": "00-24"
},
{
"value": 25,
"periodo": "00-12"
},
{
"value": 5,
"periodo": "12-24"
},
{
"value": 5,
"periodo": "00-06"
},
{
"value": 15,
"periodo": "06-12"
},
{
"value": 5,
"periodo": "12-18"
},
{
"value": 0,
"periodo": "18-24"
}
],
"cotaNieveProv": [
{
"value": "600",
"periodo": "00-24"
},
{
"value": "600",
"periodo": "00-12"
},
{
"value": "",
"periodo": "12-24"
},
{
"value": "",
"periodo": "00-06"
},
{
"value": "600",
"periodo": "06-12"
},
{
"value": "",
"periodo": "12-18"
},
{
"value": "",
"periodo": "18-24"
}
],
"estadoCielo": [
{
"value": "13",
"periodo": "00-24",
"descripcion": "Intervalos nubosos"
},
{
"value": "15",
"periodo": "00-12",
"descripcion": "Muy nuboso"
},
{
"value": "12",
"periodo": "12-24",
"descripcion": "Poco nuboso"
},
{
"value": "14n",
"periodo": "00-06",
"descripcion": "Nuboso"
},
{
"value": "15",
"periodo": "06-12",
"descripcion": "Muy nuboso"
},
{
"value": "12",
"periodo": "12-18",
"descripcion": "Poco nuboso"
},
{
"value": "12n",
"periodo": "18-24",
"descripcion": "Poco nuboso"
}
],
"viento": [
{
"direccion": "NE",
"velocidad": 20,
"periodo": "00-24"
},
{
"direccion": "NE",
"velocidad": 20,
"periodo": "00-12"
},
{
"direccion": "NE",
"velocidad": 20,
"periodo": "12-24"
},
{
"direccion": "N",
"velocidad": 10,
"periodo": "00-06"
},
{
"direccion": "NE",
"velocidad": 20,
"periodo": "06-12"
},
{
"direccion": "NE",
"velocidad": 15,
"periodo": "12-18"
},
{
"direccion": "NE",
"velocidad": 20,
"periodo": "18-24"
}
],
"rachaMax": [
{
"value": "30",
"periodo": "00-24"
},
{
"value": "30",
"periodo": "00-12"
},
{
"value": "30",
"periodo": "12-24"
},
{
"value": "",
"periodo": "00-06"
},
{
"value": "30",
"periodo": "06-12"
},
{
"value": "",
"periodo": "12-18"
},
{
"value": "",
"periodo": "18-24"
}
],
"temperatura": {
"maxima": 4,
"minima": -4,
"dato": [
{
"value": -1,
"hora": 6
},
{
"value": 3,
"hora": 12
},
{
"value": 1,
"hora": 18
},
{
"value": -1,
"hora": 24
}
]
},
"sensTermica": {
"maxima": 1,
"minima": -7,
"dato": [
{
"value": -4,
"hora": 6
},
{
"value": -2,
"hora": 12
},
{
"value": -4,
"hora": 18
},
{
"value": -6,
"hora": 24
}
]
},
"humedadRelativa": {
"maxima": 100,
"minima": 70,
"dato": [
{
"value": 90,
"hora": 6
},
{
"value": 75,
"hora": 12
},
{
"value": 80,
"hora": 18
},
{
"value": 80,
"hora": 24
}
]
},
"uvMax": 1,
"fecha": "2021-01-10T00:00:00"
},
{
"probPrecipitacion": [
{
"value": 0,
"periodo": "00-24"
},
{
"value": 0,
"periodo": "00-12"
},
{
"value": 0,
"periodo": "12-24"
}
],
"cotaNieveProv": [
{
"value": "",
"periodo": "00-24"
},
{
"value": "",
"periodo": "00-12"
},
{
"value": "",
"periodo": "12-24"
}
],
"estadoCielo": [
{
"value": "12",
"periodo": "00-24",
"descripcion": "Poco nuboso"
},
{
"value": "12",
"periodo": "00-12",
"descripcion": "Poco nuboso"
},
{
"value": "12",
"periodo": "12-24",
"descripcion": "Poco nuboso"
}
],
"viento": [
{
"direccion": "N",
"velocidad": 5,
"periodo": "00-24"
},
{
"direccion": "NE",
"velocidad": 20,
"periodo": "00-12"
},
{
"direccion": "NO",
"velocidad": 10,
"periodo": "12-24"
}
],
"rachaMax": [
{
"value": "",
"periodo": "00-24"
},
{
"value": "",
"periodo": "00-12"
},
{
"value": "",
"periodo": "12-24"
}
],
"temperatura": {
"maxima": 3,
"minima": -7,
"dato": []
},
"sensTermica": {
"maxima": 3,
"minima": -8,
"dato": []
},
"humedadRelativa": {
"maxima": 85,
"minima": 60,
"dato": []
},
"uvMax": 1,
"fecha": "2021-01-11T00:00:00"
},
{
"probPrecipitacion": [
{
"value": 0,
"periodo": "00-24"
},
{
"value": 0,
"periodo": "00-12"
},
{
"value": 0,
"periodo": "12-24"
}
],
"cotaNieveProv": [
{
"value": "",
"periodo": "00-24"
},
{
"value": "",
"periodo": "00-12"
},
{
"value": "",
"periodo": "12-24"
}
],
"estadoCielo": [
{
"value": "12",
"periodo": "00-24",
"descripcion": "Poco nuboso"
},
{
"value": "12",
"periodo": "00-12",
"descripcion": "Poco nuboso"
},
{
"value": "12",
"periodo": "12-24",
"descripcion": "Poco nuboso"
}
],
"viento": [
{
"direccion": "C",
"velocidad": 0,
"periodo": "00-24"
},
{
"direccion": "E",
"velocidad": 5,
"periodo": "00-12"
},
{
"direccion": "C",
"velocidad": 0,
"periodo": "12-24"
}
],
"rachaMax": [
{
"value": "",
"periodo": "00-24"
},
{
"value": "",
"periodo": "00-12"
},
{
"value": "",
"periodo": "12-24"
}
],
"temperatura": {
"maxima": -1,
"minima": -13,
"dato": []
},
"sensTermica": {
"maxima": -1,
"minima": -13,
"dato": []
},
"humedadRelativa": {
"maxima": 100,
"minima": 65,
"dato": []
},
"uvMax": 2,
"fecha": "2021-01-12T00:00:00"
},
{
"probPrecipitacion": [
{
"value": 0
}
],
"cotaNieveProv": [
{
"value": ""
}
],
"estadoCielo": [
{
"value": "11",
"descripcion": "Despejado"
}
],
"viento": [
{
"direccion": "C",
"velocidad": 0
}
],
"rachaMax": [
{
"value": ""
}
],
"temperatura": {
"maxima": 6,
"minima": -11,
"dato": []
},
"sensTermica": {
"maxima": 6,
"minima": -11,
"dato": []
},
"humedadRelativa": {
"maxima": 100,
"minima": 65,
"dato": []
},
"uvMax": 2,
"fecha": "2021-01-13T00:00:00"
},
{
"probPrecipitacion": [
{
"value": 0
}
],
"cotaNieveProv": [
{
"value": ""
}
],
"estadoCielo": [
{
"value": "12",
"descripcion": "Poco nuboso"
}
],
"viento": [
{
"direccion": "C",
"velocidad": 0
}
],
"rachaMax": [
{
"value": ""
}
],
"temperatura": {
"maxima": 6,
"minima": -7,
"dato": []
},
"sensTermica": {
"maxima": 6,
"minima": -7,
"dato": []
},
"humedadRelativa": {
"maxima": 100,
"minima": 80,
"dato": []
},
"fecha": "2021-01-14T00:00:00"
},
{
"probPrecipitacion": [
{
"value": 0
}
],
"cotaNieveProv": [
{
"value": ""
}
],
"estadoCielo": [
{
"value": "14",
"descripcion": "Nuboso"
}
],
"viento": [
{
"direccion": "C",
"velocidad": 0
}
],
"rachaMax": [
{
"value": ""
}
],
"temperatura": {
"maxima": 5,
"minima": -4,
"dato": []
},
"sensTermica": {
"maxima": 5,
"minima": -4,
"dato": []
},
"humedadRelativa": {
"maxima": 100,
"minima": 55,
"dato": []
},
"fecha": "2021-01-15T00:00:00"
}
]
},
"id": 28065,
"version": 1.0
}
]

View File

@@ -0,0 +1,17 @@
[
{
"latitud": "40<34>18'14.535144\"",
"id_old": "28325",
"url": "getafe-id28065",
"latitud_dec": "40.30403754",
"altitud": "622",
"capital": "Getafe",
"num_hab": "173057",
"zona_comarcal": "722802",
"destacada": "1",
"nombre": "Getafe",
"longitud_dec": "-3.72935236",
"id": "id28065",
"longitud": "-3<>43'45.668496\""
}
]

View File

@@ -0,0 +1,47 @@
[
{
"latitud": "40<34>18'14.535144\"",
"id_old": "28325",
"url": "getafe-id28065",
"latitud_dec": "40.30403754",
"altitud": "622",
"capital": "Getafe",
"num_hab": "173057",
"zona_comarcal": "722802",
"destacada": "1",
"nombre": "Getafe",
"longitud_dec": "-3.72935236",
"id": "id28065",
"longitud": "-3<>43'45.668496\""
},
{
"latitud": "40<34>19'54.277752\"",
"id_old": "28370",
"url": "leganes-id28074",
"latitud_dec": "40.33174382",
"altitud": "667",
"capital": "Legan<61>s",
"num_hab": "186696",
"zona_comarcal": "722802",
"destacada": "1",
"nombre": "Legan<61>s",
"longitud_dec": "-3.76655557",
"id": "id28074",
"longitud": "-3<>45'59.600052\""
},
{
"latitud": "40<34>24'30.282876\"",
"id_old": "28001",
"url": "madrid-id28079",
"latitud_dec": "40.40841191",
"altitud": "657",
"capital": "Madrid",
"num_hab": "3165235",
"zona_comarcal": "722802",
"destacada": "1",
"nombre": "Madrid",
"longitud_dec": "-3.68760088",
"id": "id28079",
"longitud": "-3<>41'15.363168\""
}
]

View File

@@ -0,0 +1,122 @@
# serializer version: 1
# name: test_config_entry_diagnostics
dict({
'api_data': dict({
}),
'config_entry': dict({
'data': dict({
'api_key': '**REDACTED**',
'latitude': '**REDACTED**',
'longitude': '**REDACTED**',
'name': 'AEMET',
}),
'disabled_by': None,
'discovery_keys': dict({
}),
'domain': 'aemet',
'entry_id': '7442b231f139e813fc1939281123f220',
'minor_version': 1,
'options': dict({
'radar_updates': True,
}),
'pref_disable_new_entities': False,
'pref_disable_polling': False,
'source': 'user',
'title': 'Mock Title',
'unique_id': '**REDACTED**',
'version': 1,
}),
'coord_data': dict({
'forecast': dict({
'forecast-daily': list([
]),
'forecast-hourly': list([
]),
}),
'lib': dict({
'radar': dict({
'datetime': '2021-01-09T11:34:06.448809+00:00',
'id': 'national',
'image-bytes': '**REDACTED**',
'image-type': 'image/gif',
}),
'station': dict({
'altitude': 667.0,
'coordinates': '**REDACTED**',
'datetime': '2021-01-09T13:00:00+01:00',
'dew-point': -0.7,
'distance': 12.746,
'humidity': 99.0,
'id': '3195',
'name': 'MADRID RETIRO',
'outdated': True,
'precipitation': 7.0,
'pressure': 1004.4,
'temperature': -0.7,
'temperature-max': -0.6,
'temperature-min': -1.0,
'timestamp-utc': '2021-01-09T13:00:00+01:00',
'timezone': dict({
'__type': "<class 'zoneinfo.ZoneInfo'>",
'repr': "zoneinfo.ZoneInfo(key='Europe/Madrid')",
}),
'wind-direction': 122.0,
'wind-speed': 3.2,
'wind-speed-max': 12.2,
}),
'timestamp-utc': '2024-02-23T18:00:00+00:00',
'town': dict({
'altitude': 622,
'coordinates': '**REDACTED**',
'distance': 0.0,
'forecast-daily': dict({
'forecast': list([
]),
'timestamp-local': '2021-01-09T11:54:00+00:00',
'timestamp-utc': '2021-01-09T11:54:00+00:00',
'timezone': dict({
'__type': "<class 'zoneinfo.ZoneInfo'>",
'repr': "zoneinfo.ZoneInfo(key='Europe/Madrid')",
}),
}),
'forecast-hourly': dict({
'forecast': list([
]),
'timestamp-local': '2021-01-09T11:47:45+00:00',
'timestamp-utc': '2021-01-09T11:47:45+00:00',
'timezone': dict({
'__type': "<class 'zoneinfo.ZoneInfo'>",
'repr': "zoneinfo.ZoneInfo(key='Europe/Madrid')",
}),
}),
'id': 'id28065',
'name': 'Getafe',
'residents': 173057,
'timezone': dict({
'__type': "<class 'zoneinfo.ZoneInfo'>",
'repr': "zoneinfo.ZoneInfo(key='Europe/Madrid')",
}),
}),
'weather': dict({
'condition': None,
'dew-point': None,
'feel-temperature': None,
'humidity': None,
'precipitation': None,
'precipitation-probability': None,
'pressure': None,
'rain': None,
'rain-probability': None,
'snow': None,
'snow-probability': None,
'storm-probability': None,
'temperature': None,
'uv-index': None,
'wind-direction': None,
'wind-speed': None,
'wind-speed-max': None,
}),
}),
}),
})
# ---

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,159 @@
"""Define tests for the AEMET OpenData config flow."""
from unittest.mock import AsyncMock, MagicMock, patch
from aemet_opendata.exceptions import AuthError
from freezegun.api import FrozenDateTimeFactory
import pytest
from homeassistant.components.aemet.const import (
CONF_RADAR_UPDATES,
CONF_STATION_UPDATES,
DOMAIN,
)
from homeassistant.config_entries import SOURCE_USER, ConfigEntryState
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 .util import mock_api_call
from tests.common import MockConfigEntry
pytestmark = pytest.mark.usefixtures("mock_setup_entry")
CONFIG = {
CONF_NAME: "aemet",
CONF_API_KEY: "foo",
CONF_LATITUDE: 40.30403754,
CONF_LONGITUDE: -3.72935236,
}
async def test_form(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None:
"""Test that the form is served with valid input."""
with patch(
"homeassistant.components.aemet.AEMET.api_call",
side_effect=mock_api_call,
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], CONFIG
)
await hass.async_block_till_done()
conf_entries = hass.config_entries.async_entries(DOMAIN)
entry = conf_entries[0]
assert entry.state is ConfigEntryState.LOADED
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == CONFIG[CONF_NAME]
assert result["data"][CONF_LATITUDE] == CONFIG[CONF_LATITUDE]
assert result["data"][CONF_LONGITUDE] == CONFIG[CONF_LONGITUDE]
assert result["data"][CONF_API_KEY] == CONFIG[CONF_API_KEY]
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.parametrize(
("user_input", "expected"),
[
({}, {CONF_RADAR_UPDATES: False, CONF_STATION_UPDATES: True}),
(
{CONF_RADAR_UPDATES: False, CONF_STATION_UPDATES: False},
{CONF_RADAR_UPDATES: False, CONF_STATION_UPDATES: False},
),
],
)
async def test_form_options(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
user_input: dict[str, bool],
expected: dict[str, bool],
) -> None:
"""Test the form options."""
await hass.config.async_set_time_zone("UTC")
freezer.move_to("2021-01-09 12:00:00+00:00")
with patch(
"homeassistant.components.aemet.AEMET.api_call",
side_effect=mock_api_call,
):
entry = MockConfigEntry(
domain=DOMAIN, unique_id="40.30403754--3.72935236", data=CONFIG
)
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.LOADED
result = await hass.config_entries.options.async_init(entry.entry_id)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "init"
result = await hass.config_entries.options.async_configure(
result["flow_id"], user_input=user_input
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert entry.options == {
CONF_RADAR_UPDATES: expected[CONF_RADAR_UPDATES],
CONF_STATION_UPDATES: expected[CONF_STATION_UPDATES],
}
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.LOADED
async def test_form_duplicated_id(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test setting up duplicated entry."""
await hass.config.async_set_time_zone("UTC")
freezer.move_to("2021-01-09 12:00:00+00:00")
with patch(
"homeassistant.components.aemet.AEMET.api_call",
side_effect=mock_api_call,
):
entry = MockConfigEntry(
domain=DOMAIN, unique_id="40.30403754--3.72935236", data=CONFIG
)
entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=CONFIG
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_form_auth_error(hass: HomeAssistant) -> None:
"""Test setting up with api auth error."""
mocked_aemet = MagicMock()
mocked_aemet.select_coordinates.side_effect = AuthError
with patch(
"homeassistant.components.aemet.config_flow.AEMET",
return_value=mocked_aemet,
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=CONFIG
)
assert result["errors"] == {"base": "invalid_api_key"}

View File

@@ -0,0 +1,36 @@
"""Define tests for the AEMET OpenData coordinator."""
from unittest.mock import patch
from aemet_opendata.exceptions import AemetError
from freezegun.api import FrozenDateTimeFactory
from homeassistant.components.aemet.coordinator import WEATHER_UPDATE_INTERVAL
from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from .util import async_init_integration
from tests.common import async_fire_time_changed
async def test_coordinator_error(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test error on coordinator update."""
await hass.config.async_set_time_zone("UTC")
freezer.move_to("2021-01-09 12:00:00+00:00")
await async_init_integration(hass)
with patch(
"homeassistant.components.aemet.AEMET.api_call",
side_effect=AemetError,
):
freezer.tick(WEATHER_UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get("weather.aemet")
assert state.state == STATE_UNAVAILABLE

View File

@@ -0,0 +1,34 @@
"""Define tests for the AEMET OpenData diagnostics."""
from unittest.mock import patch
import pytest
from syrupy import SnapshotAssertion
from syrupy.filters import props
from homeassistant.components.aemet.const import DOMAIN
from homeassistant.core import HomeAssistant
from .util import async_init_integration
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
@pytest.mark.freeze_time("2024-02-23T18:00:00+00:00")
async def test_config_entry_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
snapshot: SnapshotAssertion,
) -> None:
"""Test config entry diagnostics."""
await async_init_integration(hass)
config_entry = hass.config_entries.async_entries(DOMAIN)[0]
with patch(
"homeassistant.components.aemet.AEMET.raw_data",
return_value={},
):
result = await get_diagnostics_for_config_entry(hass, hass_client, config_entry)
assert result == snapshot(exclude=props("created_at", "modified_at"))

View File

@@ -0,0 +1,22 @@
"""The image tests for the AEMET OpenData platform."""
from freezegun.api import FrozenDateTimeFactory
from homeassistant.core import HomeAssistant
from .util import async_init_integration
async def test_aemet_create_images(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test creation of AEMET images."""
await hass.config.async_set_time_zone("UTC")
freezer.move_to("2021-01-09 12:00:00+00:00")
await async_init_integration(hass)
state = hass.states.get("image.aemet_weather_radar")
assert state is not None
assert state.state == "2021-01-09T11:34:06.448809+00:00"

View File

@@ -0,0 +1,108 @@
"""Define tests for the AEMET OpenData init."""
from unittest.mock import patch
from aemet_opendata.exceptions import AemetTimeout
from freezegun.api import FrozenDateTimeFactory
from homeassistant.components.aemet.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .util import mock_api_call
from tests.common import MockConfigEntry
CONFIG = {
CONF_NAME: "aemet",
CONF_API_KEY: "foo",
CONF_LATITUDE: 40.30403754,
CONF_LONGITUDE: -3.72935236,
}
async def test_unload_entry(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test (un)loading the AEMET integration."""
await hass.config.async_set_time_zone("UTC")
freezer.move_to("2021-01-09 12:00:00+00:00")
with patch(
"homeassistant.components.aemet.AEMET.api_call",
side_effect=mock_api_call,
):
config_entry = MockConfigEntry(
domain=DOMAIN, unique_id="aemet_unique_id", data=CONFIG
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.NOT_LOADED
assert await hass.config_entries.async_remove(config_entry.entry_id)
await hass.async_block_till_done()
assert hass.states.get("weather.aemet") is None
assert entity_registry.async_get("weather.aemet") is None
async def test_init_town_not_found(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test TownNotFound when loading the AEMET integration."""
await hass.config.async_set_time_zone("UTC")
freezer.move_to("2021-01-09 12:00:00+00:00")
with patch(
"homeassistant.components.aemet.AEMET.api_call",
side_effect=mock_api_call,
):
config_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_API_KEY: "api-key",
CONF_LATITUDE: "0.0",
CONF_LONGITUDE: "0.0",
CONF_NAME: "AEMET",
},
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id) is False
async def test_init_api_timeout(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test API timeouts when loading the AEMET integration."""
await hass.config.async_set_time_zone("UTC")
freezer.move_to("2021-01-09 12:00:00+00:00")
with patch(
"homeassistant.components.aemet.AEMET.api_call",
side_effect=AemetTimeout,
):
config_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_API_KEY: "api-key",
CONF_LATITUDE: "0.0",
CONF_LONGITUDE: "0.0",
CONF_NAME: "AEMET",
},
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id) is False

View File

@@ -0,0 +1,138 @@
"""The sensor tests for the AEMET OpenData platform."""
from freezegun.api import FrozenDateTimeFactory
from homeassistant.components.weather import ATTR_CONDITION_SNOWY
from homeassistant.core import HomeAssistant
import homeassistant.util.dt as dt_util
from .util import async_init_integration
async def test_aemet_forecast_create_sensors(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test creation of forecast sensors."""
await hass.config.async_set_time_zone("UTC")
freezer.move_to("2021-01-09 12:00:00+00:00")
await async_init_integration(hass)
state = hass.states.get("sensor.aemet_daily_forecast_condition")
assert state.state == ATTR_CONDITION_SNOWY
state = hass.states.get("sensor.aemet_daily_forecast_precipitation_probability")
assert state.state == "0"
state = hass.states.get("sensor.aemet_daily_forecast_temperature")
assert state.state == "2"
state = hass.states.get("sensor.aemet_daily_forecast_temperature_low")
assert state.state == "-1"
state = hass.states.get("sensor.aemet_daily_forecast_time")
assert (
state.state == dt_util.parse_datetime("2021-01-08 23:00:00+00:00").isoformat()
)
state = hass.states.get("sensor.aemet_daily_forecast_wind_bearing")
assert state.state == "90.0"
state = hass.states.get("sensor.aemet_daily_forecast_wind_speed")
assert state.state == "0"
state = hass.states.get("sensor.aemet_hourly_forecast_condition")
assert state is None
state = hass.states.get("sensor.aemet_hourly_forecast_precipitation")
assert state is None
state = hass.states.get("sensor.aemet_hourly_forecast_precipitation_probability")
assert state is None
state = hass.states.get("sensor.aemet_hourly_forecast_temperature")
assert state is None
state = hass.states.get("sensor.aemet_hourly_forecast_temperature_low")
assert state is None
state = hass.states.get("sensor.aemet_hourly_forecast_time")
assert state is None
state = hass.states.get("sensor.aemet_hourly_forecast_wind_bearing")
assert state is None
state = hass.states.get("sensor.aemet_hourly_forecast_wind_max_speed")
assert state is None
state = hass.states.get("sensor.aemet_hourly_forecast_wind_speed")
assert state is None
async def test_aemet_weather_create_sensors(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test creation of weather sensors."""
await hass.config.async_set_time_zone("UTC")
freezer.move_to("2021-01-09 12:00:00+00:00")
await async_init_integration(hass)
state = hass.states.get("sensor.aemet_condition")
assert state.state == ATTR_CONDITION_SNOWY
state = hass.states.get("sensor.aemet_humidity")
assert state.state == "99.0"
state = hass.states.get("sensor.aemet_pressure")
assert state.state == "1004.4"
state = hass.states.get("sensor.aemet_rain")
assert state.state == "7.0"
state = hass.states.get("sensor.aemet_rain_probability")
assert state.state == "100"
state = hass.states.get("sensor.aemet_snow")
assert state.state == "1.2"
state = hass.states.get("sensor.aemet_snow_probability")
assert state.state == "100"
state = hass.states.get("sensor.aemet_station_id")
assert state.state == "3195"
state = hass.states.get("sensor.aemet_station_name")
assert state.state == "MADRID RETIRO"
state = hass.states.get("sensor.aemet_station_timestamp")
assert state.state == "2021-01-09T12:00:00+00:00"
state = hass.states.get("sensor.aemet_storm_probability")
assert state.state == "0"
state = hass.states.get("sensor.aemet_temperature")
assert state.state == "-0.7"
state = hass.states.get("sensor.aemet_temperature_feeling")
assert state.state == "-4"
state = hass.states.get("sensor.aemet_town_id")
assert state.state == "id28065"
state = hass.states.get("sensor.aemet_town_name")
assert state.state == "Getafe"
state = hass.states.get("sensor.aemet_town_timestamp")
assert state.state == "2021-01-09T11:47:45+00:00"
state = hass.states.get("sensor.aemet_wind_bearing")
assert state.state == "122.0"
state = hass.states.get("sensor.aemet_wind_max_speed")
assert state.state == "12.2"
state = hass.states.get("sensor.aemet_wind_speed")
assert state.state == "3.2"

View File

@@ -0,0 +1,143 @@
"""The sensor tests for the AEMET OpenData platform."""
import datetime
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.aemet.const import ATTRIBUTION
from homeassistant.components.aemet.coordinator import WEATHER_UPDATE_INTERVAL
from homeassistant.components.weather import (
ATTR_CONDITION_SNOWY,
ATTR_WEATHER_HUMIDITY,
ATTR_WEATHER_PRESSURE,
ATTR_WEATHER_TEMPERATURE,
ATTR_WEATHER_WIND_BEARING,
ATTR_WEATHER_WIND_GUST_SPEED,
ATTR_WEATHER_WIND_SPEED,
DOMAIN as WEATHER_DOMAIN,
SERVICE_GET_FORECASTS,
)
from homeassistant.const import ATTR_ATTRIBUTION
from homeassistant.core import HomeAssistant
from .util import async_init_integration, mock_api_call
from tests.typing import WebSocketGenerator
async def test_aemet_weather(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test states of the weather."""
await hass.config.async_set_time_zone("UTC")
freezer.move_to("2021-01-09 12:00:00+00:00")
await async_init_integration(hass)
state = hass.states.get("weather.aemet")
assert state
assert state.state == ATTR_CONDITION_SNOWY
assert state.attributes[ATTR_ATTRIBUTION] == ATTRIBUTION
assert state.attributes[ATTR_WEATHER_HUMIDITY] == 99.0
assert state.attributes[ATTR_WEATHER_PRESSURE] == 1004.4 # 100440.0 Pa -> hPa
assert state.attributes[ATTR_WEATHER_TEMPERATURE] == -0.7
assert state.attributes[ATTR_WEATHER_WIND_BEARING] == 122.0
assert state.attributes[ATTR_WEATHER_WIND_GUST_SPEED] == 12.2
assert state.attributes[ATTR_WEATHER_WIND_SPEED] == 3.2
state = hass.states.get("weather.aemet_hourly")
assert state is None
@pytest.mark.parametrize(
("service"),
[SERVICE_GET_FORECASTS],
)
async def test_forecast_service(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
snapshot: SnapshotAssertion,
service: str,
) -> None:
"""Test multiple forecast."""
await hass.config.async_set_time_zone("UTC")
freezer.move_to("2021-01-09 12:00:00+00:00")
await async_init_integration(hass)
response = await hass.services.async_call(
WEATHER_DOMAIN,
service,
{
"entity_id": "weather.aemet",
"type": "daily",
},
blocking=True,
return_response=True,
)
assert response == snapshot
response = await hass.services.async_call(
WEATHER_DOMAIN,
service,
{
"entity_id": "weather.aemet",
"type": "hourly",
},
blocking=True,
return_response=True,
)
assert response == snapshot
@pytest.mark.parametrize("forecast_type", ["daily", "hourly"])
async def test_forecast_subscription(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
freezer: FrozenDateTimeFactory,
snapshot: SnapshotAssertion,
forecast_type: str,
) -> None:
"""Test multiple forecast."""
client = await hass_ws_client(hass)
await hass.config.async_set_time_zone("UTC")
freezer.move_to("2021-01-09 12:00:00+00:00")
await async_init_integration(hass)
await client.send_json_auto_id(
{
"type": "weather/subscribe_forecast",
"forecast_type": forecast_type,
"entity_id": "weather.aemet",
}
)
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 == snapshot
with patch(
"homeassistant.components.aemet.AEMET.api_call",
side_effect=mock_api_call,
):
freezer.tick(WEATHER_UPDATE_INTERVAL + datetime.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 == snapshot

View File

@@ -0,0 +1,94 @@
"""Tests for the AEMET OpenData integration."""
from typing import Any
from unittest.mock import patch
from aemet_opendata.const import ATTR_BYTES, ATTR_DATA, ATTR_TIMESTAMP, ATTR_TYPE
from homeassistant.components.aemet.const import CONF_RADAR_UPDATES, DOMAIN
from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry, load_json_value_fixture
FORECAST_DAILY_DATA_MOCK = {
ATTR_DATA: load_json_value_fixture("aemet/town-28065-forecast-daily-data.json"),
}
FORECAST_HOURLY_DATA_MOCK = {
ATTR_DATA: load_json_value_fixture("aemet/town-28065-forecast-hourly-data.json"),
}
RADAR_DATA_MOCK = {
ATTR_DATA: {
ATTR_TYPE: "image/gif",
ATTR_BYTES: bytes([0]),
},
ATTR_TIMESTAMP: "2021-01-09T11:34:06.448809+00:00",
}
STATION_DATA_MOCK = {
ATTR_DATA: load_json_value_fixture("aemet/station-3195-data.json"),
}
STATIONS_DATA_MOCK = {
ATTR_DATA: load_json_value_fixture("aemet/station-list-data.json"),
}
TOWN_DATA_MOCK = {
ATTR_DATA: load_json_value_fixture("aemet/town-id28065.json"),
}
TOWNS_DATA_MOCK = {
ATTR_DATA: load_json_value_fixture("aemet/town-list.json"),
}
def mock_api_call(cmd: str, fetch_data: bool = False) -> dict[str, Any]:
"""Mock AEMET OpenData API calls."""
if cmd == "maestro/municipio/id28065":
return TOWN_DATA_MOCK
if cmd == "maestro/municipios":
return TOWNS_DATA_MOCK
if (
cmd
== "observacion/convencional/datos/estacion/3195" # codespell:ignore convencional
):
return STATION_DATA_MOCK
if cmd == "observacion/convencional/todas": # codespell:ignore convencional
return STATIONS_DATA_MOCK
if cmd == "prediccion/especifica/municipio/diaria/28065":
return FORECAST_DAILY_DATA_MOCK
if cmd == "prediccion/especifica/municipio/horaria/28065":
return FORECAST_HOURLY_DATA_MOCK
if cmd == "red/radar/nacional":
return RADAR_DATA_MOCK
return {}
async def async_init_integration(hass: HomeAssistant):
"""Set up the AEMET OpenData integration in Home Assistant."""
config_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_API_KEY: "api-key",
CONF_LATITUDE: "40.30403754",
CONF_LONGITUDE: "-3.72935236",
CONF_NAME: "AEMET",
},
entry_id="7442b231f139e813fc1939281123f220",
unique_id="40.30403754--3.72935236",
options={
CONF_RADAR_UPDATES: True,
},
)
config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.aemet.AEMET.api_call",
side_effect=mock_api_call,
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()

View File

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

View File

@@ -0,0 +1,15 @@
"""Common fixtures for the AfterShip tests."""
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.aftership.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry

View File

@@ -0,0 +1,75 @@
"""Test AfterShip config flow."""
from unittest.mock import AsyncMock, patch
from pyaftership import AfterShipException
from homeassistant.components.aftership.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_API_KEY
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
async def test_full_user_flow(hass: HomeAssistant, mock_setup_entry) -> None:
"""Test the full user configuration flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
with patch(
"homeassistant.components.aftership.config_flow.AfterShip",
return_value=AsyncMock(),
) as mock_aftership:
mock_aftership.return_value.trackings.return_value.list.return_value = {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_API_KEY: "mock-api-key",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "AfterShip"
assert result["data"] == {
CONF_API_KEY: "mock-api-key",
}
async def test_flow_cannot_connect(hass: HomeAssistant, mock_setup_entry) -> None:
"""Test handling invalid connection."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
with patch(
"homeassistant.components.aftership.config_flow.AfterShip",
return_value=AsyncMock(),
) as mock_aftership:
mock_aftership.side_effect = AfterShipException
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_API_KEY: "mock-api-key",
},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
with patch(
"homeassistant.components.aftership.config_flow.AfterShip",
return_value=AsyncMock(),
) as mock_aftership:
mock_aftership.return_value.trackings.return_value.list.return_value = {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_API_KEY: "mock-api-key",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "AfterShip"
assert result["data"] == {
CONF_API_KEY: "mock-api-key",
}

View File

@@ -0,0 +1,51 @@
"""Tests for the agent_dvr component."""
from homeassistant.components.agent_dvr.const import DOMAIN, SERVER_URL
from homeassistant.const import CONF_HOST, CONF_PORT, CONTENT_TYPE_JSON
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry, load_fixture
from tests.test_util.aiohttp import AiohttpClientMocker
CONF_DATA = {
CONF_HOST: "example.local",
CONF_PORT: 8090,
SERVER_URL: "http://example.local:8090/",
}
def create_entry(hass: HomeAssistant):
"""Add config entry in Home Assistant."""
entry = MockConfigEntry(
domain=DOMAIN,
unique_id="c0715bba-c2d0-48ef-9e3e-bc81c9ea4447",
data=CONF_DATA,
)
entry.add_to_hass(hass)
return entry
async def init_integration(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
skip_setup: bool = False,
) -> MockConfigEntry:
"""Set up the Agent DVR integration in Home Assistant."""
aioclient_mock.get(
"http://example.local:8090/command.cgi?cmd=getStatus",
text=load_fixture("agent_dvr/status.json"),
headers={"Content-Type": CONTENT_TYPE_JSON},
)
aioclient_mock.get(
"http://example.local:8090/command.cgi?cmd=getObjects",
text=load_fixture("agent_dvr/objects.json"),
headers={"Content-Type": CONTENT_TYPE_JSON},
)
entry = create_entry(hass)
if not skip_setup:
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
return entry

View File

@@ -0,0 +1,15 @@
"""Test fixtures for Agent DVR."""
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.agent_dvr.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry

View File

@@ -0,0 +1,43 @@
{
"settings": {
"canUpdate": true,
"supportsPlugins": true,
"isArmed": true,
"background": "255,255,255"
},
"directories": [
{
"ID": 0,
"dir": "D:\\Projects\\agent-service\\AgentService\\Media\\WebServerRoot\\Media\\"
}
],
"locations": [],
"objectList": [],
"profiles": [
{ "name": "Home", "active": true, "id": 0 },
{ "name": "Away", "active": false, "id": 1 },
{ "name": "Night", "active": false, "id": 2 }
],
"views": [
{
"name": "0",
"mode": "column",
"objects": [],
"maxWidth": 1266,
"maxHeight": 1222,
"backColor": "#222222",
"id": 1,
"typeID": 2,
"focused": false
},
{ "name": "1", "mode": "grid", "objects": [] },
{ "name": "2", "mode": "grid", "objects": [] },
{ "name": "3", "mode": "grid", "objects": [] },
{ "name": "4", "mode": "grid", "objects": [] },
{ "name": "5", "mode": "grid", "objects": [] },
{ "name": "6", "mode": "grid", "objects": [] },
{ "name": "7", "mode": "grid", "objects": [] },
{ "name": "8", "mode": "grid", "objects": [] }
],
"rtmpStreaming": false
}

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