HomeAssistantType —> HomeAssistant for Integrations p* - s* (#49558)

This commit is contained in:
jan iversen 2021-04-22 19:58:02 +02:00 committed by GitHub
parent 9fe0c96474
commit c351098f04
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 144 additions and 158 deletions

View File

@ -18,10 +18,9 @@ from homeassistant.const import (
CONF_REGION, CONF_REGION,
CONF_TOKEN, CONF_TOKEN,
) )
from homeassistant.core import split_entity_id from homeassistant.core import HomeAssistant, split_entity_id
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv, entity_registry from homeassistant.helpers import config_validation as cv, entity_registry
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.util import location from homeassistant.util import location
from homeassistant.util.json import load_json, save_json from homeassistant.util.json import load_json, save_json
@ -157,7 +156,7 @@ def format_unique_id(creds, mac_address):
return f"{mac_address}_{suffix}" return f"{mac_address}_{suffix}"
def load_games(hass: HomeAssistantType, unique_id: str) -> dict: def load_games(hass: HomeAssistant, unique_id: str) -> dict:
"""Load games for sources.""" """Load games for sources."""
g_file = hass.config.path(GAMES_FILE.format(unique_id)) g_file = hass.config.path(GAMES_FILE.format(unique_id))
try: try:
@ -176,7 +175,7 @@ def load_games(hass: HomeAssistantType, unique_id: str) -> dict:
return games return games
def save_games(hass: HomeAssistantType, games: dict, unique_id: str): def save_games(hass: HomeAssistant, games: dict, unique_id: str):
"""Save games to file.""" """Save games to file."""
g_file = hass.config.path(GAMES_FILE.format(unique_id)) g_file = hass.config.path(GAMES_FILE.format(unique_id))
try: try:
@ -185,7 +184,7 @@ def save_games(hass: HomeAssistantType, games: dict, unique_id: str):
_LOGGER.error("Could not save game list, %s", error) _LOGGER.error("Could not save game list, %s", error)
def _reformat_data(hass: HomeAssistantType, games: dict, unique_id: str) -> dict: def _reformat_data(hass: HomeAssistant, games: dict, unique_id: str) -> dict:
"""Reformat data to correct format.""" """Reformat data to correct format."""
data_reformatted = False data_reformatted = False
@ -208,7 +207,7 @@ def _reformat_data(hass: HomeAssistantType, games: dict, unique_id: str) -> dict
return games return games
def service_handle(hass: HomeAssistantType): def service_handle(hass: HomeAssistant):
"""Handle for services.""" """Handle for services."""
async def async_service_command(call): async def async_service_command(call):

View File

@ -11,7 +11,7 @@ import time
from sqlalchemy.exc import OperationalError, SQLAlchemyError from sqlalchemy.exc import OperationalError, SQLAlchemyError
from sqlalchemy.orm.session import Session from sqlalchemy.orm.session import Session
from homeassistant.helpers.typing import HomeAssistantType from homeassistant.core import HomeAssistant
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
from .const import DATA_INSTANCE, SQLITE_URL_PREFIX from .const import DATA_INSTANCE, SQLITE_URL_PREFIX
@ -37,7 +37,7 @@ MAX_RESTART_TIME = timedelta(minutes=10)
@contextmanager @contextmanager
def session_scope( def session_scope(
*, hass: HomeAssistantType | None = None, session: Session | None = None *, hass: HomeAssistant | None = None, session: Session | None = None
) -> Generator[Session, None, None]: ) -> Generator[Session, None, None]:
"""Provide a transactional scope around a series of operations.""" """Provide a transactional scope around a series of operations."""
if session is None and hass is not None: if session is None and hass is not None:

View File

