mirror of
https://github.com/home-assistant/core.git
synced 2026-05-28 19:53:18 +02:00
Compare commits
29 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ef1bbc4e0b | |||
| 849cd14233 | |||
| 4668800cd3 | |||
| 5f495d725b | |||
| 9e1741067a | |||
| a1da79314a | |||
| 6e1c6393aa | |||
| 4fe38d3f51 | |||
| c07fed05df | |||
| 13ef737873 | |||
| 0a1510135c | |||
| 6f6b7888cd | |||
| b9173e36fb | |||
| a65ca9c86b | |||
| fc12d6fbb6 | |||
| 2a6b686254 | |||
| 4d841e4d84 | |||
| df08e9f311 | |||
| d53e40eea8 | |||
| 0b261b7198 | |||
| 3a9f32de25 | |||
| b5e54583c7 | |||
| 85ea7c1176 | |||
| 713f520bc8 | |||
| e4bb5a9395 | |||
| 936b2fe933 | |||
| c6c6f08885 | |||
| c621721851 | |||
| 5bb6b20641 |
@@ -24,6 +24,7 @@ The following platforms have extra guidelines:
|
||||
## Entity platforms
|
||||
|
||||
- Ensure `async_added_to_hass()` and `async_will_remove_from_hass()` have symmetrical behavior. For example, if a subscription is created in `async_added_to_hass()`, it should be unsubscribed in `async_will_remove_from_hass()`. Also, if something is torn down in `async_will_remove_from_hass()`, it should be set up in `async_added_to_hass()`.
|
||||
- Entity base class (e.g. `SensorEntity`, `TrackerEntity`) provide a stable API for child classes to inherit from. Do not suggest redeclaring or duplicating attributes, properties, or methods the base class already provides, and do not add guards against the parent's behavior changing — rely on the base class instead.
|
||||
|
||||
## Integration Quality Scale
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ The following platforms have extra guidelines:
|
||||
## Entity platforms
|
||||
|
||||
- Ensure `async_added_to_hass()` and `async_will_remove_from_hass()` have symmetrical behavior. For example, if a subscription is created in `async_added_to_hass()`, it should be unsubscribed in `async_will_remove_from_hass()`. Also, if something is torn down in `async_will_remove_from_hass()`, it should be set up in `async_added_to_hass()`.
|
||||
- Entity base class (e.g. `SensorEntity`, `TrackerEntity`) provide a stable API for child classes to inherit from. Do not suggest redeclaring or duplicating attributes, properties, or methods the base class already provides, and do not add guards against the parent's behavior changing — rely on the base class instead.
|
||||
|
||||
## Integration Quality Scale
|
||||
|
||||
|
||||
@@ -530,7 +530,7 @@ jobs:
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build Docker image
|
||||
uses: docker/build-push-action@bcafcacb16a39f128d818304e6c9c0c18556b85f # v7.1.0
|
||||
uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7.2.0
|
||||
with:
|
||||
context: . # So action will not pull the repository again
|
||||
file: ./script/hassfest/docker/Dockerfile
|
||||
@@ -543,7 +543,7 @@ jobs:
|
||||
- name: Push Docker image
|
||||
if: needs.init.outputs.channel != 'dev' && needs.init.outputs.publish == 'true'
|
||||
id: push
|
||||
uses: docker/build-push-action@bcafcacb16a39f128d818304e6c9c0c18556b85f # v7.1.0
|
||||
uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7.2.0
|
||||
with:
|
||||
context: . # So action will not pull the repository again
|
||||
file: ./script/hassfest/docker/Dockerfile
|
||||
|
||||
+7
-7
@@ -36,7 +36,7 @@
|
||||
# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
# - actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
# - actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
# - github/gh-aw-actions/setup@d3abfe96a194bce3a523ed2093ddedd5704cdf62 # v0.74.4
|
||||
# - github/gh-aw-actions/setup@318d7f4901f78b85e25b91709cf0109ac9b425f6 # v0.74.9
|
||||
#
|
||||
# Container images used:
|
||||
# - ghcr.io/github/gh-aw-firewall/agent:0.25.46
|
||||
@@ -90,7 +90,7 @@ jobs:
|
||||
steps:
|
||||
- name: Setup Scripts
|
||||
id: setup
|
||||
uses: github/gh-aw-actions/setup@d3abfe96a194bce3a523ed2093ddedd5704cdf62 # v0.74.4
|
||||
uses: github/gh-aw-actions/setup@318d7f4901f78b85e25b91709cf0109ac9b425f6 # v0.74.9
|
||||
with:
|
||||
destination: ${{ runner.temp }}/gh-aw/actions
|
||||
job-name: ${{ github.job }}
|
||||
@@ -352,7 +352,7 @@ jobs:
|
||||
steps:
|
||||
- name: Setup Scripts
|
||||
id: setup
|
||||
uses: github/gh-aw-actions/setup@d3abfe96a194bce3a523ed2093ddedd5704cdf62 # v0.74.4
|
||||
uses: github/gh-aw-actions/setup@318d7f4901f78b85e25b91709cf0109ac9b425f6 # v0.74.9
|
||||
with:
|
||||
destination: ${{ runner.temp }}/gh-aw/actions
|
||||
job-name: ${{ github.job }}
|
||||
@@ -961,7 +961,7 @@ jobs:
|
||||
steps:
|
||||
- name: Setup Scripts
|
||||
id: setup
|
||||
uses: github/gh-aw-actions/setup@d3abfe96a194bce3a523ed2093ddedd5704cdf62 # v0.74.4
|
||||
uses: github/gh-aw-actions/setup@318d7f4901f78b85e25b91709cf0109ac9b425f6 # v0.74.9
|
||||
with:
|
||||
destination: ${{ runner.temp }}/gh-aw/actions
|
||||
job-name: ${{ github.job }}
|
||||
@@ -1100,7 +1100,7 @@ jobs:
|
||||
steps:
|
||||
- name: Setup Scripts
|
||||
id: setup
|
||||
uses: github/gh-aw-actions/setup@d3abfe96a194bce3a523ed2093ddedd5704cdf62 # v0.74.4
|
||||
uses: github/gh-aw-actions/setup@318d7f4901f78b85e25b91709cf0109ac9b425f6 # v0.74.9
|
||||
with:
|
||||
destination: ${{ runner.temp }}/gh-aw/actions
|
||||
job-name: ${{ github.job }}
|
||||
@@ -1325,7 +1325,7 @@ jobs:
|
||||
steps:
|
||||
- name: Setup Scripts
|
||||
id: setup
|
||||
uses: github/gh-aw-actions/setup@d3abfe96a194bce3a523ed2093ddedd5704cdf62 # v0.74.4
|
||||
uses: github/gh-aw-actions/setup@318d7f4901f78b85e25b91709cf0109ac9b425f6 # v0.74.9
|
||||
with:
|
||||
destination: ${{ runner.temp }}/gh-aw/actions
|
||||
job-name: ${{ github.job }}
|
||||
@@ -1383,7 +1383,7 @@ jobs:
|
||||
steps:
|
||||
- name: Setup Scripts
|
||||
id: setup
|
||||
uses: github/gh-aw-actions/setup@d3abfe96a194bce3a523ed2093ddedd5704cdf62 # v0.74.4
|
||||
uses: github/gh-aw-actions/setup@318d7f4901f78b85e25b91709cf0109ac9b425f6 # v0.74.9
|
||||
with:
|
||||
destination: ${{ runner.temp }}/gh-aw/actions
|
||||
job-name: ${{ github.job }}
|
||||
|
||||
@@ -20,7 +20,7 @@ jobs:
|
||||
issues: write # To lock issues
|
||||
pull-requests: write # To lock pull requests
|
||||
steps:
|
||||
- uses: dessant/lock-threads@7266a7ce5c1df01b1c6db85bf8cd86c737dadbe7 # v6.0.0
|
||||
- uses: dessant/lock-threads@851cffe46851ddd2051ea7147ebdc995113241c3 # v6.0.1
|
||||
with:
|
||||
github-token: ${{ github.token }}
|
||||
issue-inactive-days: "30"
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"lg_netcast",
|
||||
"lg_soundbar",
|
||||
"lg_thinq",
|
||||
"lg_tv_rs232",
|
||||
"webostv"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -5,8 +5,12 @@ from typing import Any
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components import labs, websocket_api
|
||||
from homeassistant.const import EVENT_HOMEASSISTANT_STARTED
|
||||
from homeassistant.core import Event, HomeAssistant, callback
|
||||
from homeassistant.components.hassio import HassioNotReadyError
|
||||
from homeassistant.config_entries import SOURCE_SYSTEM, ConfigEntry
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.exceptions import ConfigEntryNotReady
|
||||
from homeassistant.helpers import discovery_flow
|
||||
from homeassistant.helpers.start import async_at_started
|
||||
from homeassistant.helpers.typing import ConfigType
|
||||
from homeassistant.util.hass_dict import HassKey
|
||||
|
||||
@@ -49,6 +53,7 @@ CONFIG_SCHEMA = vol.Schema(
|
||||
)
|
||||
|
||||
DATA_COMPONENT: HassKey[Analytics] = HassKey(DOMAIN)
|
||||
_DATA_SNAPSHOTS_URL: HassKey[str | None] = HassKey(f"{DOMAIN}_snapshots_url")
|
||||
|
||||
LABS_SNAPSHOT_FEATURE = "snapshots"
|
||||
|
||||
@@ -57,18 +62,39 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
"""Set up the analytics integration."""
|
||||
analytics_config = config.get(DOMAIN, {})
|
||||
|
||||
snapshots_url: str | None = None
|
||||
if CONF_SNAPSHOTS_URL in analytics_config:
|
||||
await labs.async_update_preview_feature(
|
||||
hass, DOMAIN, LABS_SNAPSHOT_FEATURE, enabled=True
|
||||
)
|
||||
snapshots_url = analytics_config[CONF_SNAPSHOTS_URL]
|
||||
else:
|
||||
snapshots_url = None
|
||||
|
||||
hass.data[_DATA_SNAPSHOTS_URL] = snapshots_url
|
||||
|
||||
discovery_flow.async_create_flow(
|
||||
hass, DOMAIN, context={"source": SOURCE_SYSTEM}, data={}
|
||||
)
|
||||
|
||||
websocket_api.async_register_command(hass, websocket_analytics)
|
||||
websocket_api.async_register_command(hass, websocket_analytics_preferences)
|
||||
|
||||
hass.http.register_view(AnalyticsDevicesView)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Set up Analytics from a config entry."""
|
||||
snapshots_url = hass.data[_DATA_SNAPSHOTS_URL]
|
||||
analytics = Analytics(hass, snapshots_url)
|
||||
|
||||
# Load stored data
|
||||
await analytics.load()
|
||||
try:
|
||||
await analytics.load()
|
||||
except HassioNotReadyError as err:
|
||||
raise ConfigEntryNotReady(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="supervisor_not_ready",
|
||||
) from err
|
||||
|
||||
started = False
|
||||
|
||||
@@ -80,8 +106,8 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
if started:
|
||||
await analytics.async_schedule()
|
||||
|
||||
async def start_schedule(_event: Event) -> None:
|
||||
"""Start the send schedule after the started event."""
|
||||
async def start_schedule(hass: HomeAssistant) -> None:
|
||||
"""Start the send schedule once Home Assistant has started."""
|
||||
nonlocal started
|
||||
started = True
|
||||
await analytics.async_schedule()
|
||||
@@ -89,12 +115,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
labs.async_subscribe_preview_feature(
|
||||
hass, DOMAIN, LABS_SNAPSHOT_FEATURE, _async_handle_labs_update
|
||||
)
|
||||
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, start_schedule)
|
||||
|
||||
websocket_api.async_register_command(hass, websocket_analytics)
|
||||
websocket_api.async_register_command(hass, websocket_analytics_preferences)
|
||||
|
||||
hass.http.register_view(AnalyticsDevicesView)
|
||||
async_at_started(hass, start_schedule)
|
||||
|
||||
hass.data[DATA_COMPONENT] = analytics
|
||||
return True
|
||||
@@ -109,7 +130,9 @@ def websocket_analytics(
|
||||
msg: dict[str, Any],
|
||||
) -> None:
|
||||
"""Return analytics preferences."""
|
||||
analytics = hass.data[DATA_COMPONENT]
|
||||
if (analytics := hass.data.get(DATA_COMPONENT)) is None:
|
||||
connection.send_error(msg["id"], websocket_api.ERR_NOT_FOUND, "Not loaded")
|
||||
return
|
||||
connection.send_result(
|
||||
msg["id"],
|
||||
{ATTR_PREFERENCES: analytics.preferences, ATTR_ONBOARDED: analytics.onboarded},
|
||||
@@ -130,8 +153,10 @@ async def websocket_analytics_preferences(
|
||||
msg: dict[str, Any],
|
||||
) -> None:
|
||||
"""Update analytics preferences."""
|
||||
if (analytics := hass.data.get(DATA_COMPONENT)) is None:
|
||||
connection.send_error(msg["id"], websocket_api.ERR_NOT_FOUND, "Not loaded")
|
||||
return
|
||||
preferences = msg[ATTR_PREFERENCES]
|
||||
analytics = hass.data[DATA_COMPONENT]
|
||||
|
||||
await analytics.save_preferences(preferences)
|
||||
await analytics.async_schedule()
|
||||
|
||||
@@ -299,12 +299,8 @@ class Analytics:
|
||||
self._data = AnalyticsData.from_dict(stored)
|
||||
|
||||
if self.supervisor and not self.onboarded:
|
||||
# This may raise HassioNotReadyError if Supervisor was unreachable
|
||||
# during setup of the Supervisor integration. That will fail setup
|
||||
# of this integration. However there is no better option at this time
|
||||
# since we need to get the diagnostic setting from Supervisor to correctly
|
||||
# setup this integration and we can't raise ConfigEntryNotReady to
|
||||
# trigger a retry from async_setup.
|
||||
# This may raise HassioNotReadyError if Supervisor was unreachable.
|
||||
# The caller is responsible for handling this and triggering a retry.
|
||||
supervisor_info = hassio.get_supervisor_info(self._hass)
|
||||
|
||||
# User have not configured analytics, get this setting from the supervisor
|
||||
@@ -349,10 +345,10 @@ class Analytics:
|
||||
await self._save()
|
||||
|
||||
if self.supervisor:
|
||||
# get_supervisor_info was called during setup so we can't get here
|
||||
# if it raised. The others may raise HassioNotReadyError if only some
|
||||
# data was successfully fetched from Supervisor
|
||||
supervisor_info = hassio.get_supervisor_info(hass)
|
||||
# Try to pull Supervisor information, but don't fail if some or all
|
||||
# of it is unavailable due to setup failures in the hassio integration.
|
||||
with contextlib.suppress(hassio.HassioNotReadyError):
|
||||
supervisor_info = hassio.get_supervisor_info(hass)
|
||||
with contextlib.suppress(hassio.HassioNotReadyError):
|
||||
operating_system_info = hassio.get_os_info(hass)
|
||||
with contextlib.suppress(hassio.HassioNotReadyError):
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Config flow for Analytics integration."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
|
||||
|
||||
from .const import DOMAIN
|
||||
|
||||
|
||||
class AnalyticsConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
"""Handle a config flow for Analytics."""
|
||||
|
||||
VERSION = 1
|
||||
|
||||
async def async_step_system(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle the initial step."""
|
||||
return self.async_create_entry(title="Analytics", data={})
|
||||
@@ -14,5 +14,6 @@
|
||||
"report_issue_url": "https://github.com/OHF-Device-Database/device-database/issues/new"
|
||||
}
|
||||
},
|
||||
"quality_scale": "internal"
|
||||
"quality_scale": "internal",
|
||||
"single_config_entry": true
|
||||
}
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
{
|
||||
"exceptions": {
|
||||
"supervisor_not_ready": {
|
||||
"message": "Supervisor was not ready during setup, will retry"
|
||||
}
|
||||
},
|
||||
"preview_features": {
|
||||
"snapshots": {
|
||||
"description": "We're creating the [Open Home Foundation Device Database](https://www.home-assistant.io/blog/2026/02/02/about-device-database/): a free, open source community-powered resource to help users find practical information about how smart home devices perform in real installations.\n\nYou can help us build it by opting in to share anonymized data about your devices. This data will only ever include device-specific details (like model or manufacturer) – never personally identifying information (like the names you assign).\n\nFind out how we process your data (should you choose to contribute) in our [Data Use Statement](https://www.openhomefoundation.org/device-database-data-use-statement).",
|
||||
|
||||
@@ -92,7 +92,7 @@ class BroadlinkRadioFrequency(BroadlinkEntity, RadioFrequencyTransmitterEntity):
|
||||
"""Representation of a Broadlink RF transmitter."""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
_attr_name = None
|
||||
_attr_translation_key = "rf_transmitter"
|
||||
|
||||
def __init__(self, device: BroadlinkDevice) -> None:
|
||||
"""Initialize the entity."""
|
||||
|
||||
@@ -54,6 +54,11 @@
|
||||
"name": "IR emitter"
|
||||
}
|
||||
},
|
||||
"radio_frequency": {
|
||||
"rf_transmitter": {
|
||||
"name": "RF transmitter"
|
||||
}
|
||||
},
|
||||
"select": {
|
||||
"day_of_week": {
|
||||
"name": "Day of week",
|
||||
|
||||
@@ -12,13 +12,19 @@ from homeassistant.const import (
|
||||
CONF_DOMAIN,
|
||||
CONF_ENTITY_ID,
|
||||
CONF_EVENT,
|
||||
CONF_OPTIONS,
|
||||
CONF_PLATFORM,
|
||||
CONF_TYPE,
|
||||
CONF_ZONE,
|
||||
)
|
||||
from homeassistant.core import CALLBACK_TYPE, HomeAssistant
|
||||
from homeassistant.helpers import config_validation as cv, entity_registry as er
|
||||
from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo
|
||||
from homeassistant.helpers.trigger import (
|
||||
TriggerActionType,
|
||||
TriggerInfo,
|
||||
# protected, but only used for legacy triggers
|
||||
_async_attach_trigger_cls,
|
||||
)
|
||||
from homeassistant.helpers.typing import ConfigType
|
||||
|
||||
from .const import DOMAIN
|
||||
@@ -79,16 +85,18 @@ async def async_attach_trigger(
|
||||
event = zone.EVENT_ENTER
|
||||
else:
|
||||
event = zone.EVENT_LEAVE
|
||||
|
||||
zone_config = {
|
||||
CONF_PLATFORM: ZONE_DOMAIN,
|
||||
CONF_ENTITY_ID: config[CONF_ENTITY_ID],
|
||||
CONF_ZONE: config[CONF_ZONE],
|
||||
CONF_EVENT: event,
|
||||
}
|
||||
zone_config = await zone.async_validate_trigger_config(hass, zone_config)
|
||||
return await zone.async_attach_trigger(
|
||||
hass, zone_config, action, trigger_info, platform_type="device"
|
||||
zone_config = await zone.LegacyZoneTrigger.async_validate_config(
|
||||
hass,
|
||||
{
|
||||
CONF_OPTIONS: {
|
||||
CONF_ENTITY_ID: [config[CONF_ENTITY_ID]],
|
||||
CONF_ZONE: config[CONF_ZONE],
|
||||
CONF_EVENT: event,
|
||||
}
|
||||
},
|
||||
)
|
||||
return await _async_attach_trigger_cls(
|
||||
hass, zone.LegacyZoneTrigger, "device", zone_config, action, trigger_info
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -86,7 +86,6 @@ class DucoCoordinator(DataUpdateCoordinator[DucoData]):
|
||||
"""Fetch node data from the Duco box."""
|
||||
try:
|
||||
nodes = await self.client.async_get_nodes()
|
||||
lan_info = await self.client.async_get_lan_info()
|
||||
except DucoConnectionError as err:
|
||||
raise UpdateFailed(
|
||||
translation_domain=DOMAIN,
|
||||
@@ -100,7 +99,18 @@ class DucoCoordinator(DataUpdateCoordinator[DucoData]):
|
||||
translation_placeholders={"error": repr(err)},
|
||||
) from err
|
||||
|
||||
# LAN info only backs the diagnostic RSSI sensor, so failures on this
|
||||
# supplemental endpoint, including connection failures, should not make
|
||||
# the primary node entities unavailable.
|
||||
rssi_wifi = self.data.rssi_wifi if self.data else None
|
||||
try:
|
||||
lan_info = await self.client.async_get_lan_info()
|
||||
except DucoError as err:
|
||||
_LOGGER.debug("Could not fetch Duco LAN info", exc_info=err)
|
||||
else:
|
||||
rssi_wifi = lan_info.rssi_wifi
|
||||
|
||||
return DucoData(
|
||||
nodes={node.node_id: node for node in nodes},
|
||||
rssi_wifi=lan_info.rssi_wifi,
|
||||
rssi_wifi=rssi_wifi,
|
||||
)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
|
||||
from env_canada import ECAirQuality, ECRadar, ECWeather
|
||||
from env_canada import ECAirQuality, ECMap, ECWeather
|
||||
|
||||
from homeassistant.const import CONF_LANGUAGE, CONF_LATITUDE, CONF_LONGITUDE, Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
@@ -43,7 +43,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ECConfigEntry) ->
|
||||
errors = errors + 1
|
||||
_LOGGER.warning("Unable to retrieve Environment Canada weather")
|
||||
|
||||
radar_data = ECRadar(coordinates=(lat, lon))
|
||||
radar_data = ECMap(coordinates=(lat, lon), layer="precip_type", legend=False)
|
||||
radar_coordinator = ECDataUpdateCoordinator(
|
||||
hass, config_entry, radar_data, "radar", DEFAULT_RADAR_UPDATE_INTERVAL
|
||||
)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Support for the Environment Canada radar imagery."""
|
||||
|
||||
from env_canada import ECRadar
|
||||
from env_canada import ECMap
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.camera import Camera
|
||||
@@ -11,13 +11,20 @@ from homeassistant.helpers.entity_platform import (
|
||||
)
|
||||
from homeassistant.helpers.typing import VolDictType
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from .const import ATTR_OBSERVATION_TIME
|
||||
from .coordinator import ECConfigEntry, ECDataUpdateCoordinator
|
||||
|
||||
SERVICE_SET_RADAR_TYPE = "set_radar_type"
|
||||
SET_RADAR_TYPE_SCHEMA: VolDictType = {
|
||||
vol.Required("radar_type"): vol.In(["Auto", "Rain", "Snow"]),
|
||||
vol.Required("radar_type"): vol.In(["Auto", "Rain", "Snow", "Precipitation type"]),
|
||||
}
|
||||
|
||||
_RADAR_TYPE_TO_LAYER: dict[str, str] = {
|
||||
"Rain": "rain",
|
||||
"Snow": "snow",
|
||||
"Precipitation type": "precip_type",
|
||||
}
|
||||
|
||||
|
||||
@@ -38,13 +45,13 @@ async def async_setup_entry(
|
||||
)
|
||||
|
||||
|
||||
class ECCameraEntity(CoordinatorEntity[ECDataUpdateCoordinator[ECRadar]], Camera):
|
||||
class ECCameraEntity(CoordinatorEntity[ECDataUpdateCoordinator[ECMap]], Camera):
|
||||
"""Implementation of an Environment Canada radar camera."""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
_attr_translation_key = "radar"
|
||||
|
||||
def __init__(self, coordinator: ECDataUpdateCoordinator[ECRadar]) -> None:
|
||||
def __init__(self, coordinator: ECDataUpdateCoordinator[ECMap]) -> None:
|
||||
"""Initialize the camera."""
|
||||
super().__init__(coordinator)
|
||||
Camera.__init__(self)
|
||||
@@ -76,6 +83,13 @@ class ECCameraEntity(CoordinatorEntity[ECDataUpdateCoordinator[ECRadar]], Camera
|
||||
|
||||
async def async_set_radar_type(self, radar_type: str) -> None:
|
||||
"""Set the type of radar to retrieve."""
|
||||
if radar_type == "Auto":
|
||||
# Choose rain for months April through October, snow otherwise
|
||||
layer = "rain" if dt_util.now().month in range(4, 11) else "snow"
|
||||
else:
|
||||
layer = _RADAR_TYPE_TO_LAYER[radar_type]
|
||||
|
||||
# Apply new layer and clear cache to force refresh
|
||||
self.radar_object.layer = layer
|
||||
self.radar_object.clear_cache()
|
||||
self.radar_object.precip_type = radar_type.lower()
|
||||
await self.radar_object.update()
|
||||
await self.coordinator.async_request_refresh()
|
||||
|
||||
@@ -5,7 +5,7 @@ from datetime import timedelta
|
||||
import logging
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
from env_canada import ECAirQuality, ECRadar, ECWeather, ECWeatherUpdateFailed, ec_exc
|
||||
from env_canada import ECAirQuality, ECMap, ECWeather, ECWeatherUpdateFailed, ec_exc
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
@@ -17,7 +17,7 @@ from .const import DOMAIN
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
type ECConfigEntry = ConfigEntry[ECRuntimeData]
|
||||
type ECDataType = ECAirQuality | ECRadar | ECWeather
|
||||
type ECDataType = ECAirQuality | ECMap | ECWeather
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -25,7 +25,7 @@ class ECRuntimeData:
|
||||
"""Class to hold EC runtime data."""
|
||||
|
||||
aqhi_coordinator: ECDataUpdateCoordinator[ECAirQuality]
|
||||
radar_coordinator: ECDataUpdateCoordinator[ECRadar]
|
||||
radar_coordinator: ECDataUpdateCoordinator[ECMap]
|
||||
weather_coordinator: ECDataUpdateCoordinator[ECWeather]
|
||||
|
||||
|
||||
|
||||
@@ -12,10 +12,11 @@ set_radar_type:
|
||||
fields:
|
||||
radar_type:
|
||||
required: true
|
||||
example: Snow
|
||||
example: Rain
|
||||
selector:
|
||||
select:
|
||||
options:
|
||||
- "Auto"
|
||||
- "Rain"
|
||||
- "Snow"
|
||||
- "Precipitation type"
|
||||
|
||||
@@ -199,6 +199,7 @@ DEVICE_CLASS_TO_GOOGLE_TYPES = {
|
||||
(media_player.DOMAIN, media_player.MediaPlayerDeviceClass.RECEIVER): TYPE_RECEIVER,
|
||||
(media_player.DOMAIN, media_player.MediaPlayerDeviceClass.SPEAKER): TYPE_SPEAKER,
|
||||
(media_player.DOMAIN, media_player.MediaPlayerDeviceClass.TV): TYPE_TV,
|
||||
(media_player.DOMAIN, media_player.MediaPlayerDeviceClass.PROJECTOR): TYPE_TV,
|
||||
(sensor.DOMAIN, sensor.SensorDeviceClass.AQI): TYPE_SENSOR,
|
||||
(sensor.DOMAIN, sensor.SensorDeviceClass.HUMIDITY): TYPE_SENSOR,
|
||||
(sensor.DOMAIN, sensor.SensorDeviceClass.TEMPERATURE): TYPE_SENSOR,
|
||||
|
||||
@@ -2728,7 +2728,11 @@ class ChannelTrait(_Trait):
|
||||
if (
|
||||
domain == media_player.DOMAIN
|
||||
and (features & MediaPlayerEntityFeature.PLAY_MEDIA)
|
||||
and device_class == media_player.MediaPlayerDeviceClass.TV
|
||||
and device_class
|
||||
in (
|
||||
media_player.MediaPlayerDeviceClass.TV,
|
||||
media_player.MediaPlayerDeviceClass.PROJECTOR,
|
||||
)
|
||||
):
|
||||
return True
|
||||
|
||||
|
||||
@@ -202,7 +202,10 @@ def get_accessory( # noqa: C901
|
||||
|
||||
if device_class == MediaPlayerDeviceClass.RECEIVER:
|
||||
a_type = "ReceiverMediaPlayer"
|
||||
elif device_class == MediaPlayerDeviceClass.TV:
|
||||
elif device_class in (
|
||||
MediaPlayerDeviceClass.TV,
|
||||
MediaPlayerDeviceClass.PROJECTOR,
|
||||
):
|
||||
a_type = "TelevisionMediaPlayer"
|
||||
elif validate_media_player_features(state, feature_list):
|
||||
a_type = "MediaPlayer"
|
||||
|
||||
@@ -695,7 +695,11 @@ def state_needs_accessory_mode(state: State) -> bool:
|
||||
return (
|
||||
state.domain == MEDIA_PLAYER_DOMAIN
|
||||
and state.attributes.get(ATTR_DEVICE_CLASS)
|
||||
in (MediaPlayerDeviceClass.TV, MediaPlayerDeviceClass.RECEIVER)
|
||||
in (
|
||||
MediaPlayerDeviceClass.TV,
|
||||
MediaPlayerDeviceClass.RECEIVER,
|
||||
MediaPlayerDeviceClass.PROJECTOR,
|
||||
)
|
||||
) or (
|
||||
state.domain == REMOTE_DOMAIN
|
||||
and state.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
|
||||
|
||||
@@ -178,17 +178,21 @@ class HueLight(HueBaseEntity, LightEntity):
|
||||
@property
|
||||
def max_color_temp_mireds(self) -> int:
|
||||
"""Return the warmest color_temp in mireds that this light supports."""
|
||||
if color_temp := self.resource.color_temperature:
|
||||
return color_temp.mirek_schema.mirek_maximum
|
||||
# return a fallback value if the light doesn't provide limits
|
||||
if (color_temp := self.resource.color_temperature) and (
|
||||
mirek_max := color_temp.mirek_schema.mirek_maximum
|
||||
):
|
||||
return mirek_max
|
||||
# return a fallback value if the light doesn't provide valid limits
|
||||
return FALLBACK_MAX_MIREDS
|
||||
|
||||
@property
|
||||
def min_color_temp_mireds(self) -> int:
|
||||
"""Return the coldest color_temp in mireds that this light supports."""
|
||||
if color_temp := self.resource.color_temperature:
|
||||
return color_temp.mirek_schema.mirek_minimum
|
||||
# return a fallback value if the light doesn't provide limits
|
||||
if (color_temp := self.resource.color_temperature) and (
|
||||
mirek_min := color_temp.mirek_schema.mirek_minimum
|
||||
):
|
||||
return mirek_min
|
||||
# return a fallback value if the light doesn't provide valid limits
|
||||
return FALLBACK_MIN_MIREDS
|
||||
|
||||
@property
|
||||
|
||||
@@ -94,7 +94,7 @@ async def async_setup_entry(
|
||||
async_add_entities(device.zones.values())
|
||||
|
||||
# create any components not yet created
|
||||
for controller in disco.pi_disco.controllers.values():
|
||||
for controller in (await disco.pi_disco.fetch_controllers()).values():
|
||||
init_controller(controller)
|
||||
|
||||
# connect to register any further components
|
||||
|
||||
@@ -29,12 +29,13 @@ async def _async_has_devices(hass: HomeAssistant) -> bool:
|
||||
async with asyncio.timeout(TIMEOUT_DISCOVERY):
|
||||
await controller_ready.wait()
|
||||
|
||||
if not disco.pi_disco.controllers:
|
||||
controllers = await disco.pi_disco.fetch_controllers()
|
||||
if not controllers:
|
||||
await async_stop_discovery_service(hass)
|
||||
_LOGGER.debug("No controllers found")
|
||||
return False
|
||||
|
||||
_LOGGER.debug("Controllers %s", disco.pi_disco.controllers)
|
||||
_LOGGER.debug("Controllers %s", controllers)
|
||||
return True
|
||||
|
||||
|
||||
|
||||
@@ -53,9 +53,7 @@ _LOGGER = logging.getLogger(__name__)
|
||||
async def async_get_media_source(hass: HomeAssistant) -> MediaSource:
|
||||
"""Set up Jellyfin media source."""
|
||||
# Currently only a single Jellyfin server is supported
|
||||
if not (entries := hass.config_entries.async_loaded_entries(DOMAIN)):
|
||||
raise BrowseError("Jellyfin integration not loaded")
|
||||
entry: JellyfinConfigEntry = entries[0]
|
||||
entry: JellyfinConfigEntry = hass.config_entries.async_entries(DOMAIN)[0]
|
||||
coordinator = entry.runtime_data
|
||||
|
||||
return JellyfinSource(hass, coordinator.api_client, entry)
|
||||
|
||||
@@ -105,10 +105,7 @@ class ThinQEntity(CoordinatorEntity[DeviceDataUpdateCoordinator]):
|
||||
except ThinQAPIException as exc:
|
||||
if on_fail_method:
|
||||
on_fail_method()
|
||||
# pylint: disable-next=home-assistant-exception-message-with-translation
|
||||
raise ServiceValidationError(
|
||||
exc.message, translation_domain=DOMAIN, translation_key=exc.code
|
||||
) from exc
|
||||
raise ServiceValidationError(exc.message) from exc
|
||||
except ValueError as exc:
|
||||
if on_fail_method:
|
||||
on_fail_method()
|
||||
|
||||
@@ -108,5 +108,7 @@ def create_matter_ble_proxy(hass: HomeAssistant, ws_url: str) -> MatterBleProxy:
|
||||
ws_url=ws_url,
|
||||
scan_source=HaBluetoothScanSource(hass),
|
||||
device_resolver=HaBluetoothDeviceResolver(hass),
|
||||
task_factory=hass.async_create_task,
|
||||
task_factory=lambda coro: hass.async_create_background_task(
|
||||
coro, name="matter_ble_proxy"
|
||||
),
|
||||
)
|
||||
|
||||
@@ -155,6 +155,7 @@ class MediaPlayerDeviceClass(StrEnum):
|
||||
TV = "tv"
|
||||
SPEAKER = "speaker"
|
||||
RECEIVER = "receiver"
|
||||
PROJECTOR = "projector"
|
||||
|
||||
|
||||
DEVICE_CLASSES_SCHEMA = vol.All(vol.Lower, vol.Coerce(MediaPlayerDeviceClass))
|
||||
|
||||
@@ -34,6 +34,12 @@
|
||||
"playing": "mdi:cast-connected"
|
||||
}
|
||||
},
|
||||
"projector": {
|
||||
"default": "mdi:projector",
|
||||
"state": {
|
||||
"off": "mdi:projector-off"
|
||||
}
|
||||
},
|
||||
"receiver": {
|
||||
"default": "mdi:audio-video",
|
||||
"state": {
|
||||
|
||||
@@ -261,6 +261,9 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"projector": {
|
||||
"name": "Projector"
|
||||
},
|
||||
"receiver": {
|
||||
"name": "Receiver"
|
||||
},
|
||||
|
||||
@@ -4,7 +4,7 @@ from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
PLATFORMS = [Platform.MEDIA_PLAYER]
|
||||
PLATFORMS = [Platform.BUTTON, Platform.MEDIA_PLAYER]
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Button platform for Samsung IR integration."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from infrared_protocols.codes.samsung.tv import SamsungTVCode
|
||||
|
||||
from homeassistant.components.button import ButtonEntity, ButtonEntityDescription
|
||||
from homeassistant.components.infrared import InfraredEmitterConsumerEntity
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
|
||||
from .const import CONF_DEVICE_TYPE, CONF_INFRARED_EMITTER_ENTITY_ID, SamsungDeviceType
|
||||
from .entity import SamsungIrEntity
|
||||
|
||||
PARALLEL_UPDATES = 1
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class SamsungIrButtonEntityDescription(ButtonEntityDescription):
|
||||
"""Describes Samsung IR button entity."""
|
||||
|
||||
command_code: SamsungTVCode
|
||||
|
||||
|
||||
TV_BUTTON_DESCRIPTIONS: tuple[SamsungIrButtonEntityDescription, ...] = (
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="power", translation_key="power", command_code=SamsungTVCode.POWER
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="source", translation_key="source", command_code=SamsungTVCode.SOURCE
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="settings", translation_key="settings", command_code=SamsungTVCode.SETTINGS
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="info", translation_key="info", command_code=SamsungTVCode.INFO
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="exit", translation_key="exit", command_code=SamsungTVCode.EXIT
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="return", translation_key="return", command_code=SamsungTVCode.RETURN
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="home", translation_key="home", command_code=SamsungTVCode.HOME
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="red", translation_key="red", command_code=SamsungTVCode.RED
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="green", translation_key="green", command_code=SamsungTVCode.GREEN
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="yellow", translation_key="yellow", command_code=SamsungTVCode.YELLOW
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="blue", translation_key="blue", command_code=SamsungTVCode.BLUE
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="up", translation_key="up", command_code=SamsungTVCode.NAV_UP
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="down", translation_key="down", command_code=SamsungTVCode.NAV_DOWN
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="left", translation_key="left", command_code=SamsungTVCode.NAV_LEFT
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="right", translation_key="right", command_code=SamsungTVCode.NAV_RIGHT
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="ok", translation_key="ok", command_code=SamsungTVCode.OK
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="previous_channel",
|
||||
translation_key="previous_channel",
|
||||
command_code=SamsungTVCode.PREVIOUS_CHANNEL,
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="num_0", translation_key="num_0", command_code=SamsungTVCode.NUM_0
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="num_1", translation_key="num_1", command_code=SamsungTVCode.NUM_1
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="num_2", translation_key="num_2", command_code=SamsungTVCode.NUM_2
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="num_3", translation_key="num_3", command_code=SamsungTVCode.NUM_3
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="num_4", translation_key="num_4", command_code=SamsungTVCode.NUM_4
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="num_5", translation_key="num_5", command_code=SamsungTVCode.NUM_5
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="num_6", translation_key="num_6", command_code=SamsungTVCode.NUM_6
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="num_7", translation_key="num_7", command_code=SamsungTVCode.NUM_7
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="num_8", translation_key="num_8", command_code=SamsungTVCode.NUM_8
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="num_9", translation_key="num_9", command_code=SamsungTVCode.NUM_9
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="fast_forward",
|
||||
translation_key="fast_forward",
|
||||
command_code=SamsungTVCode.FAST_FORWARD,
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="rewind", translation_key="rewind", command_code=SamsungTVCode.REWIND
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="record", translation_key="record", command_code=SamsungTVCode.RECORD
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="tools", translation_key="tools", command_code=SamsungTVCode.TOOLS
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="browser", translation_key="browser", command_code=SamsungTVCode.BROWSER
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="ad_subtitle",
|
||||
translation_key="ad_subtitle",
|
||||
command_code=SamsungTVCode.AD_SUBTITLE,
|
||||
),
|
||||
SamsungIrButtonEntityDescription(
|
||||
key="e_manual",
|
||||
translation_key="e_manual",
|
||||
command_code=SamsungTVCode.E_MANUAL,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: ConfigEntry,
|
||||
async_add_entities: AddConfigEntryEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up Samsung IR buttons from config entry."""
|
||||
infrared_emitter_entity_id = entry.data[CONF_INFRARED_EMITTER_ENTITY_ID]
|
||||
device_type = entry.data[CONF_DEVICE_TYPE]
|
||||
if device_type != SamsungDeviceType.TV:
|
||||
return
|
||||
async_add_entities(
|
||||
[
|
||||
SamsungIrButton(entry, infrared_emitter_entity_id, description)
|
||||
for description in TV_BUTTON_DESCRIPTIONS
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
class SamsungIrButton(SamsungIrEntity, InfraredEmitterConsumerEntity, ButtonEntity):
|
||||
"""Samsung IR button entity."""
|
||||
|
||||
entity_description: SamsungIrButtonEntityDescription
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
entry: ConfigEntry,
|
||||
infrared_emitter_entity_id: str,
|
||||
description: SamsungIrButtonEntityDescription,
|
||||
) -> None:
|
||||
"""Initialize Samsung IR button."""
|
||||
super().__init__(entry, unique_id_suffix=description.key)
|
||||
self._infrared_emitter_entity_id = infrared_emitter_entity_id
|
||||
self.entity_description = description
|
||||
|
||||
async def async_press(self) -> None:
|
||||
"""Press the button."""
|
||||
await self._send_command(self.entity_description.command_code.to_command())
|
||||
@@ -19,6 +19,112 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"entity": {
|
||||
"button": {
|
||||
"ad_subtitle": {
|
||||
"name": "AD/Subtitle"
|
||||
},
|
||||
"blue": {
|
||||
"name": "Blue"
|
||||
},
|
||||
"browser": {
|
||||
"name": "Browser"
|
||||
},
|
||||
"down": {
|
||||
"name": "[%key:common::entity::button::down::name%]"
|
||||
},
|
||||
"e_manual": {
|
||||
"name": "E-Manual"
|
||||
},
|
||||
"exit": {
|
||||
"name": "[%key:common::entity::button::exit::name%]"
|
||||
},
|
||||
"fast_forward": {
|
||||
"name": "Fast forward"
|
||||
},
|
||||
"green": {
|
||||
"name": "Green"
|
||||
},
|
||||
"home": {
|
||||
"name": "[%key:common::entity::button::home::name%]"
|
||||
},
|
||||
"info": {
|
||||
"name": "[%key:common::entity::button::info::name%]"
|
||||
},
|
||||
"left": {
|
||||
"name": "[%key:common::entity::button::left::name%]"
|
||||
},
|
||||
"num_0": {
|
||||
"name": "[%key:common::entity::button::num_0::name%]"
|
||||
},
|
||||
"num_1": {
|
||||
"name": "[%key:common::entity::button::num_1::name%]"
|
||||
},
|
||||
"num_2": {
|
||||
"name": "[%key:common::entity::button::num_2::name%]"
|
||||
},
|
||||
"num_3": {
|
||||
"name": "[%key:common::entity::button::num_3::name%]"
|
||||
},
|
||||
"num_4": {
|
||||
"name": "[%key:common::entity::button::num_4::name%]"
|
||||
},
|
||||
"num_5": {
|
||||
"name": "[%key:common::entity::button::num_5::name%]"
|
||||
},
|
||||
"num_6": {
|
||||
"name": "[%key:common::entity::button::num_6::name%]"
|
||||
},
|
||||
"num_7": {
|
||||
"name": "[%key:common::entity::button::num_7::name%]"
|
||||
},
|
||||
"num_8": {
|
||||
"name": "[%key:common::entity::button::num_8::name%]"
|
||||
},
|
||||
"num_9": {
|
||||
"name": "[%key:common::entity::button::num_9::name%]"
|
||||
},
|
||||
"ok": {
|
||||
"name": "[%key:common::entity::button::ok::name%]"
|
||||
},
|
||||
"power": {
|
||||
"name": "[%key:common::entity::button::power::name%]"
|
||||
},
|
||||
"previous_channel": {
|
||||
"name": "Previous channel"
|
||||
},
|
||||
"record": {
|
||||
"name": "Record"
|
||||
},
|
||||
"red": {
|
||||
"name": "Red"
|
||||
},
|
||||
"return": {
|
||||
"name": "Return"
|
||||
},
|
||||
"rewind": {
|
||||
"name": "Rewind"
|
||||
},
|
||||
"right": {
|
||||
"name": "[%key:common::entity::button::right::name%]"
|
||||
},
|
||||
"settings": {
|
||||
"name": "Settings"
|
||||
},
|
||||
"source": {
|
||||
"name": "Source"
|
||||
},
|
||||
"tools": {
|
||||
"name": "Tools"
|
||||
},
|
||||
"up": {
|
||||
"name": "[%key:common::entity::button::up::name%]"
|
||||
},
|
||||
"yellow": {
|
||||
"name": "Yellow"
|
||||
}
|
||||
}
|
||||
},
|
||||
"selector": {
|
||||
"device_type": {
|
||||
"options": {
|
||||
|
||||
@@ -38,7 +38,7 @@
|
||||
"requirements": [
|
||||
"getmac==0.9.5",
|
||||
"samsungctl[websocket]==0.7.1",
|
||||
"samsungtvws[async,encrypted]==2.7.2",
|
||||
"samsungtvws[async,encrypted]==3.0.5",
|
||||
"wakeonlan==3.3.0",
|
||||
"async-upnp-client==0.46.2"
|
||||
],
|
||||
|
||||
@@ -6,6 +6,7 @@ import logging
|
||||
|
||||
from sense_energy import (
|
||||
ASyncSenseable,
|
||||
SenseAPIException,
|
||||
SenseAuthenticationException,
|
||||
SenseMFARequiredException,
|
||||
)
|
||||
@@ -88,6 +89,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: SenseConfigEntry) -> boo
|
||||
) from err
|
||||
except SENSE_WEBSOCKET_EXCEPTIONS as err:
|
||||
raise ConfigEntryNotReady(str(err) or "Error during realtime update") from err
|
||||
except SenseAPIException as err:
|
||||
raise ConfigEntryNotReady(
|
||||
str(err) or "API error retrieving realtime data"
|
||||
) from err
|
||||
|
||||
trends_coordinator = SenseTrendCoordinator(hass, entry, gateway)
|
||||
realtime_coordinator = SenseRealtimeCoordinator(hass, entry, gateway)
|
||||
|
||||
@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING
|
||||
|
||||
from sense_energy import (
|
||||
ASyncSenseable,
|
||||
SenseAPIException,
|
||||
SenseAuthenticationException,
|
||||
SenseMFARequiredException,
|
||||
)
|
||||
@@ -93,6 +94,8 @@ class SenseRealtimeCoordinator(SenseCoordinator):
|
||||
try:
|
||||
await self._gateway.update_realtime()
|
||||
except SENSE_TIMEOUT_EXCEPTIONS as ex:
|
||||
_LOGGER.error("Timeout retrieving data: %s", ex)
|
||||
raise UpdateFailed(f"Timeout retrieving realtime data: {ex}") from ex
|
||||
except SENSE_WEBSOCKET_EXCEPTIONS as ex:
|
||||
_LOGGER.error("Failed to update data: %s", ex)
|
||||
raise UpdateFailed(f"Failed to update realtime data: {ex}") from ex
|
||||
except SenseAPIException as ex:
|
||||
raise UpdateFailed(f"API error retrieving realtime data: {ex}") from ex
|
||||
|
||||
@@ -72,8 +72,10 @@ async def async_setup_entry(
|
||||
for device in entry_data.devices.values()
|
||||
for component in device.status
|
||||
if (
|
||||
Capability.SWITCH in device.status[MAIN]
|
||||
and any(capability in device.status[MAIN] for capability in CAPABILITIES)
|
||||
Capability.SWITCH in device.status[component]
|
||||
and any(
|
||||
capability in device.status[component] for capability in CAPABILITIES
|
||||
)
|
||||
and Capability.SAMSUNG_CE_LAMP not in device.status[component]
|
||||
)
|
||||
]
|
||||
|
||||
@@ -50,6 +50,7 @@ DEVICE_CLASS_MAP: dict[Category | str, MediaPlayerDeviceClass] = {
|
||||
Category.SPEAKER: MediaPlayerDeviceClass.SPEAKER,
|
||||
Category.TELEVISION: MediaPlayerDeviceClass.TV,
|
||||
Category.RECEIVER: MediaPlayerDeviceClass.RECEIVER,
|
||||
Category.PROJECTOR: MediaPlayerDeviceClass.PROJECTOR,
|
||||
}
|
||||
|
||||
VALUE_TO_STATE = {
|
||||
|
||||
@@ -3,5 +3,13 @@
|
||||
"reload": {
|
||||
"service": "mdi:reload"
|
||||
}
|
||||
},
|
||||
"triggers": {
|
||||
"entered": {
|
||||
"trigger": "mdi:map-marker-plus"
|
||||
},
|
||||
"left": {
|
||||
"trigger": "mdi:map-marker-minus"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,48 @@
|
||||
{
|
||||
"common": {
|
||||
"trigger_behavior_name": "Trigger when",
|
||||
"trigger_for_name": "For at least",
|
||||
"trigger_zone_description": "The zone to trigger on.",
|
||||
"trigger_zone_name": "Zone"
|
||||
},
|
||||
"services": {
|
||||
"reload": {
|
||||
"description": "Reloads zones from the YAML-configuration.",
|
||||
"name": "Reload zones"
|
||||
}
|
||||
},
|
||||
"triggers": {
|
||||
"entered": {
|
||||
"description": "Triggers when one or more persons or device trackers enter a zone.",
|
||||
"fields": {
|
||||
"behavior": {
|
||||
"name": "[%key:component::zone::common::trigger_behavior_name%]"
|
||||
},
|
||||
"for": {
|
||||
"name": "[%key:component::zone::common::trigger_for_name%]"
|
||||
},
|
||||
"zone": {
|
||||
"description": "[%key:component::zone::common::trigger_zone_description%]",
|
||||
"name": "[%key:component::zone::common::trigger_zone_name%]"
|
||||
}
|
||||
},
|
||||
"name": "Entered zone"
|
||||
},
|
||||
"left": {
|
||||
"description": "Triggers when one or more persons or device trackers leave a zone.",
|
||||
"fields": {
|
||||
"behavior": {
|
||||
"name": "[%key:component::zone::common::trigger_behavior_name%]"
|
||||
},
|
||||
"for": {
|
||||
"name": "[%key:component::zone::common::trigger_for_name%]"
|
||||
},
|
||||
"zone": {
|
||||
"description": "[%key:component::zone::common::trigger_zone_description%]",
|
||||
"name": "[%key:component::zone::common::trigger_zone_name%]"
|
||||
}
|
||||
},
|
||||
"name": "Left zone"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,24 @@
|
||||
"""Offer zone automation rules."""
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.device_tracker import ATTR_IN_ZONES
|
||||
from homeassistant.const import (
|
||||
ATTR_FRIENDLY_NAME,
|
||||
CONF_ENTITY_ID,
|
||||
CONF_EVENT,
|
||||
CONF_PLATFORM,
|
||||
CONF_OPTIONS,
|
||||
CONF_ZONE,
|
||||
)
|
||||
from homeassistant.core import (
|
||||
CALLBACK_TYPE,
|
||||
Event,
|
||||
EventStateChangedData,
|
||||
HassJob,
|
||||
HomeAssistant,
|
||||
State,
|
||||
callback,
|
||||
)
|
||||
from homeassistant.helpers import (
|
||||
@@ -24,8 +26,18 @@ from homeassistant.helpers import (
|
||||
entity_registry as er,
|
||||
location,
|
||||
)
|
||||
from homeassistant.helpers.automation import (
|
||||
DomainSpec,
|
||||
move_top_level_schema_fields_to_options,
|
||||
)
|
||||
from homeassistant.helpers.event import async_track_state_change_event
|
||||
from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo
|
||||
from homeassistant.helpers.trigger import (
|
||||
ENTITY_STATE_TRIGGER_SCHEMA_WITH_BEHAVIOR,
|
||||
EntityTriggerBase,
|
||||
Trigger,
|
||||
TriggerActionRunner,
|
||||
TriggerConfig,
|
||||
)
|
||||
from homeassistant.helpers.typing import ConfigType
|
||||
|
||||
from . import condition
|
||||
@@ -38,93 +50,166 @@ _LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_EVENT_DESCRIPTION = {EVENT_ENTER: "entering", EVENT_LEAVE: "leaving"}
|
||||
|
||||
_TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend(
|
||||
_LEGACY_OPTIONS_SCHEMA: dict[vol.Marker, Any] = {
|
||||
vol.Required(CONF_ENTITY_ID): cv.entity_ids_or_uuids,
|
||||
vol.Required(CONF_ZONE): cv.entity_id,
|
||||
vol.Required(CONF_EVENT, default=DEFAULT_EVENT): vol.Any(EVENT_ENTER, EVENT_LEAVE),
|
||||
}
|
||||
|
||||
_LEGACY_TRIGGER_OPTIONS_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Required(CONF_PLATFORM): "zone",
|
||||
vol.Required(CONF_ENTITY_ID): cv.entity_ids_or_uuids,
|
||||
vol.Required(CONF_ZONE): cv.entity_id,
|
||||
vol.Required(CONF_EVENT, default=DEFAULT_EVENT): vol.Any(
|
||||
EVENT_ENTER, EVENT_LEAVE
|
||||
),
|
||||
vol.Required(CONF_OPTIONS): _LEGACY_OPTIONS_SCHEMA,
|
||||
},
|
||||
)
|
||||
|
||||
# New-style zone trigger schema
|
||||
_ZONE_TRIGGER_SCHEMA = ENTITY_STATE_TRIGGER_SCHEMA_WITH_BEHAVIOR.extend(
|
||||
{
|
||||
vol.Required(CONF_OPTIONS): {
|
||||
vol.Required(CONF_ZONE): cv.entity_domain("zone"),
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def async_validate_trigger_config(
|
||||
hass: HomeAssistant, config: ConfigType
|
||||
) -> ConfigType:
|
||||
"""Validate trigger config."""
|
||||
config = _TRIGGER_SCHEMA(config)
|
||||
registry = er.async_get(hass)
|
||||
config[CONF_ENTITY_ID] = er.async_validate_entity_ids(
|
||||
registry, config[CONF_ENTITY_ID]
|
||||
)
|
||||
return config
|
||||
_DOMAIN_SPECS: dict[str, DomainSpec] = {
|
||||
"person": DomainSpec(),
|
||||
"device_tracker": DomainSpec(),
|
||||
}
|
||||
|
||||
|
||||
async def async_attach_trigger(
|
||||
hass: HomeAssistant,
|
||||
config: ConfigType,
|
||||
action: TriggerActionType,
|
||||
trigger_info: TriggerInfo,
|
||||
*,
|
||||
platform_type: str = "zone",
|
||||
) -> CALLBACK_TYPE:
|
||||
"""Listen for state changes based on configuration."""
|
||||
trigger_data = trigger_info["trigger_data"]
|
||||
entity_id: list[str] = config[CONF_ENTITY_ID]
|
||||
zone_entity_id: str = config[CONF_ZONE]
|
||||
event: str = config[CONF_EVENT]
|
||||
job = HassJob(action)
|
||||
class LegacyZoneTrigger(Trigger):
|
||||
"""Legacy zone trigger (platform: zone)."""
|
||||
|
||||
@callback
|
||||
def zone_automation_listener(zone_event: Event[EventStateChangedData]) -> None:
|
||||
"""Listen for state changes and calls action."""
|
||||
entity = zone_event.data["entity_id"]
|
||||
from_s = zone_event.data["old_state"]
|
||||
to_s = zone_event.data["new_state"]
|
||||
@classmethod
|
||||
async def async_validate_complete_config(
|
||||
cls, hass: HomeAssistant, complete_config: ConfigType
|
||||
) -> ConfigType:
|
||||
"""Validate complete config, migrating legacy format to options."""
|
||||
complete_config = move_top_level_schema_fields_to_options(
|
||||
complete_config, _LEGACY_OPTIONS_SCHEMA
|
||||
)
|
||||
return await super().async_validate_complete_config(hass, complete_config)
|
||||
|
||||
if (from_s and not location.has_location(from_s)) or (
|
||||
to_s and not location.has_location(to_s)
|
||||
):
|
||||
return
|
||||
@classmethod
|
||||
async def async_validate_config(
|
||||
cls, hass: HomeAssistant, config: ConfigType
|
||||
) -> ConfigType:
|
||||
"""Validate config."""
|
||||
config = cast(ConfigType, _LEGACY_TRIGGER_OPTIONS_SCHEMA(config))
|
||||
registry = er.async_get(hass)
|
||||
config[CONF_OPTIONS][CONF_ENTITY_ID] = er.async_validate_entity_ids(
|
||||
registry, config[CONF_OPTIONS][CONF_ENTITY_ID]
|
||||
)
|
||||
return config
|
||||
|
||||
if not (zone_state := hass.states.get(zone_entity_id)):
|
||||
_LOGGER.warning(
|
||||
(
|
||||
"Automation '%s' is referencing non-existing zone '%s' in a zone"
|
||||
" trigger"
|
||||
),
|
||||
trigger_info["name"],
|
||||
zone_entity_id,
|
||||
def __init__(self, hass: HomeAssistant, config: TriggerConfig) -> None:
|
||||
"""Initialize trigger."""
|
||||
super().__init__(hass, config)
|
||||
if TYPE_CHECKING:
|
||||
assert config.options is not None
|
||||
self._options = config.options
|
||||
|
||||
async def async_attach_runner(
|
||||
self, run_action: TriggerActionRunner
|
||||
) -> CALLBACK_TYPE:
|
||||
"""Listen for state changes based on configuration."""
|
||||
entity_id: list[str] = self._options[CONF_ENTITY_ID]
|
||||
zone_entity_id: str = self._options[CONF_ZONE]
|
||||
event: str = self._options[CONF_EVENT]
|
||||
|
||||
@callback
|
||||
def zone_automation_listener(zone_event: Event[EventStateChangedData]) -> None:
|
||||
"""Listen for state changes and calls action."""
|
||||
entity = zone_event.data["entity_id"]
|
||||
from_s = zone_event.data["old_state"]
|
||||
to_s = zone_event.data["new_state"]
|
||||
|
||||
if (from_s and not location.has_location(from_s)) or (
|
||||
to_s and not location.has_location(to_s)
|
||||
):
|
||||
return
|
||||
|
||||
if not (zone_state := self._hass.states.get(zone_entity_id)):
|
||||
_LOGGER.warning(
|
||||
"Non-existing zone '%s' in a zone trigger",
|
||||
zone_entity_id,
|
||||
)
|
||||
return
|
||||
|
||||
from_match = (
|
||||
condition.zone(self._hass, zone_state, from_s) if from_s else False
|
||||
)
|
||||
return
|
||||
to_match = condition.zone(self._hass, zone_state, to_s) if to_s else False
|
||||
|
||||
from_match = condition.zone(hass, zone_state, from_s) if from_s else False
|
||||
to_match = condition.zone(hass, zone_state, to_s) if to_s else False
|
||||
|
||||
if (event == EVENT_ENTER and not from_match and to_match) or (
|
||||
event == EVENT_LEAVE and from_match and not to_match
|
||||
):
|
||||
description = (
|
||||
f"{entity} {_EVENT_DESCRIPTION[event]}"
|
||||
f" {zone_state.attributes[ATTR_FRIENDLY_NAME]}"
|
||||
)
|
||||
hass.async_run_hass_job(
|
||||
job,
|
||||
{
|
||||
"trigger": {
|
||||
**trigger_data,
|
||||
"platform": platform_type,
|
||||
if (event == EVENT_ENTER and not from_match and to_match) or (
|
||||
event == EVENT_LEAVE and from_match and not to_match
|
||||
):
|
||||
description = f"{entity} {_EVENT_DESCRIPTION[event]} {zone_state.attributes[ATTR_FRIENDLY_NAME]}"
|
||||
run_action(
|
||||
{
|
||||
"entity_id": entity,
|
||||
"from_state": from_s,
|
||||
"to_state": to_s,
|
||||
"zone": zone_state,
|
||||
"event": event,
|
||||
"description": description,
|
||||
}
|
||||
},
|
||||
to_s.context if to_s else None,
|
||||
)
|
||||
},
|
||||
description,
|
||||
to_s.context if to_s else None,
|
||||
)
|
||||
|
||||
return async_track_state_change_event(hass, entity_id, zone_automation_listener)
|
||||
return async_track_state_change_event(
|
||||
self._hass, entity_id, zone_automation_listener
|
||||
)
|
||||
|
||||
|
||||
class ZoneTriggerBase(EntityTriggerBase):
|
||||
"""Base for zone-based triggers targeting person and device_tracker entities."""
|
||||
|
||||
_domain_specs = _DOMAIN_SPECS
|
||||
_schema = _ZONE_TRIGGER_SCHEMA
|
||||
|
||||
def __init__(self, hass: HomeAssistant, config: TriggerConfig) -> None:
|
||||
"""Initialize the trigger."""
|
||||
super().__init__(hass, config)
|
||||
self._zone: str = self._options[CONF_ZONE]
|
||||
|
||||
def _in_target_zone(self, state: State) -> bool:
|
||||
"""Check if the entity is in the selected zone."""
|
||||
in_zones = state.attributes.get(ATTR_IN_ZONES) or ()
|
||||
return self._zone in in_zones
|
||||
|
||||
|
||||
class EnteredZoneTrigger(ZoneTriggerBase):
|
||||
"""Trigger when an entity enters the selected zone."""
|
||||
|
||||
def is_valid_transition(self, from_state: State, to_state: State) -> bool:
|
||||
"""Check that the entity was not already in the selected zone."""
|
||||
return not self._in_target_zone(from_state)
|
||||
|
||||
def is_valid_state(self, state: State) -> bool:
|
||||
"""Check that the entity is now in the selected zone."""
|
||||
return self._in_target_zone(state)
|
||||
|
||||
|
||||
class LeftZoneTrigger(ZoneTriggerBase):
|
||||
"""Trigger when an entity leaves the selected zone."""
|
||||
|
||||
def is_valid_transition(self, from_state: State, to_state: State) -> bool:
|
||||
"""Check that the entity was previously in the selected zone."""
|
||||
return self._in_target_zone(from_state)
|
||||
|
||||
def is_valid_state(self, state: State) -> bool:
|
||||
"""Check that the entity is no longer in the selected zone."""
|
||||
return not self._in_target_zone(state)
|
||||
|
||||
|
||||
TRIGGERS: dict[str, type[Trigger]] = {
|
||||
"_": LegacyZoneTrigger,
|
||||
"entered": EnteredZoneTrigger,
|
||||
"left": LeftZoneTrigger,
|
||||
}
|
||||
|
||||
|
||||
async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]:
|
||||
"""Return the triggers for zones."""
|
||||
return TRIGGERS
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
.trigger_zone: &trigger_zone
|
||||
target:
|
||||
entity:
|
||||
domain:
|
||||
- person
|
||||
- device_tracker
|
||||
fields:
|
||||
behavior:
|
||||
required: true
|
||||
default: each
|
||||
selector:
|
||||
automation_behavior:
|
||||
mode: trigger
|
||||
for:
|
||||
required: true
|
||||
default: 00:00:00
|
||||
selector:
|
||||
duration:
|
||||
zone:
|
||||
required: true
|
||||
selector:
|
||||
entity:
|
||||
domain: zone
|
||||
|
||||
entered: *trigger_zone
|
||||
left: *trigger_zone
|
||||
@@ -3759,6 +3759,12 @@
|
||||
"iot_class": "cloud_push",
|
||||
"name": "LG ThinQ"
|
||||
},
|
||||
"lg_tv_rs232": {
|
||||
"integration_type": "device",
|
||||
"config_flow": true,
|
||||
"iot_class": "local_polling",
|
||||
"name": "LG TV via Serial"
|
||||
},
|
||||
"webostv": {
|
||||
"integration_type": "device",
|
||||
"config_flow": true,
|
||||
@@ -3767,12 +3773,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"lg_tv_rs232": {
|
||||
"name": "LG TV via Serial",
|
||||
"integration_type": "device",
|
||||
"config_flow": true,
|
||||
"iot_class": "local_polling"
|
||||
},
|
||||
"libre_hardware_monitor": {
|
||||
"name": "Libre Hardware Monitor",
|
||||
"integration_type": "device",
|
||||
|
||||
@@ -31,7 +31,6 @@ from homeassistant.const import (
|
||||
MAX_LENGTH_STATE_DOMAIN,
|
||||
MAX_LENGTH_STATE_ENTITY_ID,
|
||||
STATE_UNAVAILABLE,
|
||||
STATE_UNKNOWN,
|
||||
EntityCategory,
|
||||
Platform,
|
||||
)
|
||||
@@ -1951,9 +1950,10 @@ class EntityRegistry(BaseRegistry):
|
||||
This should only be used when an entity needs to be migrated between
|
||||
integrations.
|
||||
"""
|
||||
if (
|
||||
state := self.hass.states.get(entity_id)
|
||||
) is not None and state.state != STATE_UNKNOWN:
|
||||
# import here to avoid circular import
|
||||
from .entity import entity_sources # noqa: PLC0415
|
||||
|
||||
if entity_id in entity_sources(self.hass):
|
||||
raise ValueError("Only entities that haven't been loaded can be migrated")
|
||||
|
||||
old = self.entities[entity_id]
|
||||
|
||||
@@ -1714,7 +1714,14 @@ def async_extract_entities(trigger_conf: dict) -> list[str]:
|
||||
return [trigger_conf[CONF_OPTIONS][CONF_ENTITY_ID]]
|
||||
|
||||
if trigger_conf[CONF_PLATFORM] == "zone":
|
||||
return trigger_conf[CONF_ENTITY_ID] + [trigger_conf[CONF_ZONE]] # type: ignore[no-any-return]
|
||||
options = trigger_conf[CONF_OPTIONS]
|
||||
return [*options[CONF_ENTITY_ID], options[CONF_ZONE]]
|
||||
|
||||
if trigger_conf[CONF_PLATFORM] in ("zone.entered", "zone.left"):
|
||||
return [
|
||||
*async_extract_targets(trigger_conf, CONF_ENTITY_ID),
|
||||
trigger_conf[CONF_OPTIONS][CONF_ZONE],
|
||||
]
|
||||
|
||||
if trigger_conf[CONF_PLATFORM] == "geo_location":
|
||||
return [trigger_conf[CONF_ZONE]]
|
||||
|
||||
@@ -99,6 +99,8 @@ Every check has a code following the
|
||||
| `W7407` | [`home-assistant-config-flow-polling-field`](#w7407-home-assistant-config-flow-polling-field) | Config flow should not include polling interval fields |
|
||||
| `W7408` | [`home-assistant-config-flow-name-field`](#w7408-home-assistant-config-flow-name-field) | Config flow should not include name fields |
|
||||
| `R7402` | [`home-assistant-unused-test-fixture-argument`](#r7402-home-assistant-unused-test-fixture-argument) | Unused test function argument should use `@pytest.mark.usefixtures` |
|
||||
| `W7418` | [`home-assistant-tests-direct-async-setup-entry`](#w7418-home-assistant-tests-direct-async-setup-entry) | Tests should not call an integration's `async_setup_entry` directly |
|
||||
| `W7420` | [`home-assistant-tests-direct-platform-async-setup-entry`](#w7420-home-assistant-tests-direct-platform-async-setup-entry) | Tests should not call a platform's `async_setup_entry` directly |
|
||||
| `W7422` | [`home-assistant-tests-direct-async-setup`](#w7422-home-assistant-tests-direct-async-setup) | Tests should not call an integration's `async_setup` directly |
|
||||
|
||||
|
||||
@@ -342,6 +344,27 @@ only needed for its side effects.
|
||||
This rule only applies to `test_*` functions, not to fixture functions.
|
||||
|
||||
|
||||
## `home_assistant_tests_direct_async_setup_entry` checker
|
||||
|
||||
Detects tests that call an integration's `async_setup_entry` directly.
|
||||
|
||||
### `W7418`: `home-assistant-tests-direct-async-setup-entry`
|
||||
|
||||
Tests should not invoke an integration's `async_setup_entry` from
|
||||
`__init__.py` directly. Instead, tests should let Home Assistant perform
|
||||
the setup via `await hass.config_entries.async_setup(entry.entry_id)` so
|
||||
that the real setup pipeline (platforms, services, listeners, unload
|
||||
handlers, etc.) is exercised.
|
||||
|
||||
### `W7420`: `home-assistant-tests-direct-platform-async-setup-entry`
|
||||
|
||||
Same as `W7418`, but for an entity platform's `async_setup_entry` (e.g.
|
||||
`homeassistant.components.<integration>.sensor.async_setup_entry`).
|
||||
Tests should drive setup through `hass.config_entries.async_setup` so
|
||||
the platform is loaded via the normal Home Assistant flow.
|
||||
|
||||
See [epic #77](https://github.com/home-assistant/epics/issues/77).
|
||||
|
||||
|
||||
## `home_assistant_tests_direct_async_setup` checker
|
||||
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Checker for direct calls to ``async_setup_entry`` from tests.
|
||||
|
||||
Tests should not invoke an integration's ``async_setup_entry`` directly
|
||||
(either the one in ``__init__.py`` or in an entity-platform module).
|
||||
Instead, tests should let Home Assistant perform the setup via
|
||||
``await hass.config_entries.async_setup(entry.entry_id)`` so that the
|
||||
real setup pipeline (platforms, services, listeners, unload handlers,
|
||||
etc.) is exercised.
|
||||
|
||||
This checker flags any call to ``async_setup_entry`` (whether awaited or
|
||||
not, accessed as a name or an attribute) made from a test module whose
|
||||
target resolves to a module-level function defined under
|
||||
``homeassistant.components.*``. The integration-init case and the
|
||||
entity-platform case get separate messages so violations can be tracked
|
||||
and fixed independently.
|
||||
"""
|
||||
|
||||
from enum import Enum
|
||||
|
||||
import astroid
|
||||
from astroid import nodes
|
||||
from pylint.checkers import BaseChecker
|
||||
from pylint.lint import PyLinter
|
||||
|
||||
from pylint_home_assistant.helpers.module_info import is_test_module, parse_module
|
||||
|
||||
|
||||
class _SetupKind(Enum):
|
||||
"""The kind of integration ``async_setup_entry`` being called."""
|
||||
|
||||
INIT = "init"
|
||||
PLATFORM = "platform"
|
||||
|
||||
|
||||
def _resolve_integration_async_setup_entry(call: nodes.Call) -> _SetupKind | None:
|
||||
"""Return the kind of integration ``async_setup_entry`` *call* targets.
|
||||
|
||||
Returns ``_SetupKind.INIT`` if the target is in the integration's
|
||||
``__init__`` module, ``_SetupKind.PLATFORM`` if it is in an
|
||||
entity-platform module, or ``None`` if the call does not resolve to
|
||||
an integration's ``async_setup_entry``.
|
||||
"""
|
||||
func = call.func
|
||||
match func:
|
||||
case nodes.Attribute(attrname="async_setup_entry"):
|
||||
pass
|
||||
case nodes.Name(name="async_setup_entry"):
|
||||
pass
|
||||
case _:
|
||||
return None
|
||||
|
||||
seen_qnames: set[str] = set()
|
||||
try:
|
||||
for inferred in func.infer():
|
||||
if inferred is astroid.Uninferable:
|
||||
continue
|
||||
if not isinstance(inferred, (nodes.FunctionDef, nodes.AsyncFunctionDef)):
|
||||
continue
|
||||
# Require the function to be defined at module level so that
|
||||
# class methods named ``async_setup_entry`` (whose qname
|
||||
# includes the class name) are not classified as integration
|
||||
# setup functions.
|
||||
if not isinstance(inferred.parent, nodes.Module):
|
||||
continue
|
||||
module_qname = inferred.parent.qname()
|
||||
if not module_qname or module_qname in seen_qnames:
|
||||
continue
|
||||
seen_qnames.add(module_qname)
|
||||
parsed = parse_module(module_qname)
|
||||
if parsed is None:
|
||||
continue
|
||||
return _SetupKind.INIT if parsed.module is None else _SetupKind.PLATFORM
|
||||
except astroid.exceptions.InferenceError, astroid.exceptions.AstroidError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
class DirectAsyncSetupEntry(BaseChecker):
|
||||
"""Checker for direct calls to async_setup_entry in tests."""
|
||||
|
||||
name = "home_assistant_tests_direct_async_setup_entry"
|
||||
priority = -1
|
||||
msgs = {
|
||||
"W7418": (
|
||||
(
|
||||
"Do not call `async_setup_entry` directly from tests; use "
|
||||
"`await hass.config_entries.async_setup(entry.entry_id)` instead"
|
||||
),
|
||||
"home-assistant-tests-direct-async-setup-entry",
|
||||
(
|
||||
"Used when a test module calls an integration's "
|
||||
"`async_setup_entry` from `__init__.py` directly. Tests should "
|
||||
"let Home Assistant drive the setup so the full setup pipeline "
|
||||
"is exercised."
|
||||
),
|
||||
),
|
||||
"W7420": (
|
||||
(
|
||||
"Do not call a platform's `async_setup_entry` directly from "
|
||||
"tests; use `await hass.config_entries.async_setup(entry.entry_id)`"
|
||||
" instead"
|
||||
),
|
||||
"home-assistant-tests-direct-platform-async-setup-entry",
|
||||
(
|
||||
"Used when a test module calls an integration entity platform's "
|
||||
"`async_setup_entry` directly. Tests should let Home Assistant "
|
||||
"drive the setup so the full setup pipeline is exercised."
|
||||
),
|
||||
),
|
||||
}
|
||||
options = ()
|
||||
|
||||
_in_test_module: bool = False
|
||||
|
||||
def visit_module(self, node: nodes.Module) -> None:
|
||||
"""Record whether the current module is a test module."""
|
||||
self._in_test_module = is_test_module(node.name)
|
||||
|
||||
def visit_call(self, node: nodes.Call) -> None:
|
||||
"""Flag direct calls to an integration's async_setup_entry."""
|
||||
if not self._in_test_module:
|
||||
return
|
||||
match _resolve_integration_async_setup_entry(node):
|
||||
case _SetupKind.INIT:
|
||||
self.add_message(
|
||||
"home-assistant-tests-direct-async-setup-entry",
|
||||
node=node,
|
||||
)
|
||||
case _SetupKind.PLATFORM:
|
||||
self.add_message(
|
||||
"home-assistant-tests-direct-platform-async-setup-entry",
|
||||
node=node,
|
||||
)
|
||||
|
||||
|
||||
def register(linter: PyLinter) -> None:
|
||||
"""Register the checker."""
|
||||
linter.register_checker(DirectAsyncSetupEntry(linter))
|
||||
Generated
+1
-1
@@ -2929,7 +2929,7 @@ rxv==0.7.0
|
||||
samsungctl[websocket]==0.7.1
|
||||
|
||||
# homeassistant.components.samsungtv
|
||||
samsungtvws[async,encrypted]==2.7.2
|
||||
samsungtvws[async,encrypted]==3.0.5
|
||||
|
||||
# homeassistant.components.sanix
|
||||
sanix==1.0.6
|
||||
|
||||
@@ -6,15 +6,18 @@ from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.analytics import LABS_SNAPSHOT_FEATURE
|
||||
from homeassistant.components.analytics import CONF_SNAPSHOTS_URL, LABS_SNAPSHOT_FEATURE
|
||||
from homeassistant.components.analytics.const import (
|
||||
BASIC_ENDPOINT_URL,
|
||||
BASIC_ENDPOINT_URL_DEV,
|
||||
DOMAIN,
|
||||
SNAPSHOT_DEFAULT_URL,
|
||||
SNAPSHOT_URL_PATH,
|
||||
STORAGE_KEY,
|
||||
)
|
||||
from homeassistant.components.hassio import HassioNotReadyError
|
||||
from homeassistant.components.labs import async_update_preview_feature
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import EVENT_HOMEASSISTANT_STARTED
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
@@ -37,6 +40,118 @@ async def test_setup(hass: HomeAssistant) -> None:
|
||||
assert DOMAIN in hass.data
|
||||
|
||||
|
||||
async def test_setup_with_snapshots_url(
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
) -> None:
|
||||
"""Test setup with snapshots_url in YAML config sends snapshots to that URL."""
|
||||
custom_url = "https://custom-snapshot-endpoint.example.com"
|
||||
snapshot_endpoint = custom_url + SNAPSHOT_URL_PATH
|
||||
aioclient_mock.post(snapshot_endpoint, status=200, json={})
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.analytics.analytics._async_snapshot_payload",
|
||||
return_value={"mock": {}},
|
||||
):
|
||||
assert await async_setup_component(hass, "labs", {})
|
||||
assert await async_setup_component(
|
||||
hass, DOMAIN, {DOMAIN: {CONF_SNAPSHOTS_URL: custom_url}}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
ws_client = await hass_ws_client(hass)
|
||||
await ws_client.send_json_auto_id(
|
||||
{"type": "analytics/preferences", "preferences": {"snapshots": True}}
|
||||
)
|
||||
assert (await ws_client.receive_json())["success"]
|
||||
|
||||
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=25))
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert any(str(call[1]) == snapshot_endpoint for call in aioclient_mock.mock_calls)
|
||||
|
||||
|
||||
async def test_setup_entry_supervisor_not_ready(hass: HomeAssistant) -> None:
|
||||
"""Test that HassioNotReadyError raises ConfigEntryNotReady."""
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.analytics.analytics.is_hassio",
|
||||
return_value=True,
|
||||
),
|
||||
patch(
|
||||
"homeassistant.components.hassio.get_supervisor_info",
|
||||
side_effect=HassioNotReadyError,
|
||||
),
|
||||
):
|
||||
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
await hass.async_block_till_done()
|
||||
|
||||
entry = hass.config_entries.async_entries(DOMAIN)[0]
|
||||
assert entry.state is ConfigEntryState.SETUP_RETRY
|
||||
|
||||
|
||||
async def test_schedule_starts_and_sends_analytics(
|
||||
hass: HomeAssistant,
|
||||
hass_storage: dict[str, Any],
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
) -> None:
|
||||
"""Test that the analytics schedule fires and sends analytics after time travel."""
|
||||
aioclient_mock.post(BASIC_ENDPOINT_URL, status=200)
|
||||
aioclient_mock.post(BASIC_ENDPOINT_URL_DEV, status=200)
|
||||
|
||||
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
await hass.async_block_till_done()
|
||||
|
||||
ws_client = await hass_ws_client(hass)
|
||||
with patch("homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION):
|
||||
await ws_client.send_json_auto_id(
|
||||
{"type": "analytics/preferences", "preferences": {"base": True}}
|
||||
)
|
||||
assert (await ws_client.receive_json())["success"]
|
||||
|
||||
assert len(aioclient_mock.mock_calls) == 0
|
||||
|
||||
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=901))
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(aioclient_mock.mock_calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("ws_type", "ws_options"),
|
||||
[("analytics", {}), ("analytics/preferences", {"preferences": {"base": True}})],
|
||||
)
|
||||
async def test_websocket_not_loaded(
|
||||
hass: HomeAssistant,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
ws_type: str,
|
||||
ws_options: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test websocket returns error when analytics entry failed to load."""
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.analytics.analytics.is_hassio",
|
||||
return_value=True,
|
||||
),
|
||||
patch(
|
||||
"homeassistant.components.hassio.get_supervisor_info",
|
||||
side_effect=HassioNotReadyError,
|
||||
),
|
||||
):
|
||||
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
|
||||
await hass.async_block_till_done()
|
||||
|
||||
ws_client = await hass_ws_client(hass)
|
||||
await ws_client.send_json_auto_id({"type": ws_type} | ws_options)
|
||||
response = await ws_client.receive_json()
|
||||
|
||||
assert not response["success"]
|
||||
assert response["error"]["code"] == "not_found"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_snapshot_payload")
|
||||
async def test_labs_feature_toggle(
|
||||
hass: HomeAssistant,
|
||||
|
||||
@@ -81,6 +81,7 @@ async def test_config_exceptions(
|
||||
),
|
||||
pytest.raises(config_error),
|
||||
):
|
||||
# pylint: disable-next=home-assistant-tests-direct-async-setup-entry
|
||||
await async_setup_entry(hass, config_entry)
|
||||
|
||||
|
||||
|
||||
@@ -411,7 +411,6 @@ async def test_initialize_flow(hass: HomeAssistant, client: TestClient) -> None:
|
||||
data_schema=vol.Schema(schema),
|
||||
description_placeholders={
|
||||
"url": "https://example.com",
|
||||
"show_advanced_options": self.show_advanced_options,
|
||||
},
|
||||
errors={"username": "Should be unique."},
|
||||
)
|
||||
@@ -437,7 +436,6 @@ async def test_initialize_flow(hass: HomeAssistant, client: TestClient) -> None:
|
||||
],
|
||||
"description_placeholders": {
|
||||
"url": "https://example.com",
|
||||
"show_advanced_options": True,
|
||||
},
|
||||
"errors": {"username": "Should be unique."},
|
||||
"last_step": None,
|
||||
|
||||
@@ -98,6 +98,29 @@ async def test_setup_entry_success(
|
||||
assert init_integration.state is ConfigEntryState.LOADED
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exception",
|
||||
[
|
||||
pytest.param(DucoError("lan info error"), id="duco_error"),
|
||||
pytest.param(DucoConnectionError("lan info offline"), id="connection_error"),
|
||||
],
|
||||
)
|
||||
async def test_setup_entry_ignores_lan_info_failures(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_duco_client: AsyncMock,
|
||||
exception: Exception,
|
||||
) -> None:
|
||||
"""Test setup succeeds when the supplemental LAN info endpoint fails."""
|
||||
mock_duco_client.async_get_lan_info.side_effect = exception
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_config_entry.state is ConfigEntryState.LOADED
|
||||
|
||||
|
||||
@pytest.mark.parametrize("unsupported_board_info", UNSUPPORTED_BOARD_INFOS)
|
||||
async def test_setup_entry_unsupported_board_info(
|
||||
hass: HomeAssistant,
|
||||
|
||||
@@ -122,24 +122,34 @@ async def test_coordinator_update_duco_error_marks_unavailable(
|
||||
assert state.state == STATE_UNAVAILABLE
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exception",
|
||||
[
|
||||
pytest.param(DucoError("lan info error"), id="duco_error"),
|
||||
pytest.param(DucoConnectionError("lan info offline"), id="connection_error"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
|
||||
async def test_lan_info_duco_error_marks_unavailable(
|
||||
async def test_lan_info_failures_keep_node_entities_available(
|
||||
hass: HomeAssistant,
|
||||
mock_duco_client: AsyncMock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
exception: Exception,
|
||||
) -> None:
|
||||
"""Test entities become unavailable when async_get_lan_info raises DucoError."""
|
||||
mock_duco_client.async_get_lan_info = AsyncMock(
|
||||
side_effect=DucoError("lan info error")
|
||||
)
|
||||
"""Test node entities stay available when LAN info retrieval fails."""
|
||||
mock_duco_client.async_get_lan_info = AsyncMock(side_effect=exception)
|
||||
|
||||
freezer.tick(SCAN_INTERVAL)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
state = hass.states.get("sensor.office_co2_carbon_dioxide")
|
||||
assert state is not None
|
||||
assert state.state == "405"
|
||||
|
||||
state = hass.states.get("sensor.living_signal_strength")
|
||||
assert state is not None
|
||||
assert state.state == STATE_UNAVAILABLE
|
||||
assert state.state == "-60"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
|
||||
@@ -83,6 +83,7 @@ async def test_setup_entry_successful(hass: HomeAssistant) -> None:
|
||||
"homeassistant.components.emulated_roku.binding.EmulatedRokuServer",
|
||||
return_value=Mock(start=AsyncMock(), close=AsyncMock()),
|
||||
) as instantiate:
|
||||
# pylint: disable-next=home-assistant-tests-direct-async-setup-entry
|
||||
assert await emulated_roku.async_setup_entry(hass, entry) is True
|
||||
|
||||
assert len(instantiate.mock_calls) == 1
|
||||
@@ -101,6 +102,7 @@ async def test_unload_entry(hass: HomeAssistant) -> None:
|
||||
"homeassistant.components.emulated_roku.binding.EmulatedRokuServer",
|
||||
return_value=Mock(start=AsyncMock(), close=AsyncMock()),
|
||||
):
|
||||
# pylint: disable-next=home-assistant-tests-direct-async-setup-entry
|
||||
assert await emulated_roku.async_setup_entry(hass, entry) is True
|
||||
|
||||
await hass.async_block_till_done()
|
||||
|
||||
@@ -43,6 +43,9 @@ async def init_integration(hass: HomeAssistant, ec_data) -> MockConfigEntry:
|
||||
radar_mock = mock_ec()
|
||||
radar_mock.image = b"GIF..."
|
||||
radar_mock.timestamp = datetime(2022, 10, 4, tzinfo=UTC)
|
||||
radar_mock.layer = "precip_type"
|
||||
radar_mock.metadata = {"attribution": "Data provided by Environment Canada"}
|
||||
radar_mock.clear_cache = MagicMock()
|
||||
|
||||
with (
|
||||
patch(
|
||||
@@ -54,7 +57,7 @@ async def init_integration(hass: HomeAssistant, ec_data) -> MockConfigEntry:
|
||||
return_value=mock_ec(),
|
||||
),
|
||||
patch(
|
||||
"homeassistant.components.environment_canada.ECRadar",
|
||||
"homeassistant.components.environment_canada.ECMap",
|
||||
return_value=radar_mock,
|
||||
),
|
||||
patch(
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Test Environment Canada camera."""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.environment_canada.camera import SERVICE_SET_RADAR_TYPE
|
||||
from homeassistant.components.environment_canada.const import DOMAIN
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.util.dt import UTC
|
||||
|
||||
from . import init_integration
|
||||
|
||||
|
||||
async def test_camera_entity(hass: HomeAssistant, ec_data: dict[str, Any]) -> None:
|
||||
"""Test camera entity setup."""
|
||||
await init_integration(hass, ec_data)
|
||||
|
||||
state = hass.states.get("camera.home_radar")
|
||||
# Camera is disabled by default, so state should be None
|
||||
assert state is None
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
@pytest.mark.parametrize(
|
||||
("radar_type", "expected_layer"),
|
||||
[
|
||||
("Rain", "rain"),
|
||||
("Snow", "snow"),
|
||||
("Precipitation type", "precip_type"),
|
||||
],
|
||||
)
|
||||
async def test_set_radar_type(
|
||||
hass: HomeAssistant,
|
||||
ec_data: dict[str, Any],
|
||||
radar_type: str,
|
||||
expected_layer: str,
|
||||
) -> None:
|
||||
"""Test setting radar type."""
|
||||
config_entry = await init_integration(hass, ec_data)
|
||||
radar_coordinator = config_entry.runtime_data.radar_coordinator
|
||||
radar_mock = radar_coordinator.ec_data
|
||||
|
||||
await hass.services.async_call(
|
||||
DOMAIN,
|
||||
SERVICE_SET_RADAR_TYPE,
|
||||
{"entity_id": "camera.home_radar", "radar_type": radar_type},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
assert radar_mock.layer == expected_layer
|
||||
radar_mock.update.assert_awaited()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
@pytest.mark.parametrize(
|
||||
("month", "expected_layer"),
|
||||
[
|
||||
(1, "snow"), # January - winter
|
||||
(2, "snow"), # February - winter
|
||||
(3, "snow"), # March - winter
|
||||
(4, "rain"), # April - spring/summer
|
||||
(5, "rain"), # May - spring/summer
|
||||
(6, "rain"), # June - summer
|
||||
(7, "rain"), # July - summer
|
||||
(8, "rain"), # August - summer
|
||||
(9, "rain"), # September - summer
|
||||
(10, "rain"), # October - fall
|
||||
(11, "snow"), # November - winter
|
||||
(12, "snow"), # December - winter
|
||||
],
|
||||
)
|
||||
async def test_set_radar_type_auto(
|
||||
hass: HomeAssistant,
|
||||
ec_data: dict[str, Any],
|
||||
month: int,
|
||||
expected_layer: str,
|
||||
) -> None:
|
||||
"""Test auto radar type selects rain or snow based on month."""
|
||||
config_entry = await init_integration(hass, ec_data)
|
||||
radar_coordinator = config_entry.runtime_data.radar_coordinator
|
||||
radar_mock = radar_coordinator.ec_data
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.environment_canada.camera.dt_util.now",
|
||||
return_value=datetime(2024, month, 15, tzinfo=UTC),
|
||||
):
|
||||
await hass.services.async_call(
|
||||
DOMAIN,
|
||||
SERVICE_SET_RADAR_TYPE,
|
||||
{"entity_id": "camera.home_radar", "radar_type": "Auto"},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
assert radar_mock.layer == expected_layer
|
||||
radar_mock.update.assert_awaited()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_set_radar_type_clears_cache(
|
||||
hass: HomeAssistant, ec_data: dict[str, Any]
|
||||
) -> None:
|
||||
"""Test that setting radar type clears the cache."""
|
||||
config_entry = await init_integration(hass, ec_data)
|
||||
radar_coordinator = config_entry.runtime_data.radar_coordinator
|
||||
radar_mock = radar_coordinator.ec_data
|
||||
|
||||
await hass.services.async_call(
|
||||
DOMAIN,
|
||||
SERVICE_SET_RADAR_TYPE,
|
||||
{"entity_id": "camera.home_radar", "radar_type": "Rain"},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
# Verify clear_cache was called on the radar object
|
||||
radar_mock.clear_cache.assert_called_once()
|
||||
@@ -4176,6 +4176,12 @@ async def test_channel(hass: HomeAssistant) -> None:
|
||||
media_player.MediaPlayerDeviceClass.TV,
|
||||
None,
|
||||
)
|
||||
assert trait.ChannelTrait.supported(
|
||||
media_player.DOMAIN,
|
||||
MediaPlayerEntityFeature.PLAY_MEDIA,
|
||||
media_player.MediaPlayerDeviceClass.PROJECTOR,
|
||||
None,
|
||||
)
|
||||
assert (
|
||||
trait.ChannelTrait.supported(
|
||||
media_player.DOMAIN,
|
||||
|
||||
@@ -246,6 +246,13 @@ def test_type_covers(type_name, entity_id, state, attrs) -> None:
|
||||
{ATTR_DEVICE_CLASS: MediaPlayerDeviceClass.RECEIVER},
|
||||
{},
|
||||
),
|
||||
(
|
||||
"TelevisionMediaPlayer",
|
||||
"media_player.projector",
|
||||
"on",
|
||||
{ATTR_DEVICE_CLASS: MediaPlayerDeviceClass.PROJECTOR},
|
||||
{},
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_type_media_player(type_name, entity_id, state, attrs, config) -> None:
|
||||
|
||||
@@ -1046,3 +1046,29 @@ async def test_light_turn_on_service_deprecation(
|
||||
blocking=True,
|
||||
)
|
||||
assert mock_bridge_v2.mock_requests[0]["json"]["effects"]["effect"] == "no_effect"
|
||||
|
||||
|
||||
async def test_light_with_zero_mirek(
|
||||
hass: HomeAssistant, mock_bridge_v2: Mock, v2_resources_test_data: JsonArrayType
|
||||
) -> None:
|
||||
"""Test light doesn't crash when bridge reports zero mirek values.
|
||||
|
||||
Regression test for https://github.com/home-assistant/core/issues/116258
|
||||
"""
|
||||
# Patch the fixture data to have zero mirek values before loading
|
||||
for resource in v2_resources_test_data:
|
||||
if resource.get("type") == "light" and "color_temperature" in resource:
|
||||
resource["color_temperature"]["mirek_schema"]["mirek_minimum"] = 0
|
||||
resource["color_temperature"]["mirek_schema"]["mirek_maximum"] = 0
|
||||
break
|
||||
|
||||
await mock_bridge_v2.api.load_test_data(v2_resources_test_data)
|
||||
|
||||
# Should not raise ZeroDivisionError during setup
|
||||
await setup_platform(hass, mock_bridge_v2, Platform.LIGHT)
|
||||
|
||||
test_light = hass.states.get("light.hue_light_with_color_and_color_temperature_1")
|
||||
assert test_light is not None
|
||||
# Should fall back to defaults instead of crashing
|
||||
assert test_light.attributes["max_color_temp_kelvin"] == 6535
|
||||
assert test_light.attributes["min_color_temp_kelvin"] == 2000
|
||||
|
||||
@@ -32,6 +32,7 @@ async def test_ha_mqtt_publish(
|
||||
mock_discovery.start.return_value = []
|
||||
mock_discovery_class.return_value = mock_discovery
|
||||
|
||||
# pylint: disable-next=home-assistant-tests-direct-async-setup-entry
|
||||
await inels.async_setup_entry(hass, config_entry)
|
||||
|
||||
topic, payload, qos, retain = "test/topic", "test_payload", 1, True
|
||||
@@ -60,6 +61,7 @@ async def test_ha_mqtt_subscribe(
|
||||
mock_discovery.start.return_value = []
|
||||
mock_discovery_class.return_value = mock_discovery
|
||||
|
||||
# pylint: disable-next=home-assistant-tests-direct-async-setup-entry
|
||||
await inels.async_setup_entry(hass, config_entry)
|
||||
|
||||
topic = "test/topic"
|
||||
@@ -82,6 +84,7 @@ async def test_ha_mqtt_not_available(
|
||||
),
|
||||
pytest.raises(ConfigEntryNotReady, match="MQTT integration not available"),
|
||||
):
|
||||
# pylint: disable-next=home-assistant-tests-direct-async-setup-entry
|
||||
await inels.async_setup_entry(hass, config_entry)
|
||||
|
||||
|
||||
|
||||
@@ -62,6 +62,7 @@ async def test_async_setup_entry_connection_error(
|
||||
)
|
||||
|
||||
with pytest.raises(ConfigEntryNotReady):
|
||||
# pylint: disable-next=home-assistant-tests-direct-async-setup-entry
|
||||
await async_setup_entry(hass, mock_config_entry)
|
||||
|
||||
assert mock_iometer_client.get_current_status.await_count == 1
|
||||
|
||||
@@ -26,7 +26,7 @@ def mock_config_entry() -> MockConfigEntry:
|
||||
def mock_pizone_discovery_service() -> Mock:
|
||||
"""Create a mock pizone discovery service."""
|
||||
disco = Mock()
|
||||
disco.controllers = {}
|
||||
disco.fetch_controllers = AsyncMock(return_value={})
|
||||
disco.start_discovery = AsyncMock()
|
||||
disco.close = AsyncMock()
|
||||
return disco
|
||||
@@ -96,9 +96,9 @@ async def mock_discovery(
|
||||
"homeassistant.components.izone.discovery.pizone.discovery", autospec=True
|
||||
) as mock_disco:
|
||||
mock_disco.return_value.start_discovery = AsyncMock()
|
||||
mock_disco.return_value.controllers = {
|
||||
mock_controller.device_uid: mock_controller
|
||||
}
|
||||
mock_disco.return_value.fetch_controllers = AsyncMock(
|
||||
return_value={mock_controller.device_uid: mock_controller}
|
||||
)
|
||||
mock_disco.return_value.close = AsyncMock()
|
||||
yield mock_disco
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
from unittest.mock import Mock, patch
|
||||
from unittest.mock import AsyncMock, Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -18,7 +18,7 @@ def mock_disco() -> Mock:
|
||||
"""Mock discovery service."""
|
||||
disco = Mock()
|
||||
disco.pi_disco = Mock()
|
||||
disco.pi_disco.controllers = {}
|
||||
disco.pi_disco.fetch_controllers = AsyncMock(return_value={})
|
||||
return disco
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ async def test_not_found(hass: HomeAssistant, mock_disco: Mock) -> None:
|
||||
|
||||
async def test_found(hass: HomeAssistant, mock_disco: Mock) -> None:
|
||||
"""Test not finding iZone controller."""
|
||||
mock_disco.pi_disco.controllers["blah"] = object()
|
||||
mock_disco.pi_disco.fetch_controllers = AsyncMock(return_value={"blah": object()})
|
||||
|
||||
with (
|
||||
patch(
|
||||
|
||||
@@ -42,6 +42,7 @@ async def test_setup_demo_platform(hass: HomeAssistant) -> None:
|
||||
"""Test setup."""
|
||||
mock = MagicMock()
|
||||
add_entities = mock.MagicMock()
|
||||
# pylint: disable-next=home-assistant-tests-direct-platform-async-setup-entry
|
||||
await demo.async_setup_entry(hass, {}, add_entities)
|
||||
assert add_entities.call_count == 1
|
||||
|
||||
|
||||
@@ -69,9 +69,15 @@ def test_create_matter_ble_proxy_wires_ha_backends(hass: HomeAssistant) -> None:
|
||||
assert kwargs["ws_url"] == "ws://localhost:5580/ble"
|
||||
assert isinstance(kwargs["scan_source"], HaBluetoothScanSource)
|
||||
assert isinstance(kwargs["device_resolver"], HaBluetoothDeviceResolver)
|
||||
assert kwargs["task_factory"] == hass.async_create_task
|
||||
assert result is proxy_cls.return_value
|
||||
|
||||
coro = MagicMock()
|
||||
with patch.object(hass, "async_create_background_task") as bg_task:
|
||||
task = kwargs["task_factory"](coro)
|
||||
|
||||
bg_task.assert_called_once_with(coro, name="matter_ble_proxy")
|
||||
assert task is bg_task.return_value
|
||||
|
||||
|
||||
async def test_scan_source_start_registers_passive_callback(
|
||||
hass: HomeAssistant,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,101 @@
|
||||
"""Tests for the Samsung Infrared button platform."""
|
||||
|
||||
from infrared_protocols.codes.samsung.tv import SamsungTVCode
|
||||
import pytest
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS
|
||||
from homeassistant.const import ATTR_ENTITY_ID, Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
|
||||
from tests.common import MockConfigEntry, snapshot_platform
|
||||
from tests.components.common import assert_availability_follows_source_entity
|
||||
from tests.components.infrared import EMITTER_ENTITY_ID
|
||||
from tests.components.infrared.common import MockInfraredEmitterEntity
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def platforms() -> list[Platform]:
|
||||
"""Return platforms to set up."""
|
||||
return [Platform.BUTTON]
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("init_integration")
|
||||
async def test_entities(
|
||||
hass: HomeAssistant,
|
||||
snapshot: SnapshotAssertion,
|
||||
entity_registry: er.EntityRegistry,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Test button entities are created with correct attributes."""
|
||||
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("entity_id", "expected_code"),
|
||||
[
|
||||
("button.samsung_tv_power", SamsungTVCode.POWER),
|
||||
("button.samsung_tv_source", SamsungTVCode.SOURCE),
|
||||
("button.samsung_tv_settings", SamsungTVCode.SETTINGS),
|
||||
("button.samsung_tv_info", SamsungTVCode.INFO),
|
||||
("button.samsung_tv_exit", SamsungTVCode.EXIT),
|
||||
("button.samsung_tv_return", SamsungTVCode.RETURN),
|
||||
("button.samsung_tv_home", SamsungTVCode.HOME),
|
||||
("button.samsung_tv_red", SamsungTVCode.RED),
|
||||
("button.samsung_tv_green", SamsungTVCode.GREEN),
|
||||
("button.samsung_tv_yellow", SamsungTVCode.YELLOW),
|
||||
("button.samsung_tv_blue", SamsungTVCode.BLUE),
|
||||
("button.samsung_tv_up", SamsungTVCode.NAV_UP),
|
||||
("button.samsung_tv_down", SamsungTVCode.NAV_DOWN),
|
||||
("button.samsung_tv_left", SamsungTVCode.NAV_LEFT),
|
||||
("button.samsung_tv_right", SamsungTVCode.NAV_RIGHT),
|
||||
("button.samsung_tv_ok", SamsungTVCode.OK),
|
||||
("button.samsung_tv_previous_channel", SamsungTVCode.PREVIOUS_CHANNEL),
|
||||
("button.samsung_tv_number_0", SamsungTVCode.NUM_0),
|
||||
("button.samsung_tv_number_1", SamsungTVCode.NUM_1),
|
||||
("button.samsung_tv_number_2", SamsungTVCode.NUM_2),
|
||||
("button.samsung_tv_number_3", SamsungTVCode.NUM_3),
|
||||
("button.samsung_tv_number_4", SamsungTVCode.NUM_4),
|
||||
("button.samsung_tv_number_5", SamsungTVCode.NUM_5),
|
||||
("button.samsung_tv_number_6", SamsungTVCode.NUM_6),
|
||||
("button.samsung_tv_number_7", SamsungTVCode.NUM_7),
|
||||
("button.samsung_tv_number_8", SamsungTVCode.NUM_8),
|
||||
("button.samsung_tv_number_9", SamsungTVCode.NUM_9),
|
||||
("button.samsung_tv_fast_forward", SamsungTVCode.FAST_FORWARD),
|
||||
("button.samsung_tv_rewind", SamsungTVCode.REWIND),
|
||||
("button.samsung_tv_record", SamsungTVCode.RECORD),
|
||||
("button.samsung_tv_tools", SamsungTVCode.TOOLS),
|
||||
("button.samsung_tv_browser", SamsungTVCode.BROWSER),
|
||||
("button.samsung_tv_ad_subtitle", SamsungTVCode.AD_SUBTITLE),
|
||||
("button.samsung_tv_e_manual", SamsungTVCode.E_MANUAL),
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("init_integration")
|
||||
async def test_button_press_sends_correct_code(
|
||||
hass: HomeAssistant,
|
||||
mock_infrared_emitter_entity: MockInfraredEmitterEntity,
|
||||
entity_id: str,
|
||||
expected_code: SamsungTVCode,
|
||||
) -> None:
|
||||
"""Test pressing each button sends the correct IR code."""
|
||||
await hass.services.async_call(
|
||||
BUTTON_DOMAIN,
|
||||
SERVICE_PRESS,
|
||||
{ATTR_ENTITY_ID: entity_id},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
assert len(mock_infrared_emitter_entity.send_command_calls) == 1
|
||||
assert (
|
||||
mock_infrared_emitter_entity.send_command_calls[0] == expected_code.to_command()
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("init_integration")
|
||||
async def test_button_availability_follows_ir_entity(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test button becomes unavailable when IR entity is unavailable."""
|
||||
entity_id = "button.samsung_tv_source"
|
||||
await assert_availability_follows_source_entity(hass, entity_id, EMITTER_ENTITY_ID)
|
||||
@@ -1,19 +1,21 @@
|
||||
"""The tests for Sense binary sensor platform."""
|
||||
|
||||
from datetime import timedelta
|
||||
from unittest.mock import MagicMock
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
from sense_energy import SenseAPIException
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN
|
||||
from homeassistant.components.sense.const import ACTIVE_UPDATE_RATE
|
||||
from homeassistant.const import STATE_OFF, STATE_ON, Platform
|
||||
from homeassistant.components.sense.const import ACTIVE_UPDATE_RATE, DOMAIN
|
||||
from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE, Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
from homeassistant.util.dt import utcnow
|
||||
|
||||
from . import setup_platform
|
||||
from .const import DEVICE_1_NAME, DEVICE_2_NAME
|
||||
from .const import DEVICE_1_ID, DEVICE_1_NAME, DEVICE_2_NAME, MONITOR_ID
|
||||
|
||||
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
|
||||
|
||||
@@ -66,3 +68,50 @@ async def test_on_off_sensors(
|
||||
|
||||
state = hass.states.get(f"binary_sensor.{DEVICE_2_NAME.lower()}_power")
|
||||
assert state.state == STATE_ON
|
||||
|
||||
|
||||
async def test_realtime_update_exception(
|
||||
hass: HomeAssistant,
|
||||
mock_sense: MagicMock,
|
||||
config_entry: MockConfigEntry,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test that binary sensor entities become unavailable on realtime coordinator failure."""
|
||||
await setup_platform(hass, config_entry, Platform.BINARY_SENSOR)
|
||||
|
||||
state = hass.states.get(f"binary_sensor.{DEVICE_1_NAME.lower()}_power")
|
||||
assert state is not None
|
||||
assert state.state != STATE_UNAVAILABLE
|
||||
|
||||
mock_sense.update_realtime.side_effect = SenseAPIException("api error")
|
||||
|
||||
freezer.tick(timedelta(seconds=ACTIVE_UPDATE_RATE))
|
||||
async_fire_time_changed(hass, freezer())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get(f"binary_sensor.{DEVICE_1_NAME.lower()}_power")
|
||||
assert state.state == STATE_UNAVAILABLE
|
||||
|
||||
|
||||
async def test_migrate_unique_ids(
|
||||
hass: HomeAssistant,
|
||||
mock_sense: MagicMock,
|
||||
config_entry: MockConfigEntry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
) -> None:
|
||||
"""Test that entities registered under the old bare device-ID unique_id are migrated."""
|
||||
config_entry.add_to_hass(hass)
|
||||
old_entry = entity_registry.async_get_or_create(
|
||||
BINARY_SENSOR_DOMAIN,
|
||||
DOMAIN,
|
||||
DEVICE_1_ID,
|
||||
config_entry=config_entry,
|
||||
)
|
||||
assert old_entry.unique_id == DEVICE_1_ID
|
||||
|
||||
with patch("homeassistant.components.sense.PLATFORMS", [Platform.BINARY_SENSOR]):
|
||||
assert await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
migrated = entity_registry.async_get(old_entry.entity_id)
|
||||
assert migrated.unique_id == f"{MONITOR_ID}-{DEVICE_1_ID}"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Test the Sense config flow."""
|
||||
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from collections.abc import Iterator
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from sense_energy import (
|
||||
@@ -21,9 +22,9 @@ from .const import MOCK_CONFIG
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
@pytest.fixture(name="mock_sense")
|
||||
def mock_sense():
|
||||
"""Mock Sense object for authenticatation."""
|
||||
@pytest.fixture(name="mock_flow_sense")
|
||||
def mock_flow_sense_fixture() -> Iterator[MagicMock]:
|
||||
"""Mock Sense object for authentication."""
|
||||
with patch(
|
||||
"homeassistant.components.sense.config_flow.ASyncSenseable"
|
||||
) as mock_sense:
|
||||
@@ -37,259 +38,196 @@ def mock_sense():
|
||||
yield mock_sense
|
||||
|
||||
|
||||
async def test_form(hass: HomeAssistant, mock_sense) -> None:
|
||||
@pytest.mark.usefixtures("mock_flow_sense")
|
||||
async def test_form(
|
||||
hass: HomeAssistant,
|
||||
mock_setup_entry: AsyncMock,
|
||||
) -> 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"] == {}
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sense.async_setup_entry",
|
||||
return_value=True,
|
||||
) as mock_setup_entry:
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{"timeout": "6", "email": "test-email", "password": "test-password"},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{"timeout": "6", "email": "test-email", "password": "test-password"},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result2["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result2["title"] == "test-email"
|
||||
assert result2["data"] == MOCK_CONFIG
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == "test-email"
|
||||
assert result["data"] == MOCK_CONFIG
|
||||
mock_setup_entry.assert_called_once()
|
||||
|
||||
|
||||
async def test_form_invalid_auth(hass: HomeAssistant) -> None:
|
||||
"""Test we handle invalid auth."""
|
||||
@pytest.mark.parametrize(
|
||||
("exception", "error"),
|
||||
[
|
||||
(SenseAuthenticationException(), "invalid_auth"),
|
||||
(SenseAPITimeoutException(), "cannot_connect"),
|
||||
(SenseAPIException(), "cannot_connect"),
|
||||
(Exception("unknown exception"), "unknown"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("mock_setup_entry")
|
||||
async def test_form_exceptions(
|
||||
hass: HomeAssistant,
|
||||
mock_flow_sense: MagicMock,
|
||||
exception: Exception,
|
||||
error: str,
|
||||
) -> None:
|
||||
"""Test we handle all exceptions in the user flow and can recover."""
|
||||
mock_flow_sense.return_value.authenticate.side_effect = exception
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
|
||||
with patch(
|
||||
"sense_energy.ASyncSenseable.authenticate",
|
||||
side_effect=SenseAuthenticationException,
|
||||
):
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{"timeout": "6", "email": "test-email", "password": "test-password"},
|
||||
)
|
||||
|
||||
assert result2["type"] is FlowResultType.FORM
|
||||
assert result2["errors"] == {"base": "invalid_auth"}
|
||||
|
||||
|
||||
async def test_form_mfa_required(hass: HomeAssistant, mock_sense) -> None:
|
||||
"""Test we handle invalid auth."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
|
||||
mock_sense.return_value.authenticate.side_effect = SenseMFARequiredException
|
||||
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{"timeout": "6", "email": "test-email", "password": "test-password"},
|
||||
)
|
||||
|
||||
assert result2["type"] is FlowResultType.FORM
|
||||
assert result2["step_id"] == "validation"
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {"base": error}
|
||||
|
||||
mock_sense.return_value.validate_mfa.side_effect = None
|
||||
result3 = await hass.config_entries.flow.async_configure(
|
||||
# Verify recovery: clear the error and complete the flow successfully
|
||||
mock_flow_sense.return_value.authenticate.side_effect = None
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{"timeout": "6", "email": "test-email", "password": "test-password"},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_setup_entry")
|
||||
async def test_form_mfa_required(
|
||||
hass: HomeAssistant,
|
||||
mock_flow_sense: MagicMock,
|
||||
) -> None:
|
||||
"""Test we handle the MFA flow."""
|
||||
mock_flow_sense.return_value.authenticate.side_effect = SenseMFARequiredException()
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{"timeout": "6", "email": "test-email", "password": "test-password"},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "validation"
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{CONF_CODE: "012345"},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result3["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result3["title"] == "test-email"
|
||||
assert result3["data"] == MOCK_CONFIG
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == "test-email"
|
||||
assert result["data"] == MOCK_CONFIG
|
||||
|
||||
|
||||
async def test_form_mfa_required_wrong(hass: HomeAssistant, mock_sense) -> None:
|
||||
"""Test we handle invalid auth."""
|
||||
@pytest.mark.parametrize(
|
||||
("exception", "error"),
|
||||
[
|
||||
(SenseAuthenticationException(), "invalid_auth"),
|
||||
(SenseAPITimeoutException(), "cannot_connect"),
|
||||
(SenseAPIException(), "cannot_connect"),
|
||||
(Exception("Unknown exception"), "unknown"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("mock_setup_entry")
|
||||
async def test_form_mfa_exceptions(
|
||||
hass: HomeAssistant,
|
||||
mock_flow_sense: MagicMock,
|
||||
exception: Exception,
|
||||
error: str,
|
||||
) -> None:
|
||||
"""Test we handle all MFA validation exceptions and can recover."""
|
||||
mock_flow_sense.return_value.authenticate.side_effect = SenseMFARequiredException()
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
|
||||
mock_sense.return_value.authenticate.side_effect = SenseMFARequiredException
|
||||
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{"timeout": "6", "email": "test-email", "password": "test-password"},
|
||||
)
|
||||
|
||||
assert result2["type"] is FlowResultType.FORM
|
||||
assert result2["step_id"] == "validation"
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "validation"
|
||||
|
||||
mock_sense.return_value.validate_mfa.side_effect = SenseAuthenticationException
|
||||
# Try with the WRONG verification code give us the form back again
|
||||
result3 = await hass.config_entries.flow.async_configure(
|
||||
mock_flow_sense.return_value.validate_mfa.side_effect = exception
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{CONF_CODE: "000000"},
|
||||
)
|
||||
|
||||
assert result3["type"] is FlowResultType.FORM
|
||||
assert result3["errors"] == {"base": "invalid_auth"}
|
||||
assert result3["step_id"] == "validation"
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {"base": error}
|
||||
assert result["step_id"] == "validation"
|
||||
|
||||
|
||||
async def test_form_mfa_required_timeout(hass: HomeAssistant, mock_sense) -> None:
|
||||
"""Test we handle invalid auth."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
|
||||
mock_sense.return_value.authenticate.side_effect = SenseMFARequiredException
|
||||
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
# Verify recovery: clear the error and complete MFA successfully
|
||||
mock_flow_sense.return_value.validate_mfa.side_effect = None
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{"timeout": "6", "email": "test-email", "password": "test-password"},
|
||||
{CONF_CODE: "012345"},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result2["type"] is FlowResultType.FORM
|
||||
assert result2["step_id"] == "validation"
|
||||
|
||||
mock_sense.return_value.validate_mfa.side_effect = SenseAPITimeoutException
|
||||
result3 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{CONF_CODE: "000000"},
|
||||
)
|
||||
|
||||
assert result3["type"] is FlowResultType.FORM
|
||||
assert result3["errors"] == {"base": "cannot_connect"}
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == "test-email"
|
||||
assert result["data"] == MOCK_CONFIG
|
||||
|
||||
|
||||
async def test_form_mfa_required_exception(hass: HomeAssistant, mock_sense) -> None:
|
||||
"""Test we handle invalid auth."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
|
||||
mock_sense.return_value.authenticate.side_effect = SenseMFARequiredException
|
||||
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{"timeout": "6", "email": "test-email", "password": "test-password"},
|
||||
)
|
||||
|
||||
assert result2["type"] is FlowResultType.FORM
|
||||
assert result2["step_id"] == "validation"
|
||||
|
||||
mock_sense.return_value.validate_mfa.side_effect = Exception
|
||||
result3 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{CONF_CODE: "000000"},
|
||||
)
|
||||
|
||||
assert result3["type"] is FlowResultType.FORM
|
||||
assert result3["errors"] == {"base": "unknown"}
|
||||
|
||||
|
||||
async def test_form_timeout(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(
|
||||
"sense_energy.ASyncSenseable.authenticate",
|
||||
side_effect=SenseAPITimeoutException,
|
||||
):
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{"timeout": "6", "email": "test-email", "password": "test-password"},
|
||||
)
|
||||
|
||||
assert result2["type"] is FlowResultType.FORM
|
||||
assert result2["errors"] == {"base": "cannot_connect"}
|
||||
|
||||
|
||||
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(
|
||||
"sense_energy.ASyncSenseable.authenticate",
|
||||
side_effect=SenseAPIException,
|
||||
):
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{"timeout": "6", "email": "test-email", "password": "test-password"},
|
||||
)
|
||||
|
||||
assert result2["type"] is FlowResultType.FORM
|
||||
assert result2["errors"] == {"base": "cannot_connect"}
|
||||
|
||||
|
||||
async def test_form_unknown_exception(hass: HomeAssistant) -> None:
|
||||
"""Test we handle unknown error."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
|
||||
with patch(
|
||||
"sense_energy.ASyncSenseable.authenticate",
|
||||
side_effect=Exception,
|
||||
):
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{"timeout": "6", "email": "test-email", "password": "test-password"},
|
||||
)
|
||||
|
||||
assert result2["type"] is FlowResultType.FORM
|
||||
assert result2["errors"] == {"base": "unknown"}
|
||||
|
||||
|
||||
async def test_reauth_no_form(hass: HomeAssistant, mock_sense) -> None:
|
||||
@pytest.mark.usefixtures("mock_flow_sense")
|
||||
async def test_reauth_no_form(
|
||||
hass: HomeAssistant,
|
||||
mock_setup_entry: AsyncMock,
|
||||
) -> None:
|
||||
"""Test reauth where no form needed."""
|
||||
|
||||
# set up initially
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data=MOCK_CONFIG,
|
||||
unique_id="test-email",
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
with patch(
|
||||
"homeassistant.config_entries.ConfigEntries.async_reload",
|
||||
return_value=True,
|
||||
):
|
||||
result = await entry.start_reauth_flow(hass)
|
||||
result = await entry.start_reauth_flow(hass)
|
||||
await hass.async_block_till_done()
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
mock_setup_entry.assert_called_once()
|
||||
|
||||
|
||||
async def test_reauth_password(hass: HomeAssistant, mock_sense) -> None:
|
||||
@pytest.mark.usefixtures("mock_setup_entry")
|
||||
async def test_reauth_password(
|
||||
hass: HomeAssistant,
|
||||
mock_flow_sense: MagicMock,
|
||||
) -> None:
|
||||
"""Test reauth form."""
|
||||
|
||||
# set up initially
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data=MOCK_CONFIG,
|
||||
unique_id="test-email",
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
mock_sense.return_value.authenticate.side_effect = SenseAuthenticationException
|
||||
mock_flow_sense.return_value.authenticate.side_effect = SenseAuthenticationException
|
||||
|
||||
# Reauth success without user input
|
||||
result = await entry.start_reauth_flow(hass)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
|
||||
mock_sense.return_value.authenticate.side_effect = None
|
||||
with patch(
|
||||
"homeassistant.components.sense.async_setup_entry",
|
||||
return_value=True,
|
||||
):
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{"password": "test-password"},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
mock_flow_sense.return_value.authenticate.side_effect = None
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{"password": "test-password"},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result2["type"] is FlowResultType.ABORT
|
||||
assert result2["reason"] == "reauth_successful"
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Tests for the Sense coordinators."""
|
||||
|
||||
from datetime import timedelta
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
import pytest
|
||||
from sense_energy import SenseAuthenticationException, SenseMFARequiredException
|
||||
|
||||
from homeassistant.components.sense.const import DOMAIN, TREND_UPDATE_RATE
|
||||
from homeassistant.config_entries import SOURCE_REAUTH
|
||||
from homeassistant.const import STATE_UNAVAILABLE, Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from . import setup_platform
|
||||
from .const import MONITOR_ID
|
||||
|
||||
from tests.common import MockConfigEntry, async_fire_time_changed
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exception",
|
||||
[
|
||||
SenseAuthenticationException("auth expired"),
|
||||
SenseMFARequiredException("auth expired"),
|
||||
],
|
||||
)
|
||||
async def test_trend_coordinator_auth_failure(
|
||||
hass: HomeAssistant,
|
||||
mock_sense: MagicMock,
|
||||
config_entry: MockConfigEntry,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
exception: Exception,
|
||||
) -> None:
|
||||
"""Test that auth errors from the trend coordinator start a reauth flow."""
|
||||
await setup_platform(hass, config_entry, Platform.SENSOR)
|
||||
|
||||
mock_sense.update_trend_data.side_effect = exception
|
||||
|
||||
freezer.tick(timedelta(seconds=TREND_UPDATE_RATE))
|
||||
async_fire_time_changed(hass, freezer())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get(f"sensor.sense_{MONITOR_ID}_daily_energy")
|
||||
assert state.state == STATE_UNAVAILABLE
|
||||
|
||||
flows = hass.config_entries.flow.async_progress()
|
||||
assert len(flows) == 1
|
||||
flow = flows[0]
|
||||
assert flow.get("step_id") == "reauth_validate"
|
||||
assert flow.get("handler") == DOMAIN
|
||||
assert flow["context"].get("source") == SOURCE_REAUTH
|
||||
assert flow["context"].get("entry_id") == config_entry.entry_id
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Tests for the Sense integration setup."""
|
||||
|
||||
import socket
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from sense_energy import (
|
||||
SenseAPIException,
|
||||
SenseAPITimeoutException,
|
||||
SenseAuthenticationException,
|
||||
SenseMFARequiredException,
|
||||
SenseWebsocketException,
|
||||
)
|
||||
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exception",
|
||||
[
|
||||
SenseAPITimeoutException(),
|
||||
SenseWebsocketException(),
|
||||
],
|
||||
)
|
||||
async def test_setup_entry_exceptions(
|
||||
hass: HomeAssistant,
|
||||
mock_sense: MagicMock,
|
||||
config_entry: MockConfigEntry,
|
||||
exception: Exception,
|
||||
) -> None:
|
||||
"""Test we handle exceptions during async_setup_entry and can recover."""
|
||||
mock_sense.update_realtime.side_effect = exception
|
||||
config_entry.add_to_hass(hass)
|
||||
|
||||
assert not await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
|
||||
# Verify recovery: clear the error and reload the entry
|
||||
mock_sense.update_realtime.side_effect = None
|
||||
assert await hass.config_entries.async_reload(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert config_entry.state is ConfigEntryState.LOADED
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exception",
|
||||
[
|
||||
SenseAuthenticationException(),
|
||||
SenseMFARequiredException(),
|
||||
],
|
||||
)
|
||||
async def test_setup_get_monitor_data_auth_exceptions(
|
||||
hass: HomeAssistant,
|
||||
mock_sense: MagicMock,
|
||||
config_entry: MockConfigEntry,
|
||||
exception: Exception,
|
||||
) -> None:
|
||||
"""Test auth exceptions from get_monitor_data result in a failed entry."""
|
||||
mock_sense.get_monitor_data.side_effect = exception
|
||||
config_entry.add_to_hass(hass)
|
||||
|
||||
assert not await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert config_entry.state is ConfigEntryState.SETUP_ERROR
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exception",
|
||||
[
|
||||
SenseAPITimeoutException(),
|
||||
TimeoutError(),
|
||||
SenseAPIException("connect error"),
|
||||
socket.gaierror(),
|
||||
],
|
||||
)
|
||||
async def test_setup_get_monitor_data_retry_exceptions(
|
||||
hass: HomeAssistant,
|
||||
mock_sense: MagicMock,
|
||||
config_entry: MockConfigEntry,
|
||||
exception: Exception,
|
||||
) -> None:
|
||||
"""Test timeout and connect exceptions from get_monitor_data result in a retryable entry."""
|
||||
mock_sense.get_monitor_data.side_effect = exception
|
||||
config_entry.add_to_hass(hass)
|
||||
|
||||
assert not await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exception",
|
||||
[
|
||||
SenseAPITimeoutException(),
|
||||
TimeoutError(),
|
||||
SenseAPIException("connect error"),
|
||||
socket.gaierror(),
|
||||
SenseWebsocketException("ws error"),
|
||||
SenseAPIException(),
|
||||
],
|
||||
)
|
||||
async def test_setup_get_realtime_retry_exceptions(
|
||||
hass: HomeAssistant,
|
||||
mock_sense: MagicMock,
|
||||
config_entry: MockConfigEntry,
|
||||
exception: Exception,
|
||||
) -> None:
|
||||
"""Test timeout and connect exceptions from update_realtime result in a retryable entry."""
|
||||
mock_sense.update_realtime.side_effect = exception
|
||||
config_entry.add_to_hass(hass)
|
||||
|
||||
assert not await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
@@ -1,16 +1,22 @@
|
||||
"""The tests for Sense sensor platform."""
|
||||
|
||||
from datetime import timedelta
|
||||
import socket
|
||||
from unittest.mock import MagicMock, PropertyMock
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
import pytest
|
||||
from sense_energy import Scale
|
||||
from sense_energy import (
|
||||
Scale,
|
||||
SenseAPIException,
|
||||
SenseAPITimeoutException,
|
||||
SenseWebsocketException,
|
||||
)
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant.components.sense.const import ACTIVE_UPDATE_RATE, TREND_UPDATE_RATE
|
||||
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.const import STATE_UNAVAILABLE, Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
from homeassistant.util.dt import utcnow
|
||||
@@ -232,3 +238,88 @@ async def test_trend_energy_sensors(
|
||||
|
||||
state = hass.states.get(f"sensor.sense_{MONITOR_ID}_daily_net_production")
|
||||
assert state.state == "5000"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exception",
|
||||
[
|
||||
SenseAPIException("api error"),
|
||||
SenseAPITimeoutException("timeout"),
|
||||
TimeoutError("timeout"),
|
||||
socket.gaierror("addr info error"),
|
||||
],
|
||||
)
|
||||
async def test_trend_coordinator_update_failure(
|
||||
hass: HomeAssistant,
|
||||
mock_sense: MagicMock,
|
||||
config_entry: MockConfigEntry,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
exception: Exception,
|
||||
) -> None:
|
||||
"""Test that connection errors from the trend coordinator mark entities unavailable."""
|
||||
await setup_platform(hass, config_entry, Platform.SENSOR)
|
||||
|
||||
state = hass.states.get(f"sensor.sense_{MONITOR_ID}_daily_energy")
|
||||
assert state is not None
|
||||
assert state.state != STATE_UNAVAILABLE
|
||||
|
||||
mock_sense.update_trend_data.side_effect = exception
|
||||
|
||||
freezer.tick(timedelta(seconds=TREND_UPDATE_RATE))
|
||||
async_fire_time_changed(hass, freezer())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get(f"sensor.sense_{MONITOR_ID}_daily_energy")
|
||||
assert state.state == STATE_UNAVAILABLE
|
||||
|
||||
mock_sense.update_trend_data.side_effect = None
|
||||
|
||||
freezer.tick(timedelta(seconds=TREND_UPDATE_RATE))
|
||||
async_fire_time_changed(hass, freezer())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get(f"sensor.sense_{MONITOR_ID}_daily_energy")
|
||||
assert state.state != STATE_UNAVAILABLE
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exception",
|
||||
[
|
||||
SenseAPIException("api error"),
|
||||
SenseAPITimeoutException("timeout"),
|
||||
TimeoutError("timeout"),
|
||||
SenseWebsocketException("ws error"),
|
||||
socket.gaierror("addr info error"),
|
||||
],
|
||||
)
|
||||
async def test_realtime_coordinator_update_failure(
|
||||
hass: HomeAssistant,
|
||||
mock_sense: MagicMock,
|
||||
config_entry: MockConfigEntry,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
exception: Exception,
|
||||
) -> None:
|
||||
"""Test that errors from the realtime coordinator mark entities unavailable."""
|
||||
await setup_platform(hass, config_entry, Platform.SENSOR)
|
||||
|
||||
state = hass.states.get(f"sensor.sense_{MONITOR_ID}_energy")
|
||||
assert state is not None
|
||||
assert state.state != STATE_UNAVAILABLE
|
||||
|
||||
mock_sense.update_realtime.side_effect = exception
|
||||
|
||||
freezer.tick(timedelta(seconds=ACTIVE_UPDATE_RATE))
|
||||
async_fire_time_changed(hass, freezer())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get(f"sensor.sense_{MONITOR_ID}_energy")
|
||||
assert state.state == STATE_UNAVAILABLE
|
||||
|
||||
mock_sense.update_realtime.side_effect = None
|
||||
|
||||
freezer.tick(timedelta(seconds=ACTIVE_UPDATE_RATE))
|
||||
async_fire_time_changed(hass, freezer())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get(f"sensor.sense_{MONITOR_ID}_energy")
|
||||
assert state.state != STATE_UNAVAILABLE
|
||||
|
||||
@@ -39,6 +39,7 @@ DEVICE_FIXTURES = [
|
||||
"copper_water_meter_v03",
|
||||
"base_electric_meter",
|
||||
"smart_plug",
|
||||
"fibaro_dimmer_2",
|
||||
"vd_stv_2017_k",
|
||||
"c2c_arlo_pro_3_switch",
|
||||
"yale_push_button_deadbolt_lock",
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"components": {
|
||||
"button2": {
|
||||
"button": {
|
||||
"button": {
|
||||
"value": null
|
||||
},
|
||||
"numberOfButtons": {
|
||||
"value": null
|
||||
},
|
||||
"supportedButtonValues": {
|
||||
"value": null
|
||||
}
|
||||
}
|
||||
},
|
||||
"main": {
|
||||
"powerMeter": {
|
||||
"power": {
|
||||
"value": 0.0,
|
||||
"unit": "W",
|
||||
"timestamp": "2026-05-28T12:21:31.639Z"
|
||||
}
|
||||
},
|
||||
"energyMeter": {
|
||||
"energy": {
|
||||
"value": 36.89,
|
||||
"unit": "kWh",
|
||||
"timestamp": "2026-05-28T12:32:57.766Z"
|
||||
}
|
||||
},
|
||||
"switchLevel": {
|
||||
"levelRange": {
|
||||
"value": null
|
||||
},
|
||||
"level": {
|
||||
"value": 0,
|
||||
"unit": "%",
|
||||
"timestamp": "2026-05-28T10:20:37.674Z"
|
||||
}
|
||||
},
|
||||
"legendabsolute60149.forcedOnLevel": {
|
||||
"forcedOnLevel": {
|
||||
"value": 5,
|
||||
"unit": "%",
|
||||
"timestamp": "2026-05-21T15:10:35.371Z"
|
||||
}
|
||||
},
|
||||
"refresh": {},
|
||||
"switch": {
|
||||
"switch": {
|
||||
"value": "off",
|
||||
"timestamp": "2026-05-28T10:20:37.616Z"
|
||||
}
|
||||
}
|
||||
},
|
||||
"button1": {
|
||||
"button": {
|
||||
"button": {
|
||||
"value": null
|
||||
},
|
||||
"numberOfButtons": {
|
||||
"value": null
|
||||
},
|
||||
"supportedButtonValues": {
|
||||
"value": null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"deviceId": "df9f5405-f930-46aa-9693-14c570b35c83",
|
||||
"name": "fibaro-dimmer-2",
|
||||
"label": "Dimmer entr\u00e9 1 1",
|
||||
"manufacturerName": "SmartThingsCommunity",
|
||||
"presentationId": "b1b79065-1923-3e7a-b016-9abcc3d1d416",
|
||||
"deviceManufacturerCode": "010F-0102-1001",
|
||||
"locationId": "c85a9f8a-5d2e-4cdd-8bdb-bc49ba4a3544",
|
||||
"ownerId": "7b68139b-d068-45d8-bf27-961320350024",
|
||||
"roomId": "f4084bf6-2985-47cc-b3c9-3907d098ec0c",
|
||||
"components": [
|
||||
{
|
||||
"id": "main",
|
||||
"label": "main",
|
||||
"capabilities": [
|
||||
{
|
||||
"id": "switch",
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"id": "switchLevel",
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"id": "powerMeter",
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"id": "energyMeter",
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"id": "legendabsolute60149.forcedOnLevel",
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"id": "refresh",
|
||||
"version": 1
|
||||
}
|
||||
],
|
||||
"categories": [
|
||||
{
|
||||
"name": "Switch",
|
||||
"categoryType": "manufacturer"
|
||||
}
|
||||
],
|
||||
"optional": false
|
||||
},
|
||||
{
|
||||
"id": "button1",
|
||||
"label": "button1",
|
||||
"capabilities": [
|
||||
{
|
||||
"id": "button",
|
||||
"version": 1
|
||||
}
|
||||
],
|
||||
"categories": [
|
||||
{
|
||||
"name": "RemoteController",
|
||||
"categoryType": "manufacturer"
|
||||
}
|
||||
],
|
||||
"optional": false
|
||||
},
|
||||
{
|
||||
"id": "button2",
|
||||
"label": "button2",
|
||||
"capabilities": [
|
||||
{
|
||||
"id": "button",
|
||||
"version": 1
|
||||
}
|
||||
],
|
||||
"categories": [
|
||||
{
|
||||
"name": "RemoteController",
|
||||
"categoryType": "manufacturer"
|
||||
}
|
||||
],
|
||||
"optional": false
|
||||
}
|
||||
],
|
||||
"createTime": "2023-04-23T06:35:16.202Z",
|
||||
"parentDeviceId": "4869d882-e898-40c3-a198-7611b72187a5",
|
||||
"profile": {
|
||||
"id": "c6edf569-c7bb-38e7-a442-fe397ebe0cae"
|
||||
},
|
||||
"zwave": {
|
||||
"networkId": "0A",
|
||||
"driverId": "17c05c19-f008-42e2-aa12-f12f1aae5612",
|
||||
"executingLocally": true,
|
||||
"hubId": "4869d882-e898-40c3-a198-7611b72187a5",
|
||||
"networkSecurityLevel": "ZWAVE_S0_LEGACY",
|
||||
"provisioningState": "NONFUNCTIONAL",
|
||||
"manufacturerId": 271,
|
||||
"productType": 258,
|
||||
"productId": 4097
|
||||
},
|
||||
"type": "ZWAVE",
|
||||
"restrictionTier": 0,
|
||||
"allowed": null,
|
||||
"executionContext": "LOCAL",
|
||||
"relationships": []
|
||||
}
|
||||
],
|
||||
"_links": {}
|
||||
}
|
||||
@@ -1,4 +1,114 @@
|
||||
# serializer version: 1
|
||||
# name: test_all_entities[fibaro_dimmer_2][event.dimmer_entre_1_1_button1-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
'event_types': None,
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'event',
|
||||
'entity_category': None,
|
||||
'entity_id': 'event.dimmer_entre_1_1_button1',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'button1',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <EventDeviceClass.BUTTON: 'button'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'button1',
|
||||
'platform': 'smartthings',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'button',
|
||||
'unique_id': 'df9f5405-f930-46aa-9693-14c570b35c83_button1_button',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[fibaro_dimmer_2][event.dimmer_entre_1_1_button1-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'device_class': 'button',
|
||||
'event_type': None,
|
||||
'event_types': None,
|
||||
'friendly_name': 'Dimmer entré 1 1 button1',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'event.dimmer_entre_1_1_button1',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'unknown',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[fibaro_dimmer_2][event.dimmer_entre_1_1_button2-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
'event_types': None,
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'event',
|
||||
'entity_category': None,
|
||||
'entity_id': 'event.dimmer_entre_1_1_button2',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'button2',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <EventDeviceClass.BUTTON: 'button'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'button2',
|
||||
'platform': 'smartthings',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'button',
|
||||
'unique_id': 'df9f5405-f930-46aa-9693-14c570b35c83_button2_button',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[fibaro_dimmer_2][event.dimmer_entre_1_1_button2-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'device_class': 'button',
|
||||
'event_type': None,
|
||||
'event_types': None,
|
||||
'friendly_name': 'Dimmer entré 1 1 button2',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'event.dimmer_entre_1_1_button2',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'unknown',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[heatit_zpushwall][event.livingroom_smart_switch_button1-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
|
||||
@@ -1828,6 +1828,37 @@
|
||||
'via_device_id': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_devices[fibaro_dimmer_2]
|
||||
DeviceRegistryEntrySnapshot({
|
||||
'area_id': None,
|
||||
'config_entries': <ANY>,
|
||||
'config_entries_subentries': <ANY>,
|
||||
'configuration_url': 'https://account.smartthings.com',
|
||||
'connections': set({
|
||||
}),
|
||||
'disabled_by': None,
|
||||
'entry_type': None,
|
||||
'hw_version': None,
|
||||
'id': <ANY>,
|
||||
'identifiers': set({
|
||||
tuple(
|
||||
'smartthings',
|
||||
'df9f5405-f930-46aa-9693-14c570b35c83',
|
||||
),
|
||||
}),
|
||||
'labels': set({
|
||||
}),
|
||||
'manufacturer': None,
|
||||
'model': None,
|
||||
'model_id': None,
|
||||
'name': 'Dimmer entré 1 1',
|
||||
'name_by_user': None,
|
||||
'primary_config_entry': <ANY>,
|
||||
'serial_number': None,
|
||||
'sw_version': None,
|
||||
'via_device_id': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_devices[gas_detector]
|
||||
DeviceRegistryEntrySnapshot({
|
||||
'area_id': None,
|
||||
|
||||
@@ -542,6 +542,66 @@
|
||||
'state': 'on',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[fibaro_dimmer_2][light.dimmer_entre_1_1-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
'supported_color_modes': list([
|
||||
<ColorMode.BRIGHTNESS: 'brightness'>,
|
||||
]),
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'light',
|
||||
'entity_category': None,
|
||||
'entity_id': 'light.dimmer_entre_1_1',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': None,
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': None,
|
||||
'original_icon': None,
|
||||
'original_name': None,
|
||||
'platform': 'smartthings',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': <LightEntityFeature: 32>,
|
||||
'translation_key': None,
|
||||
'unique_id': 'df9f5405-f930-46aa-9693-14c570b35c83_main',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[fibaro_dimmer_2][light.dimmer_entre_1_1-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'brightness': None,
|
||||
'color_mode': None,
|
||||
'friendly_name': 'Dimmer entré 1 1',
|
||||
'supported_color_modes': list([
|
||||
<ColorMode.BRIGHTNESS: 'brightness'>,
|
||||
]),
|
||||
'supported_features': <LightEntityFeature: 32>,
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'light.dimmer_entre_1_1',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'off',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[ge_in_wall_smart_dimmer][light.theater_basement_exit_light-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
|
||||
@@ -19725,6 +19725,122 @@
|
||||
'state': 'unknown',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[fibaro_dimmer_2][sensor.dimmer_entre_1_1_energy-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
'state_class': <SensorStateClass.TOTAL_INCREASING: 'total_increasing'>,
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.dimmer_entre_1_1_energy',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Energy',
|
||||
'options': dict({
|
||||
'sensor': dict({
|
||||
'suggested_display_precision': 2,
|
||||
}),
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.ENERGY: 'energy'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Energy',
|
||||
'platform': 'smartthings',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': None,
|
||||
'unique_id': 'df9f5405-f930-46aa-9693-14c570b35c83_main_energyMeter_energy_energy',
|
||||
'unit_of_measurement': 'kWh',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[fibaro_dimmer_2][sensor.dimmer_entre_1_1_energy-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'device_class': 'energy',
|
||||
'friendly_name': 'Dimmer entré 1 1 Energy',
|
||||
'state_class': <SensorStateClass.TOTAL_INCREASING: 'total_increasing'>,
|
||||
'unit_of_measurement': 'kWh',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.dimmer_entre_1_1_energy',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '36.89',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[fibaro_dimmer_2][sensor.dimmer_entre_1_1_power-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.dimmer_entre_1_1_power',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Power',
|
||||
'options': dict({
|
||||
'sensor': dict({
|
||||
'suggested_display_precision': 0,
|
||||
}),
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.POWER: 'power'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Power',
|
||||
'platform': 'smartthings',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': None,
|
||||
'unique_id': 'df9f5405-f930-46aa-9693-14c570b35c83_main_powerMeter_power_power',
|
||||
'unit_of_measurement': 'W',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[fibaro_dimmer_2][sensor.dimmer_entre_1_1_power-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'device_class': 'power',
|
||||
'friendly_name': 'Dimmer entré 1 1 Power',
|
||||
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
|
||||
'unit_of_measurement': 'W',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.dimmer_entre_1_1_power',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '0.0',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[gas_detector][sensor.gas_detector_link_quality-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
|
||||
@@ -1378,6 +1378,7 @@ async def test_async_setup_entry_failed(
|
||||
mock_bot.side_effect = InvalidToken("mock invalid token error")
|
||||
|
||||
with pytest.raises(ConfigEntryAuthFailed) as err:
|
||||
# pylint: disable-next=home-assistant-tests-direct-async-setup-entry
|
||||
await async_setup_entry(hass, mock_broadcast_config_entry)
|
||||
|
||||
await hass.async_block_till_done()
|
||||
|
||||
@@ -229,6 +229,7 @@ async def test_thermopro_restores_entities_on_restart_behavior(
|
||||
await hass.async_block_till_done()
|
||||
|
||||
# Manually set up sensor platform with our callback
|
||||
# pylint: disable-next=home-assistant-tests-direct-platform-async-setup-entry
|
||||
await thermopro_sensor.async_setup_entry(hass, entry1, add_entities_first)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
@@ -242,6 +243,7 @@ async def test_thermopro_restores_entities_on_restart_behavior(
|
||||
assert await hass.config_entries.async_setup(entry2.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
# pylint: disable-next=home-assistant-tests-direct-platform-async-setup-entry
|
||||
await thermopro_sensor.async_setup_entry(hass, entry2, add_entities_second)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
|
||||
@@ -96,4 +96,5 @@ async def test_setup_requires_data_api_reauth(hass: HomeAssistant) -> None:
|
||||
)
|
||||
|
||||
with pytest.raises(ConfigEntryAuthFailed):
|
||||
# pylint: disable-next=home-assistant-tests-direct-async-setup-entry
|
||||
await async_setup_entry(hass, entry)
|
||||
|
||||
@@ -54,6 +54,7 @@ async def test_async_setup_entry__no_devices(
|
||||
) -> None:
|
||||
"""Test setup connects to vesync and creates empty config when no devices."""
|
||||
with patch.object(hass.config_entries, "async_forward_entry_setups") as setups_mock:
|
||||
# pylint: disable-next=home-assistant-tests-direct-async-setup-entry
|
||||
assert await async_setup_entry(hass, config_entry)
|
||||
# Assert platforms loaded
|
||||
await hass.async_block_till_done()
|
||||
@@ -81,6 +82,7 @@ async def test_async_setup_entry__loads_fans(
|
||||
manager._dev_list["fans"].append(fan)
|
||||
|
||||
with patch.object(hass.config_entries, "async_forward_entry_setups") as setups_mock:
|
||||
# pylint: disable-next=home-assistant-tests-direct-async-setup-entry
|
||||
assert await async_setup_entry(hass, config_entry)
|
||||
# Assert platforms loaded
|
||||
await hass.async_block_till_done()
|
||||
|
||||
@@ -1,14 +1,28 @@
|
||||
"""The tests for the location automation."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components import automation, zone
|
||||
from homeassistant.const import ATTR_ENTITY_ID, ENTITY_MATCH_ALL, SERVICE_TURN_OFF
|
||||
from homeassistant.core import Context, HomeAssistant, ServiceCall
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
from homeassistant.helpers.trigger import async_validate_trigger_config
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from tests.common import mock_component
|
||||
from tests.components.common import (
|
||||
TriggerStateDescription,
|
||||
assert_trigger_behavior_all,
|
||||
assert_trigger_behavior_each,
|
||||
assert_trigger_behavior_first,
|
||||
assert_trigger_options_supported,
|
||||
parametrize_target_entities,
|
||||
parametrize_trigger_states,
|
||||
target_entities,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
@@ -343,10 +357,7 @@ async def test_unknown_zone(
|
||||
},
|
||||
)
|
||||
|
||||
assert (
|
||||
"Automation 'My Automation' is referencing non-existing zone"
|
||||
" 'zone.no_such_zone' in a zone trigger" not in caplog.text
|
||||
)
|
||||
assert "Non-existing zone 'zone.no_such_zone' in a zone trigger" not in caplog.text
|
||||
|
||||
hass.states.async_set(
|
||||
"test.entity",
|
||||
@@ -356,7 +367,192 @@ async def test_unknown_zone(
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert (
|
||||
"Automation 'My Automation' is referencing non-existing zone"
|
||||
" 'zone.no_such_zone' in a zone trigger" in caplog.text
|
||||
assert "Non-existing zone 'zone.no_such_zone' in a zone trigger" in caplog.text
|
||||
|
||||
|
||||
# --- New-style zone trigger tests ---
|
||||
|
||||
ZONE_HOME = "zone.home"
|
||||
ZONE_WORK = "zone.work"
|
||||
IN_ZONES_HOME = {"in_zones": [ZONE_HOME]}
|
||||
IN_ZONES_WORK = {"in_zones": [ZONE_WORK]}
|
||||
IN_ZONES_NONE: dict[str, list[str]] = {"in_zones": []}
|
||||
TRIGGER_ZONE = ZONE_HOME
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("trigger_key", "base_options", "supports_behavior", "supports_duration"),
|
||||
[
|
||||
("zone.entered", {"zone": TRIGGER_ZONE}, True, True),
|
||||
("zone.left", {"zone": TRIGGER_ZONE}, True, True),
|
||||
],
|
||||
)
|
||||
async def test_zone_trigger_options_validation(
|
||||
hass: HomeAssistant,
|
||||
trigger_key: str,
|
||||
base_options: dict[str, Any] | None,
|
||||
supports_behavior: bool,
|
||||
supports_duration: bool,
|
||||
) -> None:
|
||||
"""Test that zone triggers support the expected options."""
|
||||
await assert_trigger_options_supported(
|
||||
hass,
|
||||
trigger_key,
|
||||
base_options,
|
||||
supports_behavior=supports_behavior,
|
||||
supports_duration=supports_duration,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("trigger_key", ["zone.entered", "zone.left"])
|
||||
async def test_zone_trigger_rejects_non_zone_entity_id(
|
||||
hass: HomeAssistant, trigger_key: str
|
||||
) -> None:
|
||||
"""Test that the zone option must reference entities in the zone domain."""
|
||||
with pytest.raises(vol.Invalid):
|
||||
await async_validate_trigger_config(
|
||||
hass,
|
||||
[
|
||||
{
|
||||
"platform": trigger_key,
|
||||
"target": {"entity_id": "person.alice"},
|
||||
"options": {"zone": "person.alice"},
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def target_zone_entities(
|
||||
hass: HomeAssistant, domain: str
|
||||
) -> dict[str, list[str]]:
|
||||
"""Create multiple zone-trackable entities associated with different targets."""
|
||||
return await target_entities(hass, domain, domain_excluded="sensor")
|
||||
|
||||
|
||||
_ZONE_TRIGGER_STATES = [
|
||||
*parametrize_trigger_states(
|
||||
trigger="zone.entered",
|
||||
trigger_options={"zone": TRIGGER_ZONE},
|
||||
target_states=[
|
||||
("home", IN_ZONES_HOME),
|
||||
],
|
||||
other_states=[
|
||||
("not_home", IN_ZONES_NONE),
|
||||
("Work", IN_ZONES_WORK),
|
||||
],
|
||||
),
|
||||
*parametrize_trigger_states(
|
||||
trigger="zone.left",
|
||||
trigger_options={"zone": TRIGGER_ZONE},
|
||||
target_states=[
|
||||
("not_home", IN_ZONES_NONE),
|
||||
("Work", IN_ZONES_WORK),
|
||||
],
|
||||
other_states=[
|
||||
("home", IN_ZONES_HOME),
|
||||
],
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def _parametrize_zone_target_entities() -> list[tuple[dict[str, Any], str, int, str]]:
|
||||
"""Parametrize target entities for all supported zone trigger domains."""
|
||||
return [
|
||||
(*params, domain)
|
||||
for domain in ("person", "device_tracker")
|
||||
for params in parametrize_target_entities(domain)
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("trigger_target_config", "entity_id", "entities_in_target", "domain"),
|
||||
_parametrize_zone_target_entities(),
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
("trigger", "trigger_options", "states"),
|
||||
_ZONE_TRIGGER_STATES,
|
||||
)
|
||||
async def test_zone_trigger_behavior_each(
|
||||
hass: HomeAssistant,
|
||||
target_zone_entities: dict[str, list[str]],
|
||||
trigger_target_config: dict[str, Any],
|
||||
entity_id: str,
|
||||
entities_in_target: int,
|
||||
trigger: str,
|
||||
trigger_options: dict[str, Any],
|
||||
states: list[TriggerStateDescription],
|
||||
) -> None:
|
||||
"""Test zone triggers fire when any targeted entity changes."""
|
||||
await assert_trigger_behavior_each(
|
||||
hass,
|
||||
target_entities=target_zone_entities,
|
||||
trigger_target_config=trigger_target_config,
|
||||
entity_id=entity_id,
|
||||
entities_in_target=entities_in_target,
|
||||
trigger=trigger,
|
||||
trigger_options=trigger_options,
|
||||
states=states,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("trigger_target_config", "entity_id", "entities_in_target", "domain"),
|
||||
_parametrize_zone_target_entities(),
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
("trigger", "trigger_options", "states"),
|
||||
_ZONE_TRIGGER_STATES,
|
||||
)
|
||||
async def test_zone_trigger_behavior_first(
|
||||
hass: HomeAssistant,
|
||||
target_zone_entities: dict[str, list[str]],
|
||||
trigger_target_config: dict[str, Any],
|
||||
entity_id: str,
|
||||
entities_in_target: int,
|
||||
trigger: str,
|
||||
trigger_options: dict[str, Any],
|
||||
states: list[TriggerStateDescription],
|
||||
) -> None:
|
||||
"""Test zone triggers fire when first targeted entity changes."""
|
||||
await assert_trigger_behavior_first(
|
||||
hass,
|
||||
target_entities=target_zone_entities,
|
||||
trigger_target_config=trigger_target_config,
|
||||
entity_id=entity_id,
|
||||
entities_in_target=entities_in_target,
|
||||
trigger=trigger,
|
||||
trigger_options=trigger_options,
|
||||
states=states,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("trigger_target_config", "entity_id", "entities_in_target", "domain"),
|
||||
_parametrize_zone_target_entities(),
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
("trigger", "trigger_options", "states"),
|
||||
_ZONE_TRIGGER_STATES,
|
||||
)
|
||||
async def test_zone_trigger_behavior_all(
|
||||
hass: HomeAssistant,
|
||||
target_zone_entities: dict[str, list[str]],
|
||||
trigger_target_config: dict[str, Any],
|
||||
entity_id: str,
|
||||
entities_in_target: int,
|
||||
trigger: str,
|
||||
trigger_options: dict[str, Any],
|
||||
states: list[TriggerStateDescription],
|
||||
) -> None:
|
||||
"""Test zone triggers fire when last targeted entity changes."""
|
||||
await assert_trigger_behavior_all(
|
||||
hass,
|
||||
target_entities=target_zone_entities,
|
||||
trigger_target_config=trigger_target_config,
|
||||
entity_id=entity_id,
|
||||
entities_in_target=entities_in_target,
|
||||
trigger=trigger,
|
||||
trigger_options=trigger_options,
|
||||
states=states,
|
||||
)
|
||||
|
||||
@@ -31,6 +31,8 @@ from homeassistant.util.dt import utc_from_timestamp, utcnow
|
||||
from tests.common import (
|
||||
ANY,
|
||||
MockConfigEntry,
|
||||
MockEntity,
|
||||
MockEntityPlatform,
|
||||
RegistryEntryWithDefaults,
|
||||
async_capture_events,
|
||||
async_fire_time_changed,
|
||||
@@ -3651,21 +3653,43 @@ async def test_unique_id_non_string(
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("create_kwargs", "migrate_kwargs", "new_subentry_id"),
|
||||
("create_kwargs", "migrate_kwargs", "new_subentry_id", "match"),
|
||||
[
|
||||
({}, {}, None),
|
||||
({"config_subentry_id": None}, {}, None),
|
||||
({}, {"new_config_subentry_id": None}, None),
|
||||
({}, {"new_config_subentry_id": "mock-subentry-id-2"}, "mock-subentry-id-2"),
|
||||
(
|
||||
{},
|
||||
{},
|
||||
None,
|
||||
"Unique id '1234' is already in use by 'light.light'",
|
||||
),
|
||||
(
|
||||
{"config_subentry_id": None},
|
||||
{},
|
||||
None,
|
||||
"Unique id '1234' is already in use by 'light.light'",
|
||||
),
|
||||
(
|
||||
{},
|
||||
{"new_config_subentry_id": None},
|
||||
None,
|
||||
"Unique id '1234' is already in use by 'light.light'",
|
||||
),
|
||||
(
|
||||
{},
|
||||
{"new_config_subentry_id": "mock-subentry-id-2"},
|
||||
"mock-subentry-id-2",
|
||||
"Can't change config entry without changing subentry",
|
||||
),
|
||||
(
|
||||
{"config_subentry_id": "mock-subentry-id-1"},
|
||||
{"new_config_subentry_id": None},
|
||||
None,
|
||||
"Unique id '1234' is already in use by 'light.light'",
|
||||
),
|
||||
(
|
||||
{"config_subentry_id": "mock-subentry-id-1"},
|
||||
{"new_config_subentry_id": "mock-subentry-id-2"},
|
||||
"mock-subentry-id-2",
|
||||
"Can't change config entry without changing subentry",
|
||||
),
|
||||
],
|
||||
)
|
||||
@@ -3675,6 +3699,7 @@ def test_migrate_entity_to_new_platform(
|
||||
create_kwargs: dict,
|
||||
migrate_kwargs: dict,
|
||||
new_subentry_id: str | None,
|
||||
match: str,
|
||||
) -> None:
|
||||
"""Test migrate_entity_to_new_platform."""
|
||||
orig_config_entry = MockConfigEntry(
|
||||
@@ -3747,7 +3772,7 @@ def test_migrate_entity_to_new_platform(
|
||||
assert new_entry.platform == "hue2"
|
||||
|
||||
# Test nonexisting entity
|
||||
with pytest.raises(KeyError):
|
||||
with pytest.raises(KeyError, match="'light.not_a_real_light'"):
|
||||
entity_registry.async_update_entity_platform(
|
||||
"light.not_a_real_light",
|
||||
"hue2",
|
||||
@@ -3756,15 +3781,16 @@ def test_migrate_entity_to_new_platform(
|
||||
)
|
||||
|
||||
# Test migrate entity without new config entry ID
|
||||
with pytest.raises(ValueError):
|
||||
with pytest.raises(
|
||||
ValueError,
|
||||
match="new_config_entry_id required because light.light is already linked to a config entry",
|
||||
):
|
||||
entity_registry.async_update_entity_platform(
|
||||
"light.light",
|
||||
"hue3",
|
||||
)
|
||||
|
||||
# Test entity with a state
|
||||
hass.states.async_set("light.light", "on")
|
||||
with pytest.raises(ValueError):
|
||||
with pytest.raises(ValueError, match=match):
|
||||
entity_registry.async_update_entity_platform(
|
||||
"light.light",
|
||||
"hue2",
|
||||
@@ -3773,13 +3799,14 @@ def test_migrate_entity_to_new_platform(
|
||||
)
|
||||
|
||||
|
||||
def test_migrate_entity_to_new_platform_error_handling(
|
||||
async def test_migrate_entity_to_new_platform_error_handling(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: er.EntityRegistry,
|
||||
) -> None:
|
||||
"""Test migrate_entity_to_new_platform."""
|
||||
platform = MockEntityPlatform(hass, domain="light", platform_name="hue")
|
||||
orig_config_entry = MockConfigEntry(
|
||||
domain="light",
|
||||
domain="hue",
|
||||
subentries_data=[
|
||||
config_entries.ConfigSubentryData(
|
||||
data={},
|
||||
@@ -3791,25 +3818,14 @@ def test_migrate_entity_to_new_platform_error_handling(
|
||||
],
|
||||
)
|
||||
orig_config_entry.add_to_hass(hass)
|
||||
orig_unique_id = "5678"
|
||||
platform.config_entry = orig_config_entry
|
||||
entity = MockEntity(name="Light entity", entity_id="light.light", unique_id="5678")
|
||||
await platform.async_add_entities([entity], config_subentry_id="mock-subentry-id-1")
|
||||
|
||||
orig_entry = entity_registry.async_get_or_create(
|
||||
"light",
|
||||
"hue",
|
||||
orig_unique_id,
|
||||
suggested_object_id="light",
|
||||
config_entry=orig_config_entry,
|
||||
config_subentry_id="mock-subentry-id-1",
|
||||
disabled_by=er.RegistryEntryDisabler.USER,
|
||||
entity_category=EntityCategory.CONFIG,
|
||||
original_device_class="mock-device-class",
|
||||
original_icon="initial-original_icon",
|
||||
original_name="initial-original_name",
|
||||
)
|
||||
assert entity_registry.async_get("light.light") is orig_entry
|
||||
assert entity_registry.async_get("light.light") is not None
|
||||
|
||||
new_config_entry = MockConfigEntry(
|
||||
domain="light",
|
||||
domain="hue2",
|
||||
subentries_data=[
|
||||
config_entries.ConfigSubentryData(
|
||||
data={},
|
||||
@@ -3832,6 +3848,18 @@ def test_migrate_entity_to_new_platform_error_handling(
|
||||
new_config_entry_id=new_config_entry.entry_id,
|
||||
)
|
||||
|
||||
with pytest.raises(
|
||||
ValueError, match="Only entities that haven't been loaded can be migrated"
|
||||
):
|
||||
entity_registry.async_update_entity_platform(
|
||||
"light.light",
|
||||
"hue2",
|
||||
new_unique_id=new_unique_id,
|
||||
new_config_entry_id=new_config_entry.entry_id,
|
||||
)
|
||||
|
||||
await platform.async_reset()
|
||||
|
||||
# Test migrate entity without new config entry ID
|
||||
with pytest.raises(
|
||||
ValueError,
|
||||
@@ -3843,29 +3871,17 @@ def test_migrate_entity_to_new_platform_error_handling(
|
||||
):
|
||||
entity_registry.async_update_entity_platform(
|
||||
"light.light",
|
||||
"hue3",
|
||||
"hue2",
|
||||
)
|
||||
|
||||
# Test migrate entity without new config subentry ID
|
||||
with pytest.raises(
|
||||
ValueError,
|
||||
match="Can't change config entry without changing subentry",
|
||||
):
|
||||
entity_registry.async_update_entity_platform(
|
||||
"light.light",
|
||||
"hue3",
|
||||
new_config_entry_id=new_config_entry.entry_id,
|
||||
)
|
||||
|
||||
# Test entity with a state
|
||||
hass.states.async_set("light.light", "on")
|
||||
with pytest.raises(
|
||||
ValueError, match="Only entities that haven't been loaded can be migrated"
|
||||
):
|
||||
entity_registry.async_update_entity_platform(
|
||||
"light.light",
|
||||
"hue2",
|
||||
new_unique_id=new_unique_id,
|
||||
new_config_entry_id=new_config_entry.entry_id,
|
||||
)
|
||||
|
||||
|
||||
@@ -4639,13 +4639,33 @@ async def test_entity_trigger_duration_cancelled_on_invalid_state(
|
||||
pytest.param(
|
||||
{
|
||||
"platform": "zone",
|
||||
"entity_id": ["person.a"],
|
||||
"zone": "zone.home",
|
||||
"event": "enter",
|
||||
"options": {
|
||||
"entity_id": ["person.a"],
|
||||
"zone": "zone.home",
|
||||
"event": "enter",
|
||||
},
|
||||
},
|
||||
["person.a", "zone.home"],
|
||||
id="zone-legacy",
|
||||
),
|
||||
pytest.param(
|
||||
{
|
||||
"platform": "zone.entered",
|
||||
"target": {"entity_id": ["person.a", "device_tracker.b"]},
|
||||
"options": {"zone": "zone.home"},
|
||||
},
|
||||
["person.a", "device_tracker.b", "zone.home"],
|
||||
id="zone-entered-modern",
|
||||
),
|
||||
pytest.param(
|
||||
{
|
||||
"platform": "zone.left",
|
||||
"target": {"entity_id": "person.a"},
|
||||
"options": {"zone": "zone.home"},
|
||||
},
|
||||
["person.a", "zone.home"],
|
||||
id="zone-left-modern",
|
||||
),
|
||||
pytest.param(
|
||||
{"platform": "geo_location", "zone": "zone.home"},
|
||||
["zone.home"],
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Tests for the direct async_setup_entry checker."""
|
||||
|
||||
import astroid
|
||||
from pylint.testutils import UnittestLinter
|
||||
from pylint.utils.ast_walker import ASTWalker
|
||||
from pylint_home_assistant.checkers.tests.direct_async_setup_entry import (
|
||||
DirectAsyncSetupEntry,
|
||||
)
|
||||
import pytest
|
||||
|
||||
from tests.pylint import assert_no_messages
|
||||
|
||||
# Pre-load so astroid can resolve ``async_setup_entry`` in parsed snippets.
|
||||
astroid.MANAGER.ast_from_module_name("homeassistant.components.sun")
|
||||
astroid.MANAGER.ast_from_module_name("homeassistant.components.sun.sensor")
|
||||
|
||||
|
||||
@pytest.fixture(name="checker")
|
||||
def checker_fixture(linter: UnittestLinter) -> DirectAsyncSetupEntry:
|
||||
"""Fixture to provide a direct async_setup_entry checker."""
|
||||
return DirectAsyncSetupEntry(linter)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("code", "module_name"),
|
||||
[
|
||||
pytest.param(
|
||||
"""
|
||||
async def test_setup(hass):
|
||||
await hass.config_entries.async_setup(entry.entry_id)
|
||||
""",
|
||||
"tests.components.sun.test_init",
|
||||
id="proper_setup_call",
|
||||
),
|
||||
pytest.param(
|
||||
"""
|
||||
from homeassistant.components.sun import async_setup_entry
|
||||
|
||||
async def test_setup(hass, mock_config_entry):
|
||||
await async_setup_entry(hass, mock_config_entry)
|
||||
""",
|
||||
"homeassistant.components.sun",
|
||||
id="not_a_test_module",
|
||||
),
|
||||
pytest.param(
|
||||
"""
|
||||
async def test_setup(hass, mock_config_entry):
|
||||
await some_local.async_setup_entry(hass, mock_config_entry)
|
||||
""",
|
||||
"tests.components.sun.test_init",
|
||||
id="unresolved_attribute_call",
|
||||
),
|
||||
pytest.param(
|
||||
"""
|
||||
async def async_setup_entry(hass, entry):
|
||||
return True
|
||||
|
||||
async def test_setup(hass, entry):
|
||||
await async_setup_entry(hass, entry)
|
||||
""",
|
||||
"tests.components.sun.test_init",
|
||||
id="local_async_setup_entry_not_an_integration",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_no_warning(
|
||||
linter: UnittestLinter,
|
||||
checker: DirectAsyncSetupEntry,
|
||||
code: str,
|
||||
module_name: str,
|
||||
) -> None:
|
||||
"""Test cases that should not trigger a warning."""
|
||||
root_node = astroid.parse(code, module_name)
|
||||
walker = ASTWalker(linter)
|
||||
walker.add_checker(checker)
|
||||
|
||||
with assert_no_messages(linter):
|
||||
walker.walk(root_node)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("code", "module_name", "expected_msg"),
|
||||
[
|
||||
pytest.param(
|
||||
"""
|
||||
from homeassistant.components.sun import async_setup_entry
|
||||
|
||||
async def test_setup(hass, mock_config_entry):
|
||||
await async_setup_entry(hass, mock_config_entry)
|
||||
""",
|
||||
"tests.components.sun.test_init",
|
||||
"home-assistant-tests-direct-async-setup-entry",
|
||||
id="direct_name_call_from_init",
|
||||
),
|
||||
pytest.param(
|
||||
"""
|
||||
from homeassistant.components import sun
|
||||
|
||||
async def test_setup(hass, mock_config_entry):
|
||||
await sun.async_setup_entry(hass, mock_config_entry)
|
||||
""",
|
||||
"tests.components.sun.test_init",
|
||||
"home-assistant-tests-direct-async-setup-entry",
|
||||
id="attribute_call_from_init",
|
||||
),
|
||||
pytest.param(
|
||||
"""
|
||||
from homeassistant.components.sun.sensor import async_setup_entry
|
||||
|
||||
async def test_setup(hass, mock_config_entry, add_entities):
|
||||
await async_setup_entry(hass, mock_config_entry, add_entities)
|
||||
""",
|
||||
"tests.components.sun.test_sensor",
|
||||
"home-assistant-tests-direct-platform-async-setup-entry",
|
||||
id="direct_call_from_platform",
|
||||
),
|
||||
pytest.param(
|
||||
"""
|
||||
from homeassistant.components.sun import sensor
|
||||
|
||||
async def test_setup(hass, mock_config_entry, add_entities):
|
||||
await sensor.async_setup_entry(hass, mock_config_entry, add_entities)
|
||||
""",
|
||||
"tests.components.sun.test_sensor",
|
||||
"home-assistant-tests-direct-platform-async-setup-entry",
|
||||
id="attribute_call_from_platform",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_warning(
|
||||
linter: UnittestLinter,
|
||||
checker: DirectAsyncSetupEntry,
|
||||
code: str,
|
||||
module_name: str,
|
||||
expected_msg: str,
|
||||
) -> None:
|
||||
"""Test cases that should trigger a warning."""
|
||||
root_node = astroid.parse(code, module_name)
|
||||
walker = ASTWalker(linter)
|
||||
walker.add_checker(checker)
|
||||
walker.walk(root_node)
|
||||
|
||||
messages = linter.release_messages()
|
||||
assert len(messages) == 1
|
||||
assert messages[0].msg_id == expected_msg
|
||||
|
||||
|
||||
def test_multiple_calls_each_flagged(
|
||||
linter: UnittestLinter,
|
||||
checker: DirectAsyncSetupEntry,
|
||||
) -> None:
|
||||
"""Test that multiple direct calls are each flagged."""
|
||||
root_node = astroid.parse(
|
||||
"""
|
||||
from homeassistant.components.sun import async_setup_entry
|
||||
|
||||
async def test_a(hass, mock_config_entry):
|
||||
await async_setup_entry(hass, mock_config_entry)
|
||||
|
||||
async def test_b(hass, mock_config_entry):
|
||||
await async_setup_entry(hass, mock_config_entry)
|
||||
""",
|
||||
"tests.components.sun.test_init",
|
||||
)
|
||||
walker = ASTWalker(linter)
|
||||
walker.add_checker(checker)
|
||||
walker.walk(root_node)
|
||||
|
||||
messages = linter.release_messages()
|
||||
assert len(messages) == 2
|
||||
Reference in New Issue
Block a user