@ -17,6 +17,7 @@ from homeassistant.const import (
SERVICE_TURN_ON, SERVICE_TURN_ON,
STATE_ON, STATE_ON,
) )
from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.config_validation import ( # noqa: F401 from homeassistant.helpers.config_validation import ( # noqa: F401
PLATFORM_SCHEMA, PLATFORM_SCHEMA,
@ -25,7 +26,7 @@ from homeassistant.helpers.config_validation import ( # noqa: F401
) )
from homeassistant.helpers.entity import ToggleEntity from homeassistant.helpers.entity import ToggleEntity
from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.typing import ConfigType, HomeAssistantType from homeassistant.helpers.typing import ConfigType
from homeassistant.loader import bind_hass from homeassistant.loader import bind_hass
# mypy: allow-untyped-calls, allow-untyped-defs, no-check-untyped-defs # mypy: allow-untyped-calls, allow-untyped-defs, no-check-untyped-defs
@ -69,12 +70,12 @@ REMOTE_SERVICE_ACTIVITY_SCHEMA = make_entity_service_schema(
@bind_hass @bind_hass
def is_on(hass: HomeAssistantType, entity_id: str) -> bool: def is_on(hass: HomeAssistant, entity_id: str) -> bool:
"""Return if the remote is on based on the statemachine.""" """Return if the remote is on based on the statemachine."""
return hass.states.is_state(entity_id, STATE_ON) return hass.states.is_state(entity_id, STATE_ON)
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool: async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Track states and offer events for remotes.""" """Track states and offer events for remotes."""
component = hass.data[DOMAIN] = EntityComponent( component = hass.data[DOMAIN] = EntityComponent(
_LOGGER, DOMAIN, hass, SCAN_INTERVAL _LOGGER, DOMAIN, hass, SCAN_INTERVAL
@ -131,12 +132,12 @@ async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
return True return True
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up a config entry.""" """Set up a config entry."""
return await cast(EntityComponent, hass.data[DOMAIN]).async_setup_entry(entry) return await cast(EntityComponent, hass.data[DOMAIN]).async_setup_entry(entry)
async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry.""" """Unload a config entry."""
return await cast(EntityComponent, hass.data[DOMAIN]).async_unload_entry(entry) return await cast(EntityComponent, hass.data[DOMAIN]).async_unload_entry(entry)

View File

@ -3,13 +3,12 @@
from homeassistant.components.group import GroupIntegrationRegistry from homeassistant.components.group import GroupIntegrationRegistry
from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.core import callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.typing import HomeAssistantType
@callback @callback
def async_describe_on_off_states( def async_describe_on_off_states(
hass: HomeAssistantType, registry: GroupIntegrationRegistry hass: HomeAssistant, registry: GroupIntegrationRegistry
) -> None: ) -> None:
"""Describe group on off states.""" """Describe group on off states."""
registry.on_off_states({STATE_ON}, STATE_OFF) registry.on_off_states({STATE_ON}, STATE_OFF)

View File

@ -13,8 +13,7 @@ from homeassistant.const import (
STATE_OFF, STATE_OFF,
STATE_ON, STATE_ON,
) )
from homeassistant.core import Context, State from homeassistant.core import Context, HomeAssistant, State
from homeassistant.helpers.typing import HomeAssistantType
from . import DOMAIN from . import DOMAIN
@ -24,7 +23,7 @@ VALID_STATES = {STATE_ON, STATE_OFF}
async def _async_reproduce_state( async def _async_reproduce_state(
hass: HomeAssistantType, hass: HomeAssistant,
state: State, state: State,
*, *,
context: Context | None = None, context: Context | None = None,
@ -60,7 +59,7 @@ async def _async_reproduce_state(
async def async_reproduce_states( async def async_reproduce_states(
hass: HomeAssistantType, hass: HomeAssistant,
states: Iterable[State], states: Iterable[State],
*, *,
context: Context | None = None, context: Context | None = None,

View File

@ -13,9 +13,9 @@ from homeassistant.components.media_player import DOMAIN as MEDIA_PLAYER_DOMAIN
from homeassistant.components.remote import DOMAIN as REMOTE_DOMAIN from homeassistant.components.remote import DOMAIN as REMOTE_DOMAIN
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_NAME, CONF_HOST from homeassistant.const import ATTR_NAME, CONF_HOST
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.helpers.update_coordinator import ( from homeassistant.helpers.update_coordinator import (
CoordinatorEntity, CoordinatorEntity,
DataUpdateCoordinator, DataUpdateCoordinator,
@ -39,7 +39,7 @@ SCAN_INTERVAL = timedelta(seconds=15)
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Roku from a config entry.""" """Set up Roku from a config entry."""
hass.data.setdefault(DOMAIN, {}) hass.data.setdefault(DOMAIN, {})
coordinator = hass.data[DOMAIN].get(entry.entry_id) coordinator = hass.data[DOMAIN].get(entry.entry_id)
@ -57,7 +57,7 @@ async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool
return True return True
async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry.""" """Unload a config entry."""
unload_ok = all( unload_ok = all(
await asyncio.gather( await asyncio.gather(
@ -95,7 +95,7 @@ class RokuDataUpdateCoordinator(DataUpdateCoordinator[Device]):
def __init__( def __init__(
self, self,
hass: HomeAssistantType, hass: HomeAssistant,
*, *,
host: str, host: str,
): ):

View File

@ -15,9 +15,8 @@ from homeassistant.components.ssdp import (
) )
from homeassistant.config_entries import CONN_CLASS_LOCAL_POLL, ConfigFlow from homeassistant.config_entries import CONN_CLASS_LOCAL_POLL, ConfigFlow
from homeassistant.const import CONF_HOST, CONF_NAME from homeassistant.const import CONF_HOST, CONF_NAME
from homeassistant.core import callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.typing import HomeAssistantType
from .const import DOMAIN from .const import DOMAIN
@ -29,7 +28,7 @@ ERROR_UNKNOWN = "unknown"
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
async def validate_input(hass: HomeAssistantType, data: dict) -> dict: async def validate_input(hass: HomeAssistant, data: dict) -> dict:
"""Validate the user input allows us to connect. """Validate the user input allows us to connect.
Data has the keys from DATA_SCHEMA with values provided by the user. Data has the keys from DATA_SCHEMA with values provided by the user.

View File

@ -5,14 +5,14 @@ from typing import Callable
from homeassistant.components.remote import ATTR_NUM_REPEATS, RemoteEntity from homeassistant.components.remote import ATTR_NUM_REPEATS, RemoteEntity
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.typing import HomeAssistantType from homeassistant.core import HomeAssistant
from . import RokuDataUpdateCoordinator, RokuEntity, roku_exception_handler from . import RokuDataUpdateCoordinator, RokuEntity, roku_exception_handler
from .const import DOMAIN from .const import DOMAIN
async def async_setup_entry( async def async_setup_entry(
hass: HomeAssistantType, hass: HomeAssistant,
entry: ConfigEntry, entry: ConfigEntry,
async_add_entities: Callable[[list, bool], None], async_add_entities: Callable[[list, bool], None],
) -> bool: ) -> bool:

View File

@ -4,10 +4,9 @@ from __future__ import annotations
from homeassistant.components.device_tracker import SOURCE_TYPE_ROUTER from homeassistant.components.device_tracker import SOURCE_TYPE_ROUTER
from homeassistant.components.device_tracker.config_entry import ScannerEntity from homeassistant.components.device_tracker.config_entry import ScannerEntity
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.core import callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import entity_registry from homeassistant.helpers import entity_registry
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.helpers.update_coordinator import CoordinatorEntity from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import ( from .const import (
@ -22,7 +21,7 @@ from .const import (
async def async_setup_entry( async def async_setup_entry(
hass: HomeAssistantType, entry: ConfigEntry, async_add_entities hass: HomeAssistant, entry: ConfigEntry, async_add_entities
) -> None: ) -> None:
"""Set up device tracker for Ruckus Unleashed component.""" """Set up device tracker for Ruckus Unleashed component."""
coordinator = hass.data[DOMAIN][entry.entry_id][COORDINATOR] coordinator = hass.data[DOMAIN][entry.entry_id][COORDINATOR]

View File

@ -5,11 +5,10 @@ import logging
from screenlogicpy import ScreenLogicError from screenlogicpy import ScreenLogicError
import voluptuous as vol import voluptuous as vol
from homeassistant.core import ServiceCall, callback from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.service import async_extract_config_entry_ids from homeassistant.helpers.service import async_extract_config_entry_ids
from homeassistant.helpers.typing import HomeAssistantType
from .const import ( from .const import (
ATTR_COLOR_MODE, ATTR_COLOR_MODE,
@ -28,7 +27,7 @@ SET_COLOR_MODE_SCHEMA = cv.make_entity_service_schema(
@callback @callback
def async_load_screenlogic_services(hass: HomeAssistantType): def async_load_screenlogic_services(hass: HomeAssistant):
"""Set up services for the ScreenLogic integration.""" """Set up services for the ScreenLogic integration."""
if hass.services.has_service(DOMAIN, SERVICE_SET_COLOR_MODE): if hass.services.has_service(DOMAIN, SERVICE_SET_COLOR_MODE):
# Integration-level services have already been added. Return. # Integration-level services have already been added. Return.
@ -76,7 +75,7 @@ def async_load_screenlogic_services(hass: HomeAssistantType):
@callback @callback
def async_unload_screenlogic_services(hass: HomeAssistantType): def async_unload_screenlogic_services(hass: HomeAssistant):
"""Unload services for the ScreenLogic integration.""" """Unload services for the ScreenLogic integration."""
if hass.data[DOMAIN]: if hass.data[DOMAIN]:
# There is still another config entry for this domain, don't remove services. # There is still another config entry for this domain, don't remove services.

View File

@ -6,10 +6,10 @@ import shlex
import voluptuous as vol import voluptuous as vol
from homeassistant.core import ServiceCall from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.exceptions import TemplateError from homeassistant.exceptions import TemplateError
from homeassistant.helpers import config_validation as cv, template from homeassistant.helpers import config_validation as cv, template
from homeassistant.helpers.typing import ConfigType, HomeAssistantType from homeassistant.helpers.typing import ConfigType
DOMAIN = "shell_command" DOMAIN = "shell_command"
@ -22,7 +22,7 @@ CONFIG_SCHEMA = vol.Schema(
) )
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool: async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the shell_command component.""" """Set up the shell_command component."""
conf = config.get(DOMAIN, {}) conf = config.get(DOMAIN, {})

View File

@ -21,14 +21,10 @@ from homeassistant.components.notify import (
BaseNotificationService, BaseNotificationService,
) )
from homeassistant.const import ATTR_ICON, CONF_API_KEY, CONF_ICON, CONF_USERNAME from homeassistant.const import ATTR_ICON, CONF_API_KEY, CONF_ICON, CONF_USERNAME
from homeassistant.core import callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import aiohttp_client, config_validation as cv from homeassistant.helpers import aiohttp_client, config_validation as cv
import homeassistant.helpers.template as template import homeassistant.helpers.template as template
from homeassistant.helpers.typing import ( from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
ConfigType,
DiscoveryInfoType,
HomeAssistantType,
)
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -109,7 +105,7 @@ class MessageT(TypedDict, total=False):
async def async_get_service( async def async_get_service(
hass: HomeAssistantType, hass: HomeAssistant,
config: ConfigType, config: ConfigType,
discovery_info: DiscoveryInfoType | None = None, discovery_info: DiscoveryInfoType | None = None,
) -> SlackNotificationService | None: ) -> SlackNotificationService | None:
@ -152,7 +148,7 @@ def _async_sanitize_channel_names(channel_list: list[str]) -> list[str]:
@callback @callback
def _async_templatize_blocks(hass: HomeAssistantType, value: Any) -> Any: def _async_templatize_blocks(hass: HomeAssistant, value: Any) -> Any:
"""Recursive template creator helper function.""" """Recursive template creator helper function."""
if isinstance(value, list): if isinstance(value, list):
return [_async_templatize_blocks(hass, item) for item in value] return [_async_templatize_blocks(hass, item) for item in value]
@ -170,7 +166,7 @@ class SlackNotificationService(BaseNotificationService):
def __init__( def __init__(
self, self,
hass: HomeAssistantType, hass: HomeAssistant,
client: WebClient, client: WebClient,
default_channel: str, default_channel: str,
username: str | None, username: str | None,

View File

@ -7,9 +7,9 @@ import voluptuous as vol
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.exceptions import ConfigEntryNotReady
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.typing import HomeAssistantType
DOMAIN = "smarthab" DOMAIN = "smarthab"
DATA_HUB = "hub" DATA_HUB = "hub"
@ -50,7 +50,7 @@ async def async_setup(hass, config) -> bool:
return True return True
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry): async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up config entry for SmartHab integration.""" """Set up config entry for SmartHab integration."""
# Assign configuration variables # Assign configuration variables
@ -77,7 +77,7 @@ async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry):
return True return True
async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry): async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload config entry from SmartHab integration.""" """Unload config entry from SmartHab integration."""
result = all( result = all(

View File

@ -18,6 +18,7 @@ from homeassistant.const import (
HTTP_FORBIDDEN, HTTP_FORBIDDEN,
HTTP_UNAUTHORIZED, HTTP_UNAUTHORIZED,
) )
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.dispatcher import ( from homeassistant.helpers.dispatcher import (
@ -26,7 +27,7 @@ from homeassistant.helpers.dispatcher import (
) )
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_time_interval from homeassistant.helpers.event import async_track_time_interval
from homeassistant.helpers.typing import ConfigType, HomeAssistantType from homeassistant.helpers.typing import ConfigType
from .config_flow import SmartThingsFlowHandler # noqa: F401 from .config_flow import SmartThingsFlowHandler # noqa: F401
from .const import ( from .const import (
@ -55,13 +56,13 @@ from .smartapp import (
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
async def async_setup(hass: HomeAssistantType, config: ConfigType): async def async_setup(hass: HomeAssistant, config: ConfigType):
"""Initialize the SmartThings platform.""" """Initialize the SmartThings platform."""
await setup_smartapp_endpoint(hass) await setup_smartapp_endpoint(hass)
return True return True
async def async_migrate_entry(hass: HomeAssistantType, entry: ConfigEntry): async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Handle migration of a previous version config entry. """Handle migration of a previous version config entry.
A config entry created under a previous version must go through the A config entry created under a previous version must go through the
@ -81,7 +82,7 @@ async def async_migrate_entry(hass: HomeAssistantType, entry: ConfigEntry):
return False return False
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry): async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Initialize config entry which represents an installed SmartApp.""" """Initialize config entry which represents an installed SmartApp."""
# For backwards compat # For backwards compat
if entry.unique_id is None: if entry.unique_id is None:
@ -208,7 +209,7 @@ async def async_get_entry_scenes(entry: ConfigEntry, api):
return [] return []
async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry): async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry.""" """Unload a config entry."""
broker = hass.data[DOMAIN][DATA_BROKERS].pop(entry.entry_id, None) broker = hass.data[DOMAIN][DATA_BROKERS].pop(entry.entry_id, None)
if broker: if broker:
@ -221,7 +222,7 @@ async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry):
return all(await asyncio.gather(*tasks)) return all(await asyncio.gather(*tasks))
async def async_remove_entry(hass: HomeAssistantType, entry: ConfigEntry) -> None: async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Perform clean-up when entry is being removed.""" """Perform clean-up when entry is being removed."""
api = SmartThings(async_get_clientsession(hass), entry.data[CONF_ACCESS_TOKEN]) api = SmartThings(async_get_clientsession(hass), entry.data[CONF_ACCESS_TOKEN])
@ -270,7 +271,7 @@ class DeviceBroker:
def __init__( def __init__(
self, self,
hass: HomeAssistantType, hass: HomeAssistant,
entry: ConfigEntry, entry: ConfigEntry,
token, token,
smart_app, smart_app,

View File

@ -25,13 +25,13 @@ from pysmartthings import (
from homeassistant.components import webhook from homeassistant.components import webhook
from homeassistant.const import CONF_WEBHOOK_ID from homeassistant.const import CONF_WEBHOOK_ID
from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.dispatcher import ( from homeassistant.helpers.dispatcher import (
async_dispatcher_connect, async_dispatcher_connect,
async_dispatcher_send, async_dispatcher_send,
) )
from homeassistant.helpers.network import NoURLAvailableError, get_url from homeassistant.helpers.network import NoURLAvailableError, get_url
from homeassistant.helpers.typing import HomeAssistantType
from .const import ( from .const import (
APP_NAME_PREFIX, APP_NAME_PREFIX,
@ -60,7 +60,7 @@ def format_unique_id(app_id: str, location_id: str) -> str:
return f"{app_id}_{location_id}" return f"{app_id}_{location_id}"
async def find_app(hass: HomeAssistantType, api): async def find_app(hass: HomeAssistant, api):
"""Find an existing SmartApp for this installation of hass.""" """Find an existing SmartApp for this installation of hass."""
apps = await api.apps() apps = await api.apps()
for app in [app for app in apps if app.app_name.startswith(APP_NAME_PREFIX)]: for app in [app for app in apps if app.app_name.startswith(APP_NAME_PREFIX)]:
@ -92,7 +92,7 @@ async def validate_installed_app(api, installed_app_id: str):
return installed_app return installed_app
def validate_webhook_requirements(hass: HomeAssistantType) -> bool: def validate_webhook_requirements(hass: HomeAssistant) -> bool:
"""Ensure Home Assistant is setup properly to receive webhooks.""" """Ensure Home Assistant is setup properly to receive webhooks."""
if hass.components.cloud.async_active_subscription(): if hass.components.cloud.async_active_subscription():
return True return True
@ -101,7 +101,7 @@ def validate_webhook_requirements(hass: HomeAssistantType) -> bool:
return get_webhook_url(hass).lower().startswith("https://") return get_webhook_url(hass).lower().startswith("https://")
def get_webhook_url(hass: HomeAssistantType) -> str: def get_webhook_url(hass: HomeAssistant) -> str:
""" """
Get the URL of the webhook. Get the URL of the webhook.
@ -113,7 +113,7 @@ def get_webhook_url(hass: HomeAssistantType) -> str:
return webhook.async_generate_url(hass, hass.data[DOMAIN][CONF_WEBHOOK_ID]) return webhook.async_generate_url(hass, hass.data[DOMAIN][CONF_WEBHOOK_ID])
def _get_app_template(hass: HomeAssistantType): def _get_app_template(hass: HomeAssistant):
try: try:
endpoint = f"at {get_url(hass, allow_cloud=False, prefer_external=True)}" endpoint = f"at {get_url(hass, allow_cloud=False, prefer_external=True)}"
except NoURLAvailableError: except NoURLAvailableError:
@ -135,7 +135,7 @@ def _get_app_template(hass: HomeAssistantType):
} }
async def create_app(hass: HomeAssistantType, api): async def create_app(hass: HomeAssistant, api):
"""Create a SmartApp for this instance of hass.""" """Create a SmartApp for this instance of hass."""
# Create app from template attributes # Create app from template attributes
template = _get_app_template(hass) template = _get_app_template(hass)
@ -163,7 +163,7 @@ async def create_app(hass: HomeAssistantType, api):
return app, client return app, client
async def update_app(hass: HomeAssistantType, app): async def update_app(hass: HomeAssistant, app):
"""Ensure the SmartApp is up-to-date and update if necessary.""" """Ensure the SmartApp is up-to-date and update if necessary."""
template = _get_app_template(hass) template = _get_app_template(hass)
template.pop("app_name") # don't update this template.pop("app_name") # don't update this
@ -199,7 +199,7 @@ def setup_smartapp(hass, app):
return smartapp return smartapp
async def setup_smartapp_endpoint(hass: HomeAssistantType): async def setup_smartapp_endpoint(hass: HomeAssistant):
""" """
Configure the SmartApp webhook in hass. Configure the SmartApp webhook in hass.
@ -276,7 +276,7 @@ async def setup_smartapp_endpoint(hass: HomeAssistantType):
) )
async def unload_smartapp_endpoint(hass: HomeAssistantType): async def unload_smartapp_endpoint(hass: HomeAssistant):
"""Tear down the component configuration.""" """Tear down the component configuration."""
if DOMAIN not in hass.data: if DOMAIN not in hass.data:
return return
@ -308,7 +308,7 @@ async def unload_smartapp_endpoint(hass: HomeAssistantType):
async def smartapp_sync_subscriptions( async def smartapp_sync_subscriptions(
hass: HomeAssistantType, hass: HomeAssistant,
auth_token: str, auth_token: str,
location_id: str, location_id: str,
installed_app_id: str, installed_app_id: str,
@ -397,7 +397,7 @@ async def smartapp_sync_subscriptions(
async def _continue_flow( async def _continue_flow(
hass: HomeAssistantType, hass: HomeAssistant,
app_id: str, app_id: str,
location_id: str, location_id: str,
installed_app_id: str, installed_app_id: str,
@ -429,7 +429,7 @@ async def _continue_flow(
) )
async def smartapp_install(hass: HomeAssistantType, req, resp, app): async def smartapp_install(hass: HomeAssistant, req, resp, app):
"""Handle a SmartApp installation and continue the config flow.""" """Handle a SmartApp installation and continue the config flow."""
await _continue_flow( await _continue_flow(
hass, app.app_id, req.location_id, req.installed_app_id, req.refresh_token hass, app.app_id, req.location_id, req.installed_app_id, req.refresh_token
@ -441,7 +441,7 @@ async def smartapp_install(hass: HomeAssistantType, req, resp, app):
) )
async def smartapp_update(hass: HomeAssistantType, req, resp, app): async def smartapp_update(hass: HomeAssistant, req, resp, app):
"""Handle a SmartApp update and either update the entry or continue the flow.""" """Handle a SmartApp update and either update the entry or continue the flow."""
entry = next( entry = next(
( (
@ -470,7 +470,7 @@ async def smartapp_update(hass: HomeAssistantType, req, resp, app):
) )
async def smartapp_uninstall(hass: HomeAssistantType, req, resp, app): async def smartapp_uninstall(hass: HomeAssistant, req, resp, app):
""" """
Handle when a SmartApp is removed from a location by the user. Handle when a SmartApp is removed from a location by the user.
@ -496,7 +496,7 @@ async def smartapp_uninstall(hass: HomeAssistantType, req, resp, app):
) )
async def smartapp_webhook(hass: HomeAssistantType, webhook_id: str, request): async def smartapp_webhook(hass: HomeAssistant, webhook_id: str, request):
""" """
Handle a smartapp lifecycle event callback from SmartThings. Handle a smartapp lifecycle event callback from SmartThings.

View File

@ -9,8 +9,7 @@ from typing import cast
import attr import attr
from homeassistant.core import callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.loader import bind_hass from homeassistant.loader import bind_hass
from .typing import ZhaDeviceType from .typing import ZhaDeviceType
@ -35,9 +34,9 @@ class ZhaDeviceEntry:
class ZhaStorage: class ZhaStorage:
"""Class to hold a registry of zha devices.""" """Class to hold a registry of zha devices."""
def __init__(self, hass: HomeAssistantType) -> None: def __init__(self, hass: HomeAssistant) -> None:
"""Initialize the zha device storage.""" """Initialize the zha device storage."""
self.hass: HomeAssistantType = hass self.hass: HomeAssistant = hass
self.devices: MutableMapping[str, ZhaDeviceEntry] = {} self.devices: MutableMapping[str, ZhaDeviceEntry] = {}
self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY) self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY)
@ -130,7 +129,7 @@ class ZhaStorage:
@bind_hass @bind_hass
async def async_get_registry(hass: HomeAssistantType) -> ZhaStorage: async def async_get_registry(hass: HomeAssistant) -> ZhaStorage:
"""Return zha device storage instance.""" """Return zha device storage instance."""
task = hass.data.get(DATA_REGISTRY) task = hass.data.get(DATA_REGISTRY)

View File

@ -3,7 +3,7 @@ from datetime import timedelta
from homeassistant import core as ha from homeassistant import core as ha
from homeassistant.components import recorder from homeassistant.components import recorder
from homeassistant.helpers.typing import HomeAssistantType from homeassistant.core import HomeAssistant
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
from tests.common import async_fire_time_changed, fire_time_changed from tests.common import async_fire_time_changed, fire_time_changed
@ -11,7 +11,7 @@ from tests.common import async_fire_time_changed, fire_time_changed
DEFAULT_PURGE_TASKS = 3 DEFAULT_PURGE_TASKS = 3
def wait_recording_done(hass: HomeAssistantType) -> None: def wait_recording_done(hass: HomeAssistant) -> None:
"""Block till recording is done.""" """Block till recording is done."""
hass.block_till_done() hass.block_till_done()
trigger_db_commit(hass) trigger_db_commit(hass)
@ -20,12 +20,12 @@ def wait_recording_done(hass: HomeAssistantType) -> None:
hass.block_till_done() hass.block_till_done()
async def async_wait_recording_done_without_instance(hass: HomeAssistantType) -> None: async def async_wait_recording_done_without_instance(hass: HomeAssistant) -> None:
"""Block till recording is done.""" """Block till recording is done."""
await hass.loop.run_in_executor(None, wait_recording_done, hass) await hass.loop.run_in_executor(None, wait_recording_done, hass)
def trigger_db_commit(hass: HomeAssistantType) -> None: def trigger_db_commit(hass: HomeAssistant) -> None:
"""Force the recorder to commit.""" """Force the recorder to commit."""
for _ in range(recorder.DEFAULT_COMMIT_INTERVAL): for _ in range(recorder.DEFAULT_COMMIT_INTERVAL):
# We only commit on time change # We only commit on time change
@ -33,7 +33,7 @@ def trigger_db_commit(hass: HomeAssistantType) -> None:
async def async_wait_recording_done( async def async_wait_recording_done(
hass: HomeAssistantType, hass: HomeAssistant,
instance: recorder.Recorder, instance: recorder.Recorder,
) -> None: ) -> None:
"""Async wait until recording is done.""" """Async wait until recording is done."""
@ -45,7 +45,7 @@ async def async_wait_recording_done(
async def async_wait_purge_done( async def async_wait_purge_done(
hass: HomeAssistantType, instance: recorder.Recorder, max: int = None hass: HomeAssistant, instance: recorder.Recorder, max: int = None
) -> None: ) -> None:
"""Wait for max number of purge events. """Wait for max number of purge events.
@ -61,14 +61,14 @@ async def async_wait_purge_done(
@ha.callback @ha.callback
def async_trigger_db_commit(hass: HomeAssistantType) -> None: def async_trigger_db_commit(hass: HomeAssistant) -> None:
"""Fore the recorder to commit. Async friendly.""" """Fore the recorder to commit. Async friendly."""
for _ in range(recorder.DEFAULT_COMMIT_INTERVAL): for _ in range(recorder.DEFAULT_COMMIT_INTERVAL):
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=1)) async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=1))
async def async_recorder_block_till_done( async def async_recorder_block_till_done(
hass: HomeAssistantType, hass: HomeAssistant,
instance: recorder.Recorder, instance: recorder.Recorder,
) -> None: ) -> None:
"""Non blocking version of recorder.block_till_done().""" """Non blocking version of recorder.block_till_done()."""

View File

@ -8,7 +8,8 @@ import pytest
from homeassistant.components.recorder import Recorder from homeassistant.components.recorder import Recorder
from homeassistant.components.recorder.const import DATA_INSTANCE from homeassistant.components.recorder.const import DATA_INSTANCE
from homeassistant.helpers.typing import ConfigType, HomeAssistantType from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType
from .common import async_recorder_block_till_done from .common import async_recorder_block_till_done
@ -45,7 +46,7 @@ async def async_setup_recorder_instance() -> AsyncGenerator[
"""Yield callable to setup recorder instance.""" """Yield callable to setup recorder instance."""
async def async_setup_recorder( async def async_setup_recorder(
hass: HomeAssistantType, config: ConfigType | None = None hass: HomeAssistant, config: ConfigType | None = None
) -> Recorder: ) -> Recorder:
"""Setup and return recorder instance.""" # noqa: D401 """Setup and return recorder instance.""" # noqa: D401
await async_init_recorder_component(hass, config) await async_init_recorder_component(hass, config)

View File

@ -32,7 +32,6 @@ from homeassistant.const import (
STATE_UNLOCKED, STATE_UNLOCKED,
) )
from homeassistant.core import Context, CoreState, HomeAssistant, callback from homeassistant.core import Context, CoreState, HomeAssistant, callback
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.setup import async_setup_component, setup_component from homeassistant.setup import async_setup_component, setup_component
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
@ -116,7 +115,7 @@ async def test_state_gets_saved_when_set_before_start_event(
async def test_saving_state( async def test_saving_state(
hass: HomeAssistantType, async_setup_recorder_instance: SetupRecorderInstanceT hass: HomeAssistant, async_setup_recorder_instance: SetupRecorderInstanceT
): ):
"""Test saving and restoring a state.""" """Test saving and restoring a state."""
instance = await async_setup_recorder_instance(hass) instance = await async_setup_recorder_instance(hass)
@ -139,7 +138,7 @@ async def test_saving_state(
async def test_saving_many_states( async def test_saving_many_states(
hass: HomeAssistantType, async_setup_recorder_instance: SetupRecorderInstanceT hass: HomeAssistant, async_setup_recorder_instance: SetupRecorderInstanceT
): ):
"""Test we expire after many commits.""" """Test we expire after many commits."""
instance = await async_setup_recorder_instance(hass) instance = await async_setup_recorder_instance(hass)
@ -165,7 +164,7 @@ async def test_saving_many_states(
async def test_saving_state_with_intermixed_time_changes( async def test_saving_state_with_intermixed_time_changes(
hass: HomeAssistantType, async_setup_recorder_instance: SetupRecorderInstanceT hass: HomeAssistant, async_setup_recorder_instance: SetupRecorderInstanceT
): ):
"""Test saving states with intermixed time changes.""" """Test saving states with intermixed time changes."""
instance = await async_setup_recorder_instance(hass) instance = await async_setup_recorder_instance(hass)

View File

@ -12,7 +12,8 @@ from homeassistant.components.recorder.models import Events, RecorderRuns, State
from homeassistant.components.recorder.purge import purge_old_data from homeassistant.components.recorder.purge import purge_old_data
from homeassistant.components.recorder.util import session_scope from homeassistant.components.recorder.util import session_scope
from homeassistant.const import EVENT_STATE_CHANGED from homeassistant.const import EVENT_STATE_CHANGED
from homeassistant.helpers.typing import ConfigType, HomeAssistantType from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
from .common import ( from .common import (
@ -25,7 +26,7 @@ from .conftest import SetupRecorderInstanceT
async def test_purge_old_states( async def test_purge_old_states(
hass: HomeAssistantType, async_setup_recorder_instance: SetupRecorderInstanceT hass: HomeAssistant, async_setup_recorder_instance: SetupRecorderInstanceT
): ):
"""Test deleting old states.""" """Test deleting old states."""
instance = await async_setup_recorder_instance(hass) instance = await async_setup_recorder_instance(hass)
@ -57,7 +58,7 @@ async def test_purge_old_states(
async def test_purge_old_states_encouters_database_corruption( async def test_purge_old_states_encouters_database_corruption(
hass: HomeAssistantType, async_setup_recorder_instance: SetupRecorderInstanceT hass: HomeAssistant, async_setup_recorder_instance: SetupRecorderInstanceT
): ):
"""Test database image image is malformed while deleting old states.""" """Test database image image is malformed while deleting old states."""
instance = await async_setup_recorder_instance(hass) instance = await async_setup_recorder_instance(hass)
@ -89,7 +90,7 @@ async def test_purge_old_states_encouters_database_corruption(
async def test_purge_old_states_encounters_temporary_mysql_error( async def test_purge_old_states_encounters_temporary_mysql_error(
hass: HomeAssistantType, hass: HomeAssistant,
async_setup_recorder_instance: SetupRecorderInstanceT, async_setup_recorder_instance: SetupRecorderInstanceT,
caplog, caplog,
): ):
@ -122,7 +123,7 @@ async def test_purge_old_states_encounters_temporary_mysql_error(
async def test_purge_old_states_encounters_operational_error( async def test_purge_old_states_encounters_operational_error(
hass: HomeAssistantType, hass: HomeAssistant,
async_setup_recorder_instance: SetupRecorderInstanceT, async_setup_recorder_instance: SetupRecorderInstanceT,
caplog, caplog,
): ):
@ -150,7 +151,7 @@ async def test_purge_old_states_encounters_operational_error(
async def test_purge_old_events( async def test_purge_old_events(
hass: HomeAssistantType, async_setup_recorder_instance: SetupRecorderInstanceT hass: HomeAssistant, async_setup_recorder_instance: SetupRecorderInstanceT
): ):
"""Test deleting old events.""" """Test deleting old events."""
instance = await async_setup_recorder_instance(hass) instance = await async_setup_recorder_instance(hass)
@ -173,7 +174,7 @@ async def test_purge_old_events(
async def test_purge_old_recorder_runs( async def test_purge_old_recorder_runs(
hass: HomeAssistantType, async_setup_recorder_instance: SetupRecorderInstanceT hass: HomeAssistant, async_setup_recorder_instance: SetupRecorderInstanceT
): ):
"""Test deleting old recorder runs keeps current run.""" """Test deleting old recorder runs keeps current run."""
instance = await async_setup_recorder_instance(hass) instance = await async_setup_recorder_instance(hass)
@ -195,7 +196,7 @@ async def test_purge_old_recorder_runs(
async def test_purge_method( async def test_purge_method(
hass: HomeAssistantType, hass: HomeAssistant,
async_setup_recorder_instance: SetupRecorderInstanceT, async_setup_recorder_instance: SetupRecorderInstanceT,
caplog, caplog,
): ):
@ -265,12 +266,12 @@ async def test_purge_method(
async def test_purge_edge_case( async def test_purge_edge_case(
hass: HomeAssistantType, hass: HomeAssistant,
async_setup_recorder_instance: SetupRecorderInstanceT, async_setup_recorder_instance: SetupRecorderInstanceT,
): ):
"""Test states and events are purged even if they occurred shortly before purge_before.""" """Test states and events are purged even if they occurred shortly before purge_before."""
async def _add_db_entries(hass: HomeAssistantType, timestamp: datetime) -> None: async def _add_db_entries(hass: HomeAssistant, timestamp: datetime) -> None:
with recorder.session_scope(hass=hass) as session: with recorder.session_scope(hass=hass) as session:
session.add( session.add(
Events( Events(
@ -322,7 +323,7 @@ async def test_purge_edge_case(
async def test_purge_filtered_states( async def test_purge_filtered_states(
hass: HomeAssistantType, hass: HomeAssistant,
async_setup_recorder_instance: SetupRecorderInstanceT, async_setup_recorder_instance: SetupRecorderInstanceT,
): ):
"""Test filtered states are purged.""" """Test filtered states are purged."""
@ -330,7 +331,7 @@ async def test_purge_filtered_states(
instance = await async_setup_recorder_instance(hass, config) instance = await async_setup_recorder_instance(hass, config)
assert instance.entity_filter("sensor.excluded") is False assert instance.entity_filter("sensor.excluded") is False
def _add_db_entries(hass: HomeAssistantType) -> None: def _add_db_entries(hass: HomeAssistant) -> None:
with recorder.session_scope(hass=hass) as session: with recorder.session_scope(hass=hass) as session:
# Add states and state_changed events that should be purged # Add states and state_changed events that should be purged
for days in range(1, 4): for days in range(1, 4):
@ -467,14 +468,14 @@ async def test_purge_filtered_states(
async def test_purge_filtered_events( async def test_purge_filtered_events(
hass: HomeAssistantType, hass: HomeAssistant,
async_setup_recorder_instance: SetupRecorderInstanceT, async_setup_recorder_instance: SetupRecorderInstanceT,
): ):
"""Test filtered events are purged.""" """Test filtered events are purged."""
config: ConfigType = {"exclude": {"event_types": ["EVENT_PURGE"]}} config: ConfigType = {"exclude": {"event_types": ["EVENT_PURGE"]}}
instance = await async_setup_recorder_instance(hass, config) instance = await async_setup_recorder_instance(hass, config)
def _add_db_entries(hass: HomeAssistantType) -> None: def _add_db_entries(hass: HomeAssistant) -> None:
with recorder.session_scope(hass=hass) as session: with recorder.session_scope(hass=hass) as session:
# Add events that should be purged # Add events that should be purged
for days in range(1, 4): for days in range(1, 4):
@ -548,7 +549,7 @@ async def test_purge_filtered_events(
async def test_purge_filtered_events_state_changed( async def test_purge_filtered_events_state_changed(
hass: HomeAssistantType, hass: HomeAssistant,
async_setup_recorder_instance: SetupRecorderInstanceT, async_setup_recorder_instance: SetupRecorderInstanceT,
): ):
"""Test filtered state_changed events are purged. This should also remove all states.""" """Test filtered state_changed events are purged. This should also remove all states."""
@ -557,7 +558,7 @@ async def test_purge_filtered_events_state_changed(
# Assert entity_id is NOT excluded # Assert entity_id is NOT excluded
assert instance.entity_filter("sensor.excluded") is True assert instance.entity_filter("sensor.excluded") is True
def _add_db_entries(hass: HomeAssistantType) -> None: def _add_db_entries(hass: HomeAssistant) -> None:
with recorder.session_scope(hass=hass) as session: with recorder.session_scope(hass=hass) as session:
# Add states and state_changed events that should be purged # Add states and state_changed events that should be purged
for days in range(1, 4): for days in range(1, 4):
@ -652,7 +653,7 @@ async def test_purge_filtered_events_state_changed(
assert session.query(States).get(63).old_state_id == 62 # should have been kept assert session.query(States).get(63).old_state_id == 62 # should have been kept
async def _add_test_states(hass: HomeAssistantType, instance: recorder.Recorder): async def _add_test_states(hass: HomeAssistant, instance: recorder.Recorder):
"""Add multiple states to the db for testing.""" """Add multiple states to the db for testing."""
utcnow = dt_util.utcnow() utcnow = dt_util.utcnow()
five_days_ago = utcnow - timedelta(days=5) five_days_ago = utcnow - timedelta(days=5)
@ -700,7 +701,7 @@ async def _add_test_states(hass: HomeAssistantType, instance: recorder.Recorder)
old_state_id = state.state_id old_state_id = state.state_id
async def _add_test_events(hass: HomeAssistantType, instance: recorder.Recorder): async def _add_test_events(hass: HomeAssistant, instance: recorder.Recorder):
"""Add a few events for testing.""" """Add a few events for testing."""
utcnow = dt_util.utcnow() utcnow = dt_util.utcnow()
five_days_ago = utcnow - timedelta(days=5) five_days_ago = utcnow - timedelta(days=5)
@ -733,7 +734,7 @@ async def _add_test_events(hass: HomeAssistantType, instance: recorder.Recorder)
) )
async def _add_test_recorder_runs(hass: HomeAssistantType, instance: recorder.Recorder): async def _add_test_recorder_runs(hass: HomeAssistant, instance: recorder.Recorder):
"""Add a few recorder_runs for testing.""" """Add a few recorder_runs for testing."""
utcnow = dt_util.utcnow() utcnow = dt_util.utcnow()
five_days_ago = utcnow - timedelta(days=5) five_days_ago = utcnow - timedelta(days=5)

View File

@ -9,7 +9,7 @@ from homeassistant.components.ssdp import (
ATTR_UPNP_SERIAL, ATTR_UPNP_SERIAL,
) )
from homeassistant.const import CONF_HOST, CONF_ID, CONF_NAME from homeassistant.const import CONF_HOST, CONF_ID, CONF_NAME
from homeassistant.helpers.typing import HomeAssistantType from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry, load_fixture from tests.common import MockConfigEntry, load_fixture
from tests.test_util.aiohttp import AiohttpClientMocker from tests.test_util.aiohttp import AiohttpClientMocker
@ -162,7 +162,7 @@ def mock_connection_server_error(
async def setup_integration( async def setup_integration(
hass: HomeAssistantType, hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
device: str = "roku3", device: str = "roku3",
app: str = "roku", app: str = "roku",

View File

@ -4,12 +4,12 @@ from unittest.mock import patch
from homeassistant.components.roku.const import DOMAIN from homeassistant.components.roku.const import DOMAIN
from homeassistant.config_entries import SOURCE_HOMEKIT, SOURCE_SSDP, SOURCE_USER from homeassistant.config_entries import SOURCE_HOMEKIT, SOURCE_SSDP, SOURCE_USER
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_SOURCE from homeassistant.const import CONF_HOST, CONF_NAME, CONF_SOURCE
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import ( from homeassistant.data_entry_flow import (
RESULT_TYPE_ABORT, RESULT_TYPE_ABORT,
RESULT_TYPE_CREATE_ENTRY, RESULT_TYPE_CREATE_ENTRY,
RESULT_TYPE_FORM, RESULT_TYPE_FORM,
) )
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.components.roku import ( from tests.components.roku import (
@ -26,7 +26,7 @@ from tests.test_util.aiohttp import AiohttpClientMocker
async def test_duplicate_error( async def test_duplicate_error(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test that errors are shown when duplicates are added.""" """Test that errors are shown when duplicates are added."""
await setup_integration(hass, aioclient_mock, skip_entry_setup=True) await setup_integration(hass, aioclient_mock, skip_entry_setup=True)
@ -57,9 +57,7 @@ async def test_duplicate_error(
assert result["reason"] == "already_configured" assert result["reason"] == "already_configured"
async def test_form( async def test_form(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None:
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the user step.""" """Test the user step."""
await async_setup_component(hass, "persistent_notification", {}) await async_setup_component(hass, "persistent_notification", {})
mock_connection(aioclient_mock) mock_connection(aioclient_mock)
@ -90,7 +88,7 @@ async def test_form(
async def test_form_cannot_connect( async def test_form_cannot_connect(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test we handle cannot connect roku error.""" """Test we handle cannot connect roku error."""
mock_connection(aioclient_mock, error=True) mock_connection(aioclient_mock, error=True)
@ -107,7 +105,7 @@ async def test_form_cannot_connect(
assert result["errors"] == {"base": "cannot_connect"} assert result["errors"] == {"base": "cannot_connect"}
async def test_form_unknown_error(hass: HomeAssistantType) -> None: async def test_form_unknown_error(hass: HomeAssistant) -> None:
"""Test we handle unknown error.""" """Test we handle unknown error."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={CONF_SOURCE: SOURCE_USER} DOMAIN, context={CONF_SOURCE: SOURCE_USER}
@ -130,7 +128,7 @@ async def test_form_unknown_error(hass: HomeAssistantType) -> None:
async def test_homekit_cannot_connect( async def test_homekit_cannot_connect(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test we abort homekit flow on connection error.""" """Test we abort homekit flow on connection error."""
mock_connection( mock_connection(
@ -151,7 +149,7 @@ async def test_homekit_cannot_connect(
async def test_homekit_unknown_error( async def test_homekit_unknown_error(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test we abort homekit flow on unknown error.""" """Test we abort homekit flow on unknown error."""
discovery_info = MOCK_HOMEKIT_DISCOVERY_INFO.copy() discovery_info = MOCK_HOMEKIT_DISCOVERY_INFO.copy()
@ -170,7 +168,7 @@ async def test_homekit_unknown_error(
async def test_homekit_discovery( async def test_homekit_discovery(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test the homekit discovery flow.""" """Test the homekit discovery flow."""
mock_connection(aioclient_mock, device="rokutv", host=HOMEKIT_HOST) mock_connection(aioclient_mock, device="rokutv", host=HOMEKIT_HOST)
@ -213,7 +211,7 @@ async def test_homekit_discovery(
async def test_ssdp_cannot_connect( async def test_ssdp_cannot_connect(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test we abort SSDP flow on connection error.""" """Test we abort SSDP flow on connection error."""
mock_connection(aioclient_mock, error=True) mock_connection(aioclient_mock, error=True)
@ -230,7 +228,7 @@ async def test_ssdp_cannot_connect(
async def test_ssdp_unknown_error( async def test_ssdp_unknown_error(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test we abort SSDP flow on unknown error.""" """Test we abort SSDP flow on unknown error."""
discovery_info = MOCK_SSDP_DISCOVERY_INFO.copy() discovery_info = MOCK_SSDP_DISCOVERY_INFO.copy()
@ -249,7 +247,7 @@ async def test_ssdp_unknown_error(
async def test_ssdp_discovery( async def test_ssdp_discovery(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test the SSDP discovery flow.""" """Test the SSDP discovery flow."""
mock_connection(aioclient_mock) mock_connection(aioclient_mock)

View File

@ -7,14 +7,14 @@ from homeassistant.config_entries import (
ENTRY_STATE_NOT_LOADED, ENTRY_STATE_NOT_LOADED,
ENTRY_STATE_SETUP_RETRY, ENTRY_STATE_SETUP_RETRY,
) )
from homeassistant.helpers.typing import HomeAssistantType from homeassistant.core import HomeAssistant
from tests.components.roku import setup_integration from tests.components.roku import setup_integration
from tests.test_util.aiohttp import AiohttpClientMocker from tests.test_util.aiohttp import AiohttpClientMocker
async def test_config_entry_not_ready( async def test_config_entry_not_ready(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test the Roku configuration entry not ready.""" """Test the Roku configuration entry not ready."""
entry = await setup_integration(hass, aioclient_mock, error=True) entry = await setup_integration(hass, aioclient_mock, error=True)
@ -23,7 +23,7 @@ async def test_config_entry_not_ready(
async def test_unload_config_entry( async def test_unload_config_entry(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test the Roku configuration entry unloading.""" """Test the Roku configuration entry unloading."""
with patch( with patch(

View File

@ -61,8 +61,8 @@ from homeassistant.const import (
STATE_STANDBY, STATE_STANDBY,
STATE_UNAVAILABLE, STATE_UNAVAILABLE,
) )
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
from tests.common import async_fire_time_changed from tests.common import async_fire_time_changed
@ -80,9 +80,7 @@ TV_SERIAL = "YN00H5555555"
TV_SW_VERSION = "9.2.0" TV_SW_VERSION = "9.2.0"
async def test_setup( async def test_setup(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None:
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test setup with basic config.""" """Test setup with basic config."""
await setup_integration(hass, aioclient_mock) await setup_integration(hass, aioclient_mock)
@ -96,7 +94,7 @@ async def test_setup(
async def test_idle_setup( async def test_idle_setup(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test setup with idle device.""" """Test setup with idle device."""
await setup_integration(hass, aioclient_mock, power=False) await setup_integration(hass, aioclient_mock, power=False)
@ -106,7 +104,7 @@ async def test_idle_setup(
async def test_tv_setup( async def test_tv_setup(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test Roku TV setup.""" """Test Roku TV setup."""
await setup_integration( await setup_integration(
@ -128,7 +126,7 @@ async def test_tv_setup(
async def test_availability( async def test_availability(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test entity availability.""" """Test entity availability."""
now = dt_util.utcnow() now = dt_util.utcnow()
@ -153,7 +151,7 @@ async def test_availability(
async def test_supported_features( async def test_supported_features(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test supported features.""" """Test supported features."""
await setup_integration(hass, aioclient_mock) await setup_integration(hass, aioclient_mock)
@ -177,7 +175,7 @@ async def test_supported_features(
async def test_tv_supported_features( async def test_tv_supported_features(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test supported features for Roku TV.""" """Test supported features for Roku TV."""
await setup_integration( await setup_integration(
@ -207,7 +205,7 @@ async def test_tv_supported_features(
async def test_attributes( async def test_attributes(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test attributes.""" """Test attributes."""
await setup_integration(hass, aioclient_mock) await setup_integration(hass, aioclient_mock)
@ -222,7 +220,7 @@ async def test_attributes(
async def test_attributes_app( async def test_attributes_app(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test attributes for app.""" """Test attributes for app."""
await setup_integration(hass, aioclient_mock, app="netflix") await setup_integration(hass, aioclient_mock, app="netflix")
@ -237,7 +235,7 @@ async def test_attributes_app(
async def test_attributes_app_media_playing( async def test_attributes_app_media_playing(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test attributes for app with playing media.""" """Test attributes for app with playing media."""
await setup_integration(hass, aioclient_mock, app="pluto", media_state="play") await setup_integration(hass, aioclient_mock, app="pluto", media_state="play")
@ -254,7 +252,7 @@ async def test_attributes_app_media_playing(
async def test_attributes_app_media_paused( async def test_attributes_app_media_paused(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test attributes for app with paused media.""" """Test attributes for app with paused media."""
await setup_integration(hass, aioclient_mock, app="pluto", media_state="pause") await setup_integration(hass, aioclient_mock, app="pluto", media_state="pause")
@ -271,7 +269,7 @@ async def test_attributes_app_media_paused(
async def test_attributes_screensaver( async def test_attributes_screensaver(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test attributes for app with screensaver.""" """Test attributes for app with screensaver."""
await setup_integration(hass, aioclient_mock, app="screensaver") await setup_integration(hass, aioclient_mock, app="screensaver")
@ -286,7 +284,7 @@ async def test_attributes_screensaver(
async def test_tv_attributes( async def test_tv_attributes(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test attributes for Roku TV.""" """Test attributes for Roku TV."""
await setup_integration( await setup_integration(
@ -310,7 +308,7 @@ async def test_tv_attributes(
async def test_tv_device_registry( async def test_tv_device_registry(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test device registered for Roku TV in the device registry.""" """Test device registered for Roku TV in the device registry."""
await setup_integration( await setup_integration(
@ -333,7 +331,7 @@ async def test_tv_device_registry(
async def test_services( async def test_services(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test the different media player services.""" """Test the different media player services."""
await setup_integration(hass, aioclient_mock) await setup_integration(hass, aioclient_mock)
@ -448,7 +446,7 @@ async def test_services(
async def test_tv_services( async def test_tv_services(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test the media player services related to Roku TV.""" """Test the media player services related to Roku TV."""
await setup_integration( await setup_integration(
@ -691,7 +689,7 @@ async def test_media_browse_internal(hass, aioclient_mock, hass_ws_client):
async def test_integration_services( async def test_integration_services(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test integration services.""" """Test integration services."""
await setup_integration(hass, aioclient_mock) await setup_integration(hass, aioclient_mock)

View File

@ -7,8 +7,8 @@ from homeassistant.components.remote import (
SERVICE_SEND_COMMAND, SERVICE_SEND_COMMAND,
) )
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.typing import HomeAssistantType
from tests.components.roku import UPNP_SERIAL, setup_integration from tests.components.roku import UPNP_SERIAL, setup_integration
from tests.test_util.aiohttp import AiohttpClientMocker from tests.test_util.aiohttp import AiohttpClientMocker
@ -18,16 +18,14 @@ MAIN_ENTITY_ID = f"{REMOTE_DOMAIN}.my_roku_3"
# pylint: disable=redefined-outer-name # pylint: disable=redefined-outer-name
async def test_setup( async def test_setup(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None:
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test setup with basic config.""" """Test setup with basic config."""
await setup_integration(hass, aioclient_mock) await setup_integration(hass, aioclient_mock)
assert hass.states.get(MAIN_ENTITY_ID) assert hass.states.get(MAIN_ENTITY_ID)
async def test_unique_id( async def test_unique_id(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test unique id.""" """Test unique id."""
await setup_integration(hass, aioclient_mock) await setup_integration(hass, aioclient_mock)
@ -39,7 +37,7 @@ async def test_unique_id(
async def test_main_services( async def test_main_services(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None: ) -> None:
"""Test platform services.""" """Test platform services."""
await setup_integration(hass, aioclient_mock) await setup_integration(hass, aioclient_mock)

View File

@ -22,7 +22,7 @@ from homeassistant.const import (
CONF_PLATFORM, CONF_PLATFORM,
CONF_USERNAME, CONF_USERNAME,
) )
from homeassistant.helpers.typing import HomeAssistantType from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
MODULE_PATH = "homeassistant.components.slack.notify" MODULE_PATH = "homeassistant.components.slack.notify"
@ -47,7 +47,7 @@ def filter_log_records(caplog: LogCaptureFixture) -> list[logging.LogRecord]:
] ]
async def test_setup(hass: HomeAssistantType, caplog: LogCaptureFixture): async def test_setup(hass: HomeAssistant, caplog: LogCaptureFixture):
"""Test setup slack notify.""" """Test setup slack notify."""
config = DEFAULT_CONFIG config = DEFAULT_CONFIG
@ -68,7 +68,7 @@ async def test_setup(hass: HomeAssistantType, caplog: LogCaptureFixture):
client.auth_test.assert_called_once_with() client.auth_test.assert_called_once_with()
async def test_setup_clientError(hass: HomeAssistantType, caplog: LogCaptureFixture): async def test_setup_clientError(hass: HomeAssistant, caplog: LogCaptureFixture):
"""Test setup slack notify with aiohttp.ClientError exception.""" """Test setup slack notify with aiohttp.ClientError exception."""
config = copy.deepcopy(DEFAULT_CONFIG) config = copy.deepcopy(DEFAULT_CONFIG)
config[notify.DOMAIN][0].update({CONF_USERNAME: "user", CONF_ICON: "icon"}) config[notify.DOMAIN][0].update({CONF_USERNAME: "user", CONF_ICON: "icon"})
@ -89,7 +89,7 @@ async def test_setup_clientError(hass: HomeAssistantType, caplog: LogCaptureFixt
assert aiohttp.ClientError.__qualname__ in record.message assert aiohttp.ClientError.__qualname__ in record.message
async def test_setup_slackApiError(hass: HomeAssistantType, caplog: LogCaptureFixture): async def test_setup_slackApiError(hass: HomeAssistant, caplog: LogCaptureFixture):
"""Test setup slack notify with SlackApiError exception.""" """Test setup slack notify with SlackApiError exception."""
config = DEFAULT_CONFIG config = DEFAULT_CONFIG