Add type hints to integration tests (part 19) (#88178)

pull/88194/head
epenet 2023-02-15 18:07:40 +01:00 committed by GitHub
parent f5a05c1bd2
commit 80ee196fd8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
50 changed files with 974 additions and 526 deletions

View File

@ -4,7 +4,8 @@ from unittest.mock import patch
from homeassistant.components.sabnzbd import DEFAULT_NAME, DOMAIN, OLD_SENSOR_KEYS from homeassistant.components.sabnzbd import DEFAULT_NAME, DOMAIN, OLD_SENSOR_KEYS
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.const import CONF_API_KEY, CONF_NAME, CONF_URL from homeassistant.const import CONF_API_KEY, CONF_NAME, CONF_URL
from homeassistant.helpers import device_registry as dr from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
@ -25,7 +26,11 @@ MOCK_ENTRY_VERSION_1 = MockConfigEntry(
) )
async def test_unique_id_migrate(hass, device_registry, entity_registry): async def test_unique_id_migrate(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that config flow entry is migrated correctly.""" """Test that config flow entry is migrated correctly."""
# Start with the config entry at Version 1. # Start with the config entry at Version 1.
mock_entry = MOCK_ENTRY_VERSION_1 mock_entry = MOCK_ENTRY_VERSION_1

View File

@ -968,7 +968,7 @@ async def test_import_legacy_without_name(
@pytest.mark.usefixtures("remotews", "rest_api") @pytest.mark.usefixtures("remotews", "rest_api")
async def test_import_websocket(hass: HomeAssistant): async def test_import_websocket(hass: HomeAssistant) -> None:
"""Test importing from yaml with hostname.""" """Test importing from yaml with hostname."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,
@ -987,7 +987,7 @@ async def test_import_websocket(hass: HomeAssistant):
@pytest.mark.usefixtures("remoteencws") @pytest.mark.usefixtures("remoteencws")
async def test_import_websocket_encrypted(hass: HomeAssistant): async def test_import_websocket_encrypted(hass: HomeAssistant) -> None:
"""Test importing from yaml with hostname.""" """Test importing from yaml with hostname."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,
@ -1007,7 +1007,7 @@ async def test_import_websocket_encrypted(hass: HomeAssistant):
@pytest.mark.usefixtures("remotews", "rest_api") @pytest.mark.usefixtures("remotews", "rest_api")
async def test_import_websocket_without_port(hass: HomeAssistant): async def test_import_websocket_without_port(hass: HomeAssistant) -> None:
"""Test importing from yaml with hostname by no port.""" """Test importing from yaml with hostname by no port."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,
@ -1029,7 +1029,7 @@ async def test_import_websocket_without_port(hass: HomeAssistant):
@pytest.mark.usefixtures("remotews") @pytest.mark.usefixtures("remotews")
async def test_import_unknown_host(hass: HomeAssistant): async def test_import_unknown_host(hass: HomeAssistant) -> None:
"""Test importing from yaml with hostname that does not resolve.""" """Test importing from yaml with hostname that does not resolve."""
with patch( with patch(
"homeassistant.components.samsungtv.config_flow.socket.gethostbyname", "homeassistant.components.samsungtv.config_flow.socket.gethostbyname",

View File

@ -28,7 +28,9 @@ def entities(hass):
return platform.ENTITIES[0:2] return platform.ENTITIES[0:2]
async def test_config_yaml_alias_anchor(hass, entities, enable_custom_integrations): async def test_config_yaml_alias_anchor(
hass: HomeAssistant, entities, enable_custom_integrations: None
) -> None:
"""Test the usage of YAML aliases and anchors. """Test the usage of YAML aliases and anchors.
The following test scene configuration is equivalent to: The following test scene configuration is equivalent to:
@ -73,7 +75,9 @@ async def test_config_yaml_alias_anchor(hass, entities, enable_custom_integratio
assert light_2.last_call("turn_on")[1].get("brightness") == 100 assert light_2.last_call("turn_on")[1].get("brightness") == 100
async def test_config_yaml_bool(hass, entities, enable_custom_integrations): async def test_config_yaml_bool(
hass: HomeAssistant, entities, enable_custom_integrations: None
) -> None:
"""Test parsing of booleans in yaml config.""" """Test parsing of booleans in yaml config."""
light_1, light_2 = await setup_lights(hass, entities) light_1, light_2 = await setup_lights(hass, entities)
@ -100,7 +104,9 @@ async def test_config_yaml_bool(hass, entities, enable_custom_integrations):
assert light_2.last_call("turn_on")[1].get("brightness") == 100 assert light_2.last_call("turn_on")[1].get("brightness") == 100
async def test_activate_scene(hass, entities, enable_custom_integrations): async def test_activate_scene(
hass: HomeAssistant, entities, enable_custom_integrations: None
) -> None:
"""Test active scene.""" """Test active scene."""
light_1, light_2 = await setup_lights(hass, entities) light_1, light_2 = await setup_lights(hass, entities)
@ -152,7 +158,9 @@ async def test_activate_scene(hass, entities, enable_custom_integrations):
assert calls[0].data.get("transition") == 42 assert calls[0].data.get("transition") == 42
async def test_restore_state(hass, entities, enable_custom_integrations): async def test_restore_state(
hass: HomeAssistant, entities, enable_custom_integrations: None
) -> None:
"""Test we restore state integration.""" """Test we restore state integration."""
mock_restore_cache(hass, (State("scene.test", "2021-01-01T23:59:59+00:00"),)) mock_restore_cache(hass, (State("scene.test", "2021-01-01T23:59:59+00:00"),))
@ -179,8 +187,8 @@ async def test_restore_state(hass, entities, enable_custom_integrations):
async def test_restore_state_does_not_restore_unavailable( async def test_restore_state_does_not_restore_unavailable(
hass, entities, enable_custom_integrations hass: HomeAssistant, entities, enable_custom_integrations: None
): ) -> None:
"""Test we restore state integration but ignore unavailable.""" """Test we restore state integration but ignore unavailable."""
mock_restore_cache(hass, (State("scene.test", STATE_UNAVAILABLE),)) mock_restore_cache(hass, (State("scene.test", STATE_UNAVAILABLE),))

View File

@ -3,6 +3,7 @@ from __future__ import annotations
from datetime import timedelta from datetime import timedelta
from homeassistant.components.recorder import Recorder
from homeassistant.components.recorder.db_schema import StateAttributes, States from homeassistant.components.recorder.db_schema import StateAttributes, States
from homeassistant.components.recorder.util import session_scope from homeassistant.components.recorder.util import session_scope
from homeassistant.components.schedule.const import ATTR_NEXT_EVENT, DOMAIN from homeassistant.components.schedule.const import ATTR_NEXT_EVENT, DOMAIN
@ -16,7 +17,7 @@ from tests.components.recorder.common import async_wait_recording_done
async def test_exclude_attributes( async def test_exclude_attributes(
recorder_mock: None, recorder_mock: Recorder,
hass: HomeAssistant, hass: HomeAssistant,
enable_custom_integrations: None, enable_custom_integrations: None,
) -> None: ) -> None:

View File

@ -88,7 +88,9 @@ async def test_scrape_sensor_platform_yaml(hass: HomeAssistant) -> None:
assert state2.state == "secret text" assert state2.state == "secret text"
async def test_scrape_sensor_platform_yaml_no_data(hass: HomeAssistant, caplog) -> None: async def test_scrape_sensor_platform_yaml_no_data(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test Scrape sensor load from sensor platform fetching no data.""" """Test Scrape sensor load from sensor platform fetching no data."""
config = { config = {
SENSOR_DOMAIN: [ SENSOR_DOMAIN: [

View File

@ -103,7 +103,7 @@ async def test_passing_variables(hass: HomeAssistant) -> None:
@pytest.mark.parametrize("toggle", [False, True]) @pytest.mark.parametrize("toggle", [False, True])
async def test_turn_on_off_toggle(hass, toggle): async def test_turn_on_off_toggle(hass: HomeAssistant, toggle) -> None:
"""Verify turn_on, turn_off & toggle services.""" """Verify turn_on, turn_off & toggle services."""
event = "test_event" event = "test_event"
event_mock = Mock() event_mock = Mock()
@ -158,7 +158,7 @@ invalid_configs = [
@pytest.mark.parametrize("value", invalid_configs) @pytest.mark.parametrize("value", invalid_configs)
async def test_setup_with_invalid_configs(hass, value): async def test_setup_with_invalid_configs(hass: HomeAssistant, value) -> None:
"""Test setup with invalid configs.""" """Test setup with invalid configs."""
assert await async_setup_component( assert await async_setup_component(
hass, "script", {"script": value} hass, "script", {"script": value}
@ -198,8 +198,13 @@ async def test_setup_with_invalid_configs(hass, value):
), ),
) )
async def test_bad_config_validation( async def test_bad_config_validation(
hass: HomeAssistant, caplog, object_id, broken_config, problem, details hass: HomeAssistant,
): caplog: pytest.LogCaptureFixture,
object_id,
broken_config,
problem,
details,
) -> None:
"""Test bad script configuration which can be detected during validation.""" """Test bad script configuration which can be detected during validation."""
assert await async_setup_component( assert await async_setup_component(
hass, hass,
@ -229,7 +234,7 @@ async def test_bad_config_validation(
@pytest.mark.parametrize("running", ["no", "same", "different"]) @pytest.mark.parametrize("running", ["no", "same", "different"])
async def test_reload_service(hass, running): async def test_reload_service(hass: HomeAssistant, running) -> None:
"""Verify the reload service.""" """Verify the reload service."""
event = "test_event" event = "test_event"
event_flag = asyncio.Event() event_flag = asyncio.Event()
@ -287,7 +292,7 @@ async def test_reload_service(hass, running):
assert hass.services.has_service(script.DOMAIN, "test") assert hass.services.has_service(script.DOMAIN, "test")
async def test_reload_unchanged_does_not_stop(hass, calls): async def test_reload_unchanged_does_not_stop(hass: HomeAssistant, calls) -> None:
"""Test that reloading stops any running actions as appropriate.""" """Test that reloading stops any running actions as appropriate."""
test_entity = "test.entity" test_entity = "test.entity"
@ -373,7 +378,9 @@ async def test_reload_unchanged_does_not_stop(hass, calls):
}, },
), ),
) )
async def test_reload_unchanged_script(hass, calls, script_config): async def test_reload_unchanged_script(
hass: HomeAssistant, calls, script_config
) -> None:
"""Test an unmodified script is not reloaded.""" """Test an unmodified script is not reloaded."""
with patch( with patch(
"homeassistant.components.script.ScriptEntity", wraps=ScriptEntity "homeassistant.components.script.ScriptEntity", wraps=ScriptEntity
@ -746,7 +753,7 @@ async def test_logbook_humanify_script_started_event(hass: HomeAssistant) -> Non
@pytest.mark.parametrize("concurrently", [False, True]) @pytest.mark.parametrize("concurrently", [False, True])
async def test_concurrent_script(hass, concurrently): async def test_concurrent_script(hass: HomeAssistant, concurrently) -> None:
"""Test calling script concurrently or not.""" """Test calling script concurrently or not."""
if concurrently: if concurrently:
call_script_2 = { call_script_2 = {
@ -1008,7 +1015,9 @@ async def test_script_restore_last_triggered(hass: HomeAssistant) -> None:
(SCRIPT_MODE_SINGLE, "Already running"), (SCRIPT_MODE_SINGLE, "Already running"),
), ),
) )
async def test_recursive_script(hass, script_mode, warning_msg, caplog): async def test_recursive_script(
hass: HomeAssistant, script_mode, warning_msg, caplog: pytest.LogCaptureFixture
) -> None:
"""Test recursive script calls does not deadlock.""" """Test recursive script calls does not deadlock."""
# Make sure we cover all script modes # Make sure we cover all script modes
assert [ assert [
@ -1056,7 +1065,9 @@ async def test_recursive_script(hass, script_mode, warning_msg, caplog):
(SCRIPT_MODE_SINGLE, "Already running"), (SCRIPT_MODE_SINGLE, "Already running"),
), ),
) )
async def test_recursive_script_indirect(hass, script_mode, warning_msg, caplog): async def test_recursive_script_indirect(
hass: HomeAssistant, script_mode, warning_msg, caplog: pytest.LogCaptureFixture
) -> None:
"""Test recursive script calls does not deadlock.""" """Test recursive script calls does not deadlock."""
# Make sure we cover all script modes # Make sure we cover all script modes
assert [ assert [
@ -1116,7 +1127,9 @@ async def test_recursive_script_indirect(hass, script_mode, warning_msg, caplog)
@pytest.mark.parametrize( @pytest.mark.parametrize(
"script_mode", [SCRIPT_MODE_PARALLEL, SCRIPT_MODE_QUEUED, SCRIPT_MODE_RESTART] "script_mode", [SCRIPT_MODE_PARALLEL, SCRIPT_MODE_QUEUED, SCRIPT_MODE_RESTART]
) )
async def test_recursive_script_turn_on(hass: HomeAssistant, script_mode, caplog): async def test_recursive_script_turn_on(
hass: HomeAssistant, script_mode, caplog: pytest.LogCaptureFixture
) -> None:
"""Test script turning itself on. """Test script turning itself on.
- Illegal recursion detection should not be triggered - Illegal recursion detection should not be triggered
@ -1348,8 +1361,12 @@ async def test_script_service_changed_entity_id(hass: HomeAssistant) -> None:
), ),
) )
async def test_blueprint_script_bad_config( async def test_blueprint_script_bad_config(
hass, caplog, blueprint_inputs, problem, details hass: HomeAssistant,
): caplog: pytest.LogCaptureFixture,
blueprint_inputs,
problem,
details,
) -> None:
"""Test blueprint script with bad inputs.""" """Test blueprint script with bad inputs."""
assert await async_setup_component( assert await async_setup_component(
hass, hass,

View File

@ -4,6 +4,7 @@ from __future__ import annotations
import pytest import pytest
from homeassistant.components import script from homeassistant.components import script
from homeassistant.components.recorder import Recorder
from homeassistant.components.recorder.db_schema import StateAttributes, States from homeassistant.components.recorder.db_schema import StateAttributes, States
from homeassistant.components.recorder.util import session_scope from homeassistant.components.recorder.util import session_scope
from homeassistant.components.script import ( from homeassistant.components.script import (
@ -14,7 +15,7 @@ from homeassistant.components.script import (
ATTR_MODE, ATTR_MODE,
) )
from homeassistant.const import ATTR_FRIENDLY_NAME from homeassistant.const import ATTR_FRIENDLY_NAME
from homeassistant.core import Context, State, callback from homeassistant.core import Context, HomeAssistant, State, callback
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import async_mock_service from tests.common import async_mock_service
@ -27,7 +28,9 @@ def calls(hass):
return async_mock_service(hass, "test", "automation") return async_mock_service(hass, "test", "automation")
async def test_exclude_attributes(recorder_mock, hass, calls): async def test_exclude_attributes(
recorder_mock: Recorder, hass: HomeAssistant, calls
) -> None:
"""Test automation registered attributes to be excluded.""" """Test automation registered attributes to be excluded."""
await hass.async_block_till_done() await hass.async_block_till_done()
calls = [] calls = []

View File

@ -11,6 +11,7 @@ from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
from tests.components.blueprint.conftest import stub_blueprint_populate # noqa: F401 from tests.components.blueprint.conftest import stub_blueprint_populate # noqa: F401
from tests.typing import WebSocketGenerator
MOCK_ENTITY_SOURCES = { MOCK_ENTITY_SOURCES = {
"light.platform_config_source": { "light.platform_config_source": {
@ -411,7 +412,7 @@ async def test_area_lookup(
} }
async def test_person_lookup(hass): async def test_person_lookup(hass: HomeAssistant) -> None:
"""Test searching persons.""" """Test searching persons."""
assert await async_setup_component( assert await async_setup_component(
hass, hass,
@ -441,7 +442,7 @@ async def test_person_lookup(hass):
} }
async def test_ws_api(hass, hass_ws_client): async def test_ws_api(hass: HomeAssistant, hass_ws_client: WebSocketGenerator) -> None:
"""Test WS API.""" """Test WS API."""
assert await async_setup_component(hass, "search", {}) assert await async_setup_component(hass, "search", {})

View File

@ -70,12 +70,12 @@ async def test_get_actions(
), ),
) )
async def test_get_actions_hidden_auxiliary( async def test_get_actions_hidden_auxiliary(
hass, hass: HomeAssistant,
device_registry, device_registry: dr.DeviceRegistry,
entity_registry, entity_registry: er.EntityRegistry,
hidden_by, hidden_by,
entity_category, entity_category,
): ) -> None:
"""Test we get the expected actions from a hidden or auxiliary entity.""" """Test we get the expected actions from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)

View File

@ -74,12 +74,12 @@ async def test_get_conditions(
), ),
) )
async def test_get_conditions_hidden_auxiliary( async def test_get_conditions_hidden_auxiliary(
hass, hass: HomeAssistant,
device_registry, device_registry: dr.DeviceRegistry,
entity_registry, entity_registry: er.EntityRegistry,
hidden_by, hidden_by,
entity_category, entity_category,
): ) -> None:
"""Test we get the expected conditions from a hidden or auxiliary entity.""" """Test we get the expected conditions from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)

View File

@ -12,8 +12,11 @@ from homeassistant.components.select.device_trigger import (
) )
from homeassistant.const import EntityCategory from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import config_validation as cv, device_registry as dr from homeassistant.helpers import (
from homeassistant.helpers.entity_registry import EntityRegistry, RegistryEntryHider config_validation as cv,
device_registry as dr,
entity_registry as er,
)
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import ( from tests.common import (
@ -33,7 +36,7 @@ def calls(hass: HomeAssistant) -> list[ServiceCall]:
async def test_get_triggers( async def test_get_triggers(
hass: HomeAssistant, hass: HomeAssistant,
device_registry: dr.DeviceRegistry, device_registry: dr.DeviceRegistry,
entity_registry: EntityRegistry, entity_registry: er.EntityRegistry,
) -> None: ) -> None:
"""Test we get the expected triggers from a select.""" """Test we get the expected triggers from a select."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
@ -64,19 +67,19 @@ async def test_get_triggers(
@pytest.mark.parametrize( @pytest.mark.parametrize(
("hidden_by", "entity_category"), ("hidden_by", "entity_category"),
( (
(RegistryEntryHider.INTEGRATION, None), (er.RegistryEntryHider.INTEGRATION, None),
(RegistryEntryHider.USER, None), (er.RegistryEntryHider.USER, None),
(None, EntityCategory.CONFIG), (None, EntityCategory.CONFIG),
(None, EntityCategory.DIAGNOSTIC), (None, EntityCategory.DIAGNOSTIC),
), ),
) )
async def test_get_triggers_hidden_auxiliary( async def test_get_triggers_hidden_auxiliary(
hass, hass: HomeAssistant,
device_registry, device_registry: dr.DeviceRegistry,
entity_registry, entity_registry: er.EntityRegistry,
hidden_by, hidden_by,
entity_category, entity_category,
): ) -> None:
"""Test we get the expected triggers from a hidden or auxiliary entity.""" """Test we get the expected triggers from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -109,7 +112,7 @@ async def test_get_triggers_hidden_auxiliary(
assert_lists_same(triggers, expected_triggers) assert_lists_same(triggers, expected_triggers)
async def test_if_fires_on_state_change(hass, calls): async def test_if_fires_on_state_change(hass: HomeAssistant, calls) -> None:
"""Test for turn_on and turn_off triggers firing.""" """Test for turn_on and turn_off triggers firing."""
hass.states.async_set( hass.states.async_set(
"select.entity", "option1", {"options": ["option1", "option2", "option3"]} "select.entity", "option1", {"options": ["option1", "option2", "option3"]}

View File

@ -88,7 +88,9 @@ async def test_select(hass: HomeAssistant) -> None:
] ]
async def test_custom_integration_and_validation(hass, enable_custom_integrations): async def test_custom_integration_and_validation(
hass: HomeAssistant, enable_custom_integrations: None
) -> None:
"""Test we can only select valid options.""" """Test we can only select valid options."""
platform = getattr(hass.components, f"test.{DOMAIN}") platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init() platform.init()

View File

@ -4,11 +4,12 @@ from __future__ import annotations
from datetime import timedelta from datetime import timedelta
from homeassistant.components import select from homeassistant.components import select
from homeassistant.components.recorder import Recorder
from homeassistant.components.recorder.db_schema import StateAttributes, States from homeassistant.components.recorder.db_schema import StateAttributes, States
from homeassistant.components.recorder.util import session_scope from homeassistant.components.recorder.util import session_scope
from homeassistant.components.select import ATTR_OPTIONS from homeassistant.components.select import ATTR_OPTIONS
from homeassistant.const import ATTR_FRIENDLY_NAME from homeassistant.const import ATTR_FRIENDLY_NAME
from homeassistant.core import State from homeassistant.core import HomeAssistant, State
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
@ -16,7 +17,7 @@ from tests.common import async_fire_time_changed
from tests.components.recorder.common import async_wait_recording_done from tests.components.recorder.common import async_wait_recording_done
async def test_exclude_attributes(recorder_mock, hass): async def test_exclude_attributes(recorder_mock: Recorder, hass: HomeAssistant) -> None:
"""Test select registered attributes to be excluded.""" """Test select registered attributes to be excluded."""
await async_setup_component( await async_setup_component(
hass, select.DOMAIN, {select.DOMAIN: {"platform": "demo"}} hass, select.DOMAIN, {select.DOMAIN: {"platform": "demo"}}

View File

@ -44,7 +44,7 @@ def mock_sense():
yield mock_sense yield mock_sense
async def test_form(hass, mock_sense): async def test_form(hass: HomeAssistant, mock_sense) -> None:
"""Test we get the form.""" """Test we get the form."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
@ -88,7 +88,7 @@ async def test_form_invalid_auth(hass: HomeAssistant) -> None:
assert result2["errors"] == {"base": "invalid_auth"} assert result2["errors"] == {"base": "invalid_auth"}
async def test_form_mfa_required(hass, mock_sense): async def test_form_mfa_required(hass: HomeAssistant, mock_sense) -> None:
"""Test we handle invalid auth.""" """Test we handle invalid auth."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -115,7 +115,7 @@ async def test_form_mfa_required(hass, mock_sense):
assert result3["data"] == MOCK_CONFIG assert result3["data"] == MOCK_CONFIG
async def test_form_mfa_required_wrong(hass, mock_sense): async def test_form_mfa_required_wrong(hass: HomeAssistant, mock_sense) -> None:
"""Test we handle invalid auth.""" """Test we handle invalid auth."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -143,7 +143,7 @@ async def test_form_mfa_required_wrong(hass, mock_sense):
assert result3["step_id"] == "validation" assert result3["step_id"] == "validation"
async def test_form_mfa_required_timeout(hass, mock_sense): async def test_form_mfa_required_timeout(hass: HomeAssistant, mock_sense) -> None:
"""Test we handle invalid auth.""" """Test we handle invalid auth."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -169,7 +169,7 @@ async def test_form_mfa_required_timeout(hass, mock_sense):
assert result3["errors"] == {"base": "cannot_connect"} assert result3["errors"] == {"base": "cannot_connect"}
async def test_form_mfa_required_exception(hass, mock_sense): async def test_form_mfa_required_exception(hass: HomeAssistant, mock_sense) -> None:
"""Test we handle invalid auth.""" """Test we handle invalid auth."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -252,7 +252,7 @@ async def test_form_unknown_exception(hass: HomeAssistant) -> None:
assert result2["errors"] == {"base": "unknown"} assert result2["errors"] == {"base": "unknown"}
async def test_reauth_no_form(hass, mock_sense): async def test_reauth_no_form(hass: HomeAssistant, mock_sense) -> None:
"""Test reauth where no form needed.""" """Test reauth where no form needed."""
# set up initially # set up initially
@ -273,7 +273,7 @@ async def test_reauth_no_form(hass, mock_sense):
assert result["reason"] == "reauth_successful" assert result["reason"] == "reauth_successful"
async def test_reauth_password(hass, mock_sense): async def test_reauth_password(hass: HomeAssistant, mock_sense) -> None:
"""Test reauth form.""" """Test reauth form."""
# set up initially # set up initially

View File

@ -10,7 +10,7 @@ from tests.typing import ClientSessionGenerator
async def test_diagnostics( async def test_diagnostics(
hass: HomeAssistant, hass_client: ClientSessionGenerator, load_int: ConfigEntry hass: HomeAssistant, hass_client: ClientSessionGenerator, load_int: ConfigEntry
): ) -> None:
"""Test generating diagnostics for a config entry.""" """Test generating diagnostics for a config entry."""
entry = load_int entry = load_int

View File

@ -13,7 +13,7 @@ from tests.common import MockConfigEntry
from tests.components.bluetooth import inject_bluetooth_service_info from tests.components.bluetooth import inject_bluetooth_service_info
async def test_sensors(enable_bluetooth, hass: HomeAssistant): async def test_sensors(enable_bluetooth: None, hass: HomeAssistant) -> None:
"""Test the Sensirion BLE sensors.""" """Test the Sensirion BLE sensors."""
entry = MockConfigEntry(domain=DOMAIN, unique_id=SENSIRION_SERVICE_INFO.address) entry = MockConfigEntry(domain=DOMAIN, unique_id=SENSIRION_SERVICE_INFO.address)
entry.add_to_hass(hass) entry.add_to_hass(hass)

View File

@ -11,7 +11,8 @@ from homeassistant.components.sensor import (
) )
from homeassistant.components.sensor.device_condition import ENTITY_CONDITIONS from homeassistant.components.sensor.device_condition import ENTITY_CONDITIONS
from homeassistant.const import CONF_PLATFORM, PERCENTAGE, STATE_UNKNOWN, EntityCategory from homeassistant.const import CONF_PLATFORM, PERCENTAGE, STATE_UNKNOWN, EntityCategory
from homeassistant.helpers import device_registry as dr from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.entity_registry import RegistryEntryHider from homeassistant.helpers.entity_registry import RegistryEntryHider
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -33,8 +34,11 @@ def calls(hass):
async def test_get_conditions( async def test_get_conditions(
hass, device_registry, entity_registry, enable_custom_integrations hass: HomeAssistant,
): device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
enable_custom_integrations: None,
) -> None:
"""Test we get the expected conditions from a sensor.""" """Test we get the expected conditions from a sensor."""
platform = getattr(hass.components, f"test.{DOMAIN}") platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init() platform.init()
@ -86,12 +90,12 @@ async def test_get_conditions(
), ),
) )
async def test_get_conditions_hidden_auxiliary( async def test_get_conditions_hidden_auxiliary(
hass, hass: HomeAssistant,
device_registry, device_registry: dr.DeviceRegistry,
entity_registry, entity_registry: er.EntityRegistry,
hidden_by, hidden_by,
entity_category, entity_category,
): ) -> None:
"""Test we get the expected conditions from a hidden or auxiliary entity.""" """Test we get the expected conditions from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -125,7 +129,11 @@ async def test_get_conditions_hidden_auxiliary(
assert_lists_same(conditions, expected_conditions) assert_lists_same(conditions, expected_conditions)
async def test_get_conditions_no_state(hass, device_registry, entity_registry): async def test_get_conditions_no_state(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected conditions from a sensor.""" """Test we get the expected conditions from a sensor."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -177,13 +185,13 @@ async def test_get_conditions_no_state(hass, device_registry, entity_registry):
), ),
) )
async def test_get_conditions_no_unit_or_stateclass( async def test_get_conditions_no_unit_or_stateclass(
hass, hass: HomeAssistant,
device_registry, device_registry: dr.DeviceRegistry,
entity_registry, entity_registry: er.EntityRegistry,
state_class, state_class,
unit, unit,
condition_types, condition_types,
): ) -> None:
"""Test we get the expected conditions from an entity with no unit or state class.""" """Test we get the expected conditions from an entity with no unit or state class."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -224,15 +232,15 @@ async def test_get_conditions_no_unit_or_stateclass(
], ],
) )
async def test_get_condition_capabilities( async def test_get_condition_capabilities(
hass, hass: HomeAssistant,
device_registry, device_registry: dr.DeviceRegistry,
entity_registry, entity_registry: er.EntityRegistry,
set_state, set_state,
device_class_reg, device_class_reg,
device_class_state, device_class_state,
unit_reg, unit_reg,
unit_state, unit_state,
): ) -> None:
"""Test we get the expected capabilities from a sensor condition.""" """Test we get the expected capabilities from a sensor condition."""
platform = getattr(hass.components, f"test.{DOMAIN}") platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init() platform.init()
@ -285,7 +293,9 @@ async def test_get_condition_capabilities(
assert capabilities == expected_capabilities assert capabilities == expected_capabilities
async def test_get_condition_capabilities_none(hass, enable_custom_integrations): async def test_get_condition_capabilities_none(
hass: HomeAssistant, enable_custom_integrations: None
) -> None:
"""Test we get the expected capabilities from a sensor condition.""" """Test we get the expected capabilities from a sensor condition."""
platform = getattr(hass.components, f"test.{DOMAIN}") platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init() platform.init()
@ -322,8 +332,11 @@ async def test_get_condition_capabilities_none(hass, enable_custom_integrations)
async def test_if_state_not_above_below( async def test_if_state_not_above_below(
hass, calls, caplog, enable_custom_integrations hass: HomeAssistant,
): calls,
caplog: pytest.LogCaptureFixture,
enable_custom_integrations: None,
) -> None:
"""Test for bad value conditions.""" """Test for bad value conditions."""
platform = getattr(hass.components, f"test.{DOMAIN}") platform = getattr(hass.components, f"test.{DOMAIN}")
@ -357,7 +370,9 @@ async def test_if_state_not_above_below(
assert "must contain at least one of below, above" in caplog.text assert "must contain at least one of below, above" in caplog.text
async def test_if_state_above(hass, calls, enable_custom_integrations): async def test_if_state_above(
hass: HomeAssistant, calls, enable_custom_integrations: None
) -> None:
"""Test for value conditions.""" """Test for value conditions."""
platform = getattr(hass.components, f"test.{DOMAIN}") platform = getattr(hass.components, f"test.{DOMAIN}")
@ -415,7 +430,9 @@ async def test_if_state_above(hass, calls, enable_custom_integrations):
assert calls[0].data["some"] == "event - test_event1" assert calls[0].data["some"] == "event - test_event1"
async def test_if_state_below(hass, calls, enable_custom_integrations): async def test_if_state_below(
hass: HomeAssistant, calls, enable_custom_integrations: None
) -> None:
"""Test for value conditions.""" """Test for value conditions."""
platform = getattr(hass.components, f"test.{DOMAIN}") platform = getattr(hass.components, f"test.{DOMAIN}")
@ -473,7 +490,9 @@ async def test_if_state_below(hass, calls, enable_custom_integrations):
assert calls[0].data["some"] == "event - test_event1" assert calls[0].data["some"] == "event - test_event1"
async def test_if_state_between(hass, calls, enable_custom_integrations): async def test_if_state_between(
hass: HomeAssistant, calls, enable_custom_integrations: None
) -> None:
"""Test for value conditions.""" """Test for value conditions."""
platform = getattr(hass.components, f"test.{DOMAIN}") platform = getattr(hass.components, f"test.{DOMAIN}")

View File

@ -13,7 +13,8 @@ from homeassistant.components.sensor import (
) )
from homeassistant.components.sensor.device_trigger import ENTITY_TRIGGERS from homeassistant.components.sensor.device_trigger import ENTITY_TRIGGERS
from homeassistant.const import CONF_PLATFORM, PERCENTAGE, STATE_UNKNOWN, EntityCategory from homeassistant.const import CONF_PLATFORM, PERCENTAGE, STATE_UNKNOWN, EntityCategory
from homeassistant.helpers import device_registry as dr from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.entity_registry import RegistryEntryHider from homeassistant.helpers.entity_registry import RegistryEntryHider
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
@ -37,8 +38,11 @@ def calls(hass):
async def test_get_triggers( async def test_get_triggers(
hass, device_registry, entity_registry, enable_custom_integrations hass: HomeAssistant,
): device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
enable_custom_integrations: None,
) -> None:
"""Test we get the expected triggers from a sensor.""" """Test we get the expected triggers from a sensor."""
platform = getattr(hass.components, f"test.{DOMAIN}") platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init() platform.init()
@ -90,12 +94,12 @@ async def test_get_triggers(
), ),
) )
async def test_get_triggers_hidden_auxiliary( async def test_get_triggers_hidden_auxiliary(
hass, hass: HomeAssistant,
device_registry, device_registry: dr.DeviceRegistry,
entity_registry, entity_registry: er.EntityRegistry,
hidden_by, hidden_by,
entity_category, entity_category,
): ) -> None:
"""Test we get the expected triggers from a hidden or auxiliary entity.""" """Test we get the expected triggers from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -140,13 +144,13 @@ async def test_get_triggers_hidden_auxiliary(
), ),
) )
async def test_get_triggers_no_unit_or_stateclass( async def test_get_triggers_no_unit_or_stateclass(
hass, hass: HomeAssistant,
device_registry, device_registry: dr.DeviceRegistry,
entity_registry, entity_registry: er.EntityRegistry,
state_class, state_class,
unit, unit,
trigger_types, trigger_types,
): ) -> None:
"""Test we get the expected triggers from an entity with no unit or state class.""" """Test we get the expected triggers from an entity with no unit or state class."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -187,15 +191,15 @@ async def test_get_triggers_no_unit_or_stateclass(
], ],
) )
async def test_get_trigger_capabilities( async def test_get_trigger_capabilities(
hass, hass: HomeAssistant,
device_registry, device_registry: dr.DeviceRegistry,
entity_registry, entity_registry: er.EntityRegistry,
set_state, set_state,
device_class_reg, device_class_reg,
device_class_state, device_class_state,
unit_reg, unit_reg,
unit_state, unit_state,
): ) -> None:
"""Test we get the expected capabilities from a sensor trigger.""" """Test we get the expected capabilities from a sensor trigger."""
platform = getattr(hass.components, f"test.{DOMAIN}") platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init() platform.init()
@ -249,7 +253,9 @@ async def test_get_trigger_capabilities(
assert capabilities == expected_capabilities assert capabilities == expected_capabilities
async def test_get_trigger_capabilities_none(hass, enable_custom_integrations): async def test_get_trigger_capabilities_none(
hass: HomeAssistant, enable_custom_integrations: None
) -> None:
"""Test we get the expected capabilities from a sensor trigger.""" """Test we get the expected capabilities from a sensor trigger."""
platform = getattr(hass.components, f"test.{DOMAIN}") platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init() platform.init()
@ -286,8 +292,11 @@ async def test_get_trigger_capabilities_none(hass, enable_custom_integrations):
async def test_if_fires_not_on_above_below( async def test_if_fires_not_on_above_below(
hass, calls, caplog, enable_custom_integrations hass: HomeAssistant,
): calls,
caplog: pytest.LogCaptureFixture,
enable_custom_integrations: None,
) -> None:
"""Test for value triggers firing.""" """Test for value triggers firing."""
platform = getattr(hass.components, f"test.{DOMAIN}") platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init() platform.init()
@ -317,7 +326,9 @@ async def test_if_fires_not_on_above_below(
assert "must contain at least one of below, above" in caplog.text assert "must contain at least one of below, above" in caplog.text
async def test_if_fires_on_state_above(hass, calls, enable_custom_integrations): async def test_if_fires_on_state_above(
hass: HomeAssistant, calls, enable_custom_integrations: None
) -> None:
"""Test for value triggers firing.""" """Test for value triggers firing."""
platform = getattr(hass.components, f"test.{DOMAIN}") platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init() platform.init()
@ -375,7 +386,9 @@ async def test_if_fires_on_state_above(hass, calls, enable_custom_integrations):
) )
async def test_if_fires_on_state_below(hass, calls, enable_custom_integrations): async def test_if_fires_on_state_below(
hass: HomeAssistant, calls, enable_custom_integrations: None
) -> None:
"""Test for value triggers firing.""" """Test for value triggers firing."""
platform = getattr(hass.components, f"test.{DOMAIN}") platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init() platform.init()
@ -433,7 +446,9 @@ async def test_if_fires_on_state_below(hass, calls, enable_custom_integrations):
) )
async def test_if_fires_on_state_between(hass, calls, enable_custom_integrations): async def test_if_fires_on_state_between(
hass: HomeAssistant, calls, enable_custom_integrations: None
) -> None:
"""Test for value triggers firing.""" """Test for value triggers firing."""
platform = getattr(hass.components, f"test.{DOMAIN}") platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init() platform.init()
@ -504,8 +519,8 @@ async def test_if_fires_on_state_between(hass, calls, enable_custom_integrations
async def test_if_fires_on_state_change_with_for( async def test_if_fires_on_state_change_with_for(
hass, calls, enable_custom_integrations hass: HomeAssistant, calls, enable_custom_integrations: None
): ) -> None:
"""Test for triggers firing with delay.""" """Test for triggers firing with delay."""
platform = getattr(hass.components, f"test.{DOMAIN}") platform = getattr(hass.components, f"test.{DOMAIN}")

View File

@ -1,9 +1,11 @@
"""The test for sensor helpers.""" """The test for sensor helpers."""
import pytest
from homeassistant.components.sensor import SensorDeviceClass from homeassistant.components.sensor import SensorDeviceClass
from homeassistant.components.sensor.helpers import async_parse_date_datetime from homeassistant.components.sensor.helpers import async_parse_date_datetime
def test_async_parse_datetime(caplog): def test_async_parse_datetime(caplog: pytest.LogCaptureFixture) -> None:
"""Test async_parse_date_datetime.""" """Test async_parse_date_datetime."""
entity_id = "sensor.timestamp" entity_id = "sensor.timestamp"
device_class = SensorDeviceClass.TIMESTAMP device_class = SensorDeviceClass.TIMESTAMP

View File

@ -72,14 +72,14 @@ from tests.common import mock_restore_cache_with_extra_data
], ],
) )
async def test_temperature_conversion( async def test_temperature_conversion(
hass, hass: HomeAssistant,
enable_custom_integrations, enable_custom_integrations: None,
unit_system, unit_system,
native_unit, native_unit,
state_unit, state_unit,
native_value, native_value,
state_value, state_value,
): ) -> None:
"""Test temperature conversion.""" """Test temperature conversion."""
hass.config.units = unit_system hass.config.units = unit_system
platform = getattr(hass.components, "test.sensor") platform = getattr(hass.components, "test.sensor")
@ -102,8 +102,8 @@ async def test_temperature_conversion(
@pytest.mark.parametrize("device_class", (None, SensorDeviceClass.PRESSURE)) @pytest.mark.parametrize("device_class", (None, SensorDeviceClass.PRESSURE))
async def test_temperature_conversion_wrong_device_class( async def test_temperature_conversion_wrong_device_class(
hass, device_class, enable_custom_integrations hass: HomeAssistant, device_class, enable_custom_integrations: None
): ) -> None:
"""Test temperatures are not converted if the sensor has wrong device class.""" """Test temperatures are not converted if the sensor has wrong device class."""
platform = getattr(hass.components, "test.sensor") platform = getattr(hass.components, "test.sensor")
platform.init(empty=True) platform.init(empty=True)
@ -126,8 +126,11 @@ async def test_temperature_conversion_wrong_device_class(
@pytest.mark.parametrize("state_class", ("measurement", "total_increasing")) @pytest.mark.parametrize("state_class", ("measurement", "total_increasing"))
async def test_deprecated_last_reset( async def test_deprecated_last_reset(
hass, caplog, enable_custom_integrations, state_class hass: HomeAssistant,
): caplog: pytest.LogCaptureFixture,
enable_custom_integrations: None,
state_class,
) -> None:
"""Test warning on deprecated last reset.""" """Test warning on deprecated last reset."""
platform = getattr(hass.components, "test.sensor") platform = getattr(hass.components, "test.sensor")
platform.init(empty=True) platform.init(empty=True)
@ -150,7 +153,11 @@ async def test_deprecated_last_reset(
assert "last_reset" not in state.attributes assert "last_reset" not in state.attributes
async def test_datetime_conversion(hass, caplog, enable_custom_integrations): async def test_datetime_conversion(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
enable_custom_integrations: None,
) -> None:
"""Test conversion of datetime.""" """Test conversion of datetime."""
test_timestamp = datetime(2017, 12, 19, 18, 29, 42, tzinfo=timezone.utc) test_timestamp = datetime(2017, 12, 19, 18, 29, 42, tzinfo=timezone.utc)
test_local_timestamp = test_timestamp.astimezone( test_local_timestamp = test_timestamp.astimezone(
@ -206,8 +213,13 @@ async def test_datetime_conversion(hass, caplog, enable_custom_integrations):
], ],
) )
async def test_deprecated_datetime_str( async def test_deprecated_datetime_str(
hass, caplog, enable_custom_integrations, device_class, state_value, provides hass: HomeAssistant,
): caplog: pytest.LogCaptureFixture,
enable_custom_integrations: None,
device_class,
state_value,
provides,
) -> None:
"""Test warning on deprecated str for a date(time) value.""" """Test warning on deprecated str for a date(time) value."""
platform = getattr(hass.components, "test.sensor") platform = getattr(hass.components, "test.sensor")
platform.init(empty=True) platform.init(empty=True)
@ -225,8 +237,10 @@ async def test_deprecated_datetime_str(
async def test_reject_timezoneless_datetime_str( async def test_reject_timezoneless_datetime_str(
hass, caplog, enable_custom_integrations hass: HomeAssistant,
): caplog: pytest.LogCaptureFixture,
enable_custom_integrations: None,
) -> None:
"""Test rejection of timezone-less datetime objects as timestamp.""" """Test rejection of timezone-less datetime objects as timestamp."""
test_timestamp = datetime(2017, 12, 19, 18, 29, 42, tzinfo=None) test_timestamp = datetime(2017, 12, 19, 18, 29, 42, tzinfo=None)
platform = getattr(hass.components, "test.sensor") platform = getattr(hass.components, "test.sensor")
@ -318,15 +332,15 @@ RESTORE_DATA = {
], ],
) )
async def test_restore_sensor_save_state( async def test_restore_sensor_save_state(
hass, hass: HomeAssistant,
enable_custom_integrations, enable_custom_integrations: None,
hass_storage, hass_storage: dict[str, Any],
native_value, native_value,
native_value_type, native_value_type,
expected_extra_data, expected_extra_data,
device_class, device_class,
uom, uom,
): ) -> None:
"""Test RestoreSensor.""" """Test RestoreSensor."""
platform = getattr(hass.components, "test.sensor") platform = getattr(hass.components, "test.sensor")
platform.init(empty=True) platform.init(empty=True)
@ -387,15 +401,15 @@ async def test_restore_sensor_save_state(
], ],
) )
async def test_restore_sensor_restore_state( async def test_restore_sensor_restore_state(
hass, hass: HomeAssistant,
enable_custom_integrations, enable_custom_integrations: None,
hass_storage, hass_storage: dict[str, Any],
native_value, native_value,
native_value_type, native_value_type,
extra_data, extra_data,
device_class, device_class,
uom, uom,
): ) -> None:
"""Test RestoreSensor.""" """Test RestoreSensor."""
mock_restore_cache_with_extra_data(hass, ((State("sensor.test", ""), extra_data),)) mock_restore_cache_with_extra_data(hass, ((State("sensor.test", ""), extra_data),))
@ -488,15 +502,15 @@ async def test_restore_sensor_restore_state(
], ],
) )
async def test_custom_unit( async def test_custom_unit(
hass, hass: HomeAssistant,
enable_custom_integrations, enable_custom_integrations: None,
device_class, device_class,
native_unit, native_unit,
custom_unit, custom_unit,
state_unit, state_unit,
native_value, native_value,
custom_state, custom_state,
): ) -> None:
"""Test custom unit.""" """Test custom unit."""
entity_registry = er.async_get(hass) entity_registry = er.async_get(hass)
@ -746,8 +760,8 @@ async def test_custom_unit(
], ],
) )
async def test_custom_unit_change( async def test_custom_unit_change(
hass, hass: HomeAssistant,
enable_custom_integrations, enable_custom_integrations: None,
native_unit, native_unit,
custom_unit, custom_unit,
state_unit, state_unit,
@ -755,7 +769,7 @@ async def test_custom_unit_change(
native_state, native_state,
custom_state, custom_state,
device_class, device_class,
): ) -> None:
"""Test custom unit changes are picked up.""" """Test custom unit changes are picked up."""
entity_registry = er.async_get(hass) entity_registry = er.async_get(hass)
platform = getattr(hass.components, "test.sensor") platform = getattr(hass.components, "test.sensor")
@ -834,8 +848,8 @@ async def test_custom_unit_change(
], ],
) )
async def test_unit_conversion_priority( async def test_unit_conversion_priority(
hass, hass: HomeAssistant,
enable_custom_integrations, enable_custom_integrations: None,
unit_system, unit_system,
native_unit, native_unit,
automatic_unit, automatic_unit,
@ -847,7 +861,7 @@ async def test_unit_conversion_priority(
suggested_state, suggested_state,
custom_state, custom_state,
device_class, device_class,
): ) -> None:
"""Test priority of unit conversion.""" """Test priority of unit conversion."""
hass.config.units = unit_system hass.config.units = unit_system
@ -979,8 +993,8 @@ async def test_unit_conversion_priority(
], ],
) )
async def test_unit_conversion_priority_precision( async def test_unit_conversion_priority_precision(
hass, hass: HomeAssistant,
enable_custom_integrations, enable_custom_integrations: None,
unit_system, unit_system,
native_unit, native_unit,
automatic_unit, automatic_unit,
@ -993,7 +1007,7 @@ async def test_unit_conversion_priority_precision(
suggested_state, suggested_state,
custom_state, custom_state,
device_class, device_class,
): ) -> None:
"""Test priority of unit conversion for sensors with suggested_display_precision.""" """Test priority of unit conversion for sensors with suggested_display_precision."""
hass.config.units = unit_system hass.config.units = unit_system
@ -1121,8 +1135,8 @@ async def test_unit_conversion_priority_precision(
], ],
) )
async def test_unit_conversion_priority_suggested_unit_change( async def test_unit_conversion_priority_suggested_unit_change(
hass, hass: HomeAssistant,
enable_custom_integrations, enable_custom_integrations: None,
unit_system, unit_system,
native_unit, native_unit,
original_unit, original_unit,
@ -1130,7 +1144,7 @@ async def test_unit_conversion_priority_suggested_unit_change(
native_value, native_value,
original_value, original_value,
device_class, device_class,
): ) -> None:
"""Test priority of unit conversion.""" """Test priority of unit conversion."""
hass.config.units = unit_system hass.config.units = unit_system
@ -1220,8 +1234,8 @@ async def test_unit_conversion_priority_suggested_unit_change(
], ],
) )
async def test_suggested_precision_option( async def test_suggested_precision_option(
hass, hass: HomeAssistant,
enable_custom_integrations, enable_custom_integrations: None,
unit_system, unit_system,
native_unit, native_unit,
integration_suggested_precision, integration_suggested_precision,
@ -1229,7 +1243,7 @@ async def test_suggested_precision_option(
native_value, native_value,
device_class, device_class,
extra_options, extra_options,
): ) -> None:
"""Test suggested precision is stored in the registry.""" """Test suggested precision is stored in the registry."""
hass.config.units = unit_system hass.config.units = unit_system
@ -1298,8 +1312,8 @@ async def test_suggested_precision_option(
], ],
) )
async def test_suggested_precision_option_update( async def test_suggested_precision_option_update(
hass, hass: HomeAssistant,
enable_custom_integrations, enable_custom_integrations: None,
unit_system, unit_system,
native_unit, native_unit,
suggested_unit, suggested_unit,
@ -1309,7 +1323,7 @@ async def test_suggested_precision_option_update(
native_value, native_value,
device_class, device_class,
extra_options, extra_options,
): ) -> None:
"""Test suggested precision stored in the registry is updated.""" """Test suggested precision stored in the registry is updated."""
hass.config.units = unit_system hass.config.units = unit_system
@ -1390,15 +1404,15 @@ async def test_suggested_precision_option_update(
], ],
) )
async def test_unit_conversion_priority_legacy_conversion_removed( async def test_unit_conversion_priority_legacy_conversion_removed(
hass, hass: HomeAssistant,
enable_custom_integrations, enable_custom_integrations: None,
unit_system, unit_system,
native_unit, native_unit,
original_unit, original_unit,
native_value, native_value,
original_value, original_value,
device_class, device_class,
): ) -> None:
"""Test priority of unit conversion.""" """Test priority of unit conversion."""
hass.config.units = unit_system hass.config.units = unit_system
@ -1441,7 +1455,7 @@ async def test_value_unknown_in_enumeration(
hass: HomeAssistant, hass: HomeAssistant,
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
enable_custom_integrations: None, enable_custom_integrations: None,
): ) -> None:
"""Test warning on invalid enum value.""" """Test warning on invalid enum value."""
platform = getattr(hass.components, "test.sensor") platform = getattr(hass.components, "test.sensor")
platform.init(empty=True) platform.init(empty=True)
@ -1465,7 +1479,7 @@ async def test_invalid_enumeration_entity_with_device_class(
hass: HomeAssistant, hass: HomeAssistant,
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
enable_custom_integrations: None, enable_custom_integrations: None,
): ) -> None:
"""Test warning on entities that provide an enum with a device class.""" """Test warning on entities that provide an enum with a device class."""
platform = getattr(hass.components, "test.sensor") platform = getattr(hass.components, "test.sensor")
platform.init(empty=True) platform.init(empty=True)
@ -1489,7 +1503,7 @@ async def test_invalid_enumeration_entity_without_device_class(
hass: HomeAssistant, hass: HomeAssistant,
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
enable_custom_integrations: None, enable_custom_integrations: None,
): ) -> None:
"""Test warning on entities that provide an enum without a device class.""" """Test warning on entities that provide an enum without a device class."""
platform = getattr(hass.components, "test.sensor") platform = getattr(hass.components, "test.sensor")
platform.init(empty=True) platform.init(empty=True)
@ -1521,7 +1535,7 @@ async def test_non_numeric_device_class_with_unit_of_measurement(
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
enable_custom_integrations: None, enable_custom_integrations: None,
device_class: SensorDeviceClass, device_class: SensorDeviceClass,
): ) -> None:
"""Test error on numeric entities that provide an unit of measurement.""" """Test error on numeric entities that provide an unit of measurement."""
platform = getattr(hass.components, "test.sensor") platform = getattr(hass.components, "test.sensor")
platform.init(empty=True) platform.init(empty=True)
@ -1594,7 +1608,7 @@ async def test_device_classes_with_invalid_unit_of_measurement(
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
enable_custom_integrations: None, enable_custom_integrations: None,
device_class: SensorDeviceClass, device_class: SensorDeviceClass,
): ) -> None:
"""Test error when unit of measurement is not valid for used device class.""" """Test error when unit of measurement is not valid for used device class."""
platform = getattr(hass.components, "test.sensor") platform = getattr(hass.components, "test.sensor")
platform.init(empty=True) platform.init(empty=True)
@ -1804,7 +1818,7 @@ async def test_device_classes_with_invalid_state_class(
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
enable_custom_integrations: None, enable_custom_integrations: None,
device_class: SensorDeviceClass, device_class: SensorDeviceClass,
): ) -> None:
"""Test error when unit of measurement is not valid for used device class.""" """Test error when unit of measurement is not valid for used device class."""
platform = getattr(hass.components, "test.sensor") platform = getattr(hass.components, "test.sensor")
platform.init(empty=True) platform.init(empty=True)
@ -1916,8 +1930,8 @@ async def test_numeric_state_expected_helper(
], ],
) )
async def test_unit_conversion_update( async def test_unit_conversion_update(
hass, hass: HomeAssistant,
enable_custom_integrations, enable_custom_integrations: None,
unit_system_1, unit_system_1,
unit_system_2, unit_system_2,
native_unit, native_unit,
@ -1931,7 +1945,7 @@ async def test_unit_conversion_update(
suggested_state, suggested_state,
custom_state, custom_state,
device_class, device_class,
): ) -> None:
"""Test suggested unit can be updated.""" """Test suggested unit can be updated."""
hass.config.units = unit_system_1 hass.config.units = unit_system_1

View File

@ -1,4 +1,6 @@
"""The tests for sensor recorder platform.""" """The tests for sensor recorder platform."""
from collections.abc import Callable
# pylint: disable=invalid-name # pylint: disable=invalid-name
from datetime import datetime, timedelta from datetime import datetime, timedelta
import math import math
@ -8,7 +10,11 @@ from unittest.mock import patch
import pytest import pytest
from homeassistant import loader from homeassistant import loader
from homeassistant.components.recorder import DOMAIN as RECORDER_DOMAIN, history from homeassistant.components.recorder import (
DOMAIN as RECORDER_DOMAIN,
Recorder,
history,
)
from homeassistant.components.recorder.db_schema import ( from homeassistant.components.recorder.db_schema import (
StateAttributes, StateAttributes,
States, States,
@ -42,6 +48,7 @@ from tests.components.recorder.common import (
statistics_during_period, statistics_during_period,
wait_recording_done, wait_recording_done,
) )
from tests.typing import WebSocketGenerator
BATTERY_SENSOR_ATTRIBUTES = { BATTERY_SENSOR_ATTRIBUTES = {
"device_class": "battery", "device_class": "battery",
@ -127,8 +134,8 @@ def set_time_zone():
], ],
) )
def test_compile_hourly_statistics( def test_compile_hourly_statistics(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
device_class, device_class,
state_unit, state_unit,
display_unit, display_unit,
@ -137,7 +144,7 @@ def test_compile_hourly_statistics(
mean, mean,
min, min,
max, max,
): ) -> None:
"""Test compiling hourly statistics.""" """Test compiling hourly statistics."""
zero = dt_util.utcnow() zero = dt_util.utcnow()
hass = hass_recorder() hass = hass_recorder()
@ -192,14 +199,14 @@ def test_compile_hourly_statistics(
], ],
) )
def test_compile_hourly_statistics_purged_state_changes( def test_compile_hourly_statistics_purged_state_changes(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
device_class, device_class,
state_unit, state_unit,
display_unit, display_unit,
statistics_unit, statistics_unit,
unit_class, unit_class,
): ) -> None:
"""Test compiling hourly statistics.""" """Test compiling hourly statistics."""
zero = dt_util.utcnow() zero = dt_util.utcnow()
hass = hass_recorder() hass = hass_recorder()
@ -260,7 +267,11 @@ def test_compile_hourly_statistics_purged_state_changes(
@pytest.mark.parametrize("attributes", [TEMPERATURE_SENSOR_ATTRIBUTES]) @pytest.mark.parametrize("attributes", [TEMPERATURE_SENSOR_ATTRIBUTES])
def test_compile_hourly_statistics_wrong_unit(hass_recorder, caplog, attributes): def test_compile_hourly_statistics_wrong_unit(
hass_recorder: Callable[..., HomeAssistant],
caplog: pytest.LogCaptureFixture,
attributes,
) -> None:
"""Test compiling hourly statistics for sensor with unit not matching device class.""" """Test compiling hourly statistics for sensor with unit not matching device class."""
zero = dt_util.utcnow() zero = dt_util.utcnow()
hass = hass_recorder() hass = hass_recorder()
@ -447,10 +458,10 @@ def test_compile_hourly_statistics_wrong_unit(hass_recorder, caplog, attributes)
], ],
) )
async def test_compile_hourly_sum_statistics_amount( async def test_compile_hourly_sum_statistics_amount(
recorder_mock, recorder_mock: Recorder,
hass, hass: HomeAssistant,
hass_ws_client, hass_ws_client: WebSocketGenerator,
caplog, caplog: pytest.LogCaptureFixture,
units, units,
state_class, state_class,
device_class, device_class,
@ -459,7 +470,7 @@ async def test_compile_hourly_sum_statistics_amount(
statistics_unit, statistics_unit,
unit_class, unit_class,
factor, factor,
): ) -> None:
"""Test compiling hourly statistics.""" """Test compiling hourly statistics."""
period0 = dt_util.utcnow() period0 = dt_util.utcnow()
period0_end = period1 = period0 + timedelta(minutes=5) period0_end = period1 = period0 + timedelta(minutes=5)
@ -622,8 +633,8 @@ async def test_compile_hourly_sum_statistics_amount(
], ],
) )
def test_compile_hourly_sum_statistics_amount_reset_every_state_change( def test_compile_hourly_sum_statistics_amount_reset_every_state_change(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
state_class, state_class,
device_class, device_class,
state_unit, state_unit,
@ -631,7 +642,7 @@ def test_compile_hourly_sum_statistics_amount_reset_every_state_change(
statistics_unit, statistics_unit,
unit_class, unit_class,
factor, factor,
): ) -> None:
"""Test compiling hourly statistics.""" """Test compiling hourly statistics."""
zero = dt_util.utcnow() zero = dt_util.utcnow()
hass = hass_recorder() hass = hass_recorder()
@ -736,8 +747,8 @@ def test_compile_hourly_sum_statistics_amount_reset_every_state_change(
], ],
) )
def test_compile_hourly_sum_statistics_amount_invalid_last_reset( def test_compile_hourly_sum_statistics_amount_invalid_last_reset(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
state_class, state_class,
device_class, device_class,
state_unit, state_unit,
@ -745,7 +756,7 @@ def test_compile_hourly_sum_statistics_amount_invalid_last_reset(
statistics_unit, statistics_unit,
unit_class, unit_class,
factor, factor,
): ) -> None:
"""Test compiling hourly statistics.""" """Test compiling hourly statistics."""
zero = dt_util.utcnow() zero = dt_util.utcnow()
hass = hass_recorder() hass = hass_recorder()
@ -826,8 +837,8 @@ def test_compile_hourly_sum_statistics_amount_invalid_last_reset(
], ],
) )
def test_compile_hourly_sum_statistics_nan_inf_state( def test_compile_hourly_sum_statistics_nan_inf_state(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
state_class, state_class,
device_class, device_class,
state_unit, state_unit,
@ -835,7 +846,7 @@ def test_compile_hourly_sum_statistics_nan_inf_state(
statistics_unit, statistics_unit,
unit_class, unit_class,
factor, factor,
): ) -> None:
"""Test compiling hourly statistics with nan and inf states.""" """Test compiling hourly statistics with nan and inf states."""
zero = dt_util.utcnow() zero = dt_util.utcnow()
hass = hass_recorder() hass = hass_recorder()
@ -955,8 +966,8 @@ def test_compile_hourly_sum_statistics_nan_inf_state(
) )
@pytest.mark.parametrize("state_class", ["total_increasing"]) @pytest.mark.parametrize("state_class", ["total_increasing"])
def test_compile_hourly_sum_statistics_negative_state( def test_compile_hourly_sum_statistics_negative_state(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
entity_id, entity_id,
warning_1, warning_1,
warning_2, warning_2,
@ -967,7 +978,7 @@ def test_compile_hourly_sum_statistics_negative_state(
statistics_unit, statistics_unit,
unit_class, unit_class,
offset, offset,
): ) -> None:
"""Test compiling hourly statistics with negative states.""" """Test compiling hourly statistics with negative states."""
zero = dt_util.utcnow() zero = dt_util.utcnow()
hass = hass_recorder() hass = hass_recorder()
@ -1067,15 +1078,15 @@ def test_compile_hourly_sum_statistics_negative_state(
], ],
) )
def test_compile_hourly_sum_statistics_total_no_reset( def test_compile_hourly_sum_statistics_total_no_reset(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
device_class, device_class,
state_unit, state_unit,
display_unit, display_unit,
statistics_unit, statistics_unit,
unit_class, unit_class,
factor, factor,
): ) -> None:
"""Test compiling hourly statistics.""" """Test compiling hourly statistics."""
period0 = dt_util.utcnow() period0 = dt_util.utcnow()
period0_end = period1 = period0 + timedelta(minutes=5) period0_end = period1 = period0 + timedelta(minutes=5)
@ -1176,15 +1187,15 @@ def test_compile_hourly_sum_statistics_total_no_reset(
], ],
) )
def test_compile_hourly_sum_statistics_total_increasing( def test_compile_hourly_sum_statistics_total_increasing(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
device_class, device_class,
state_unit, state_unit,
display_unit, display_unit,
statistics_unit, statistics_unit,
unit_class, unit_class,
factor, factor,
): ) -> None:
"""Test compiling hourly statistics.""" """Test compiling hourly statistics."""
period0 = dt_util.utcnow() period0 = dt_util.utcnow()
period0_end = period1 = period0 + timedelta(minutes=5) period0_end = period1 = period0 + timedelta(minutes=5)
@ -1283,15 +1294,15 @@ def test_compile_hourly_sum_statistics_total_increasing(
[("energy", "kWh", "kWh", "kWh", "energy", 1)], [("energy", "kWh", "kWh", "kWh", "energy", 1)],
) )
def test_compile_hourly_sum_statistics_total_increasing_small_dip( def test_compile_hourly_sum_statistics_total_increasing_small_dip(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
device_class, device_class,
state_unit, state_unit,
display_unit, display_unit,
statistics_unit, statistics_unit,
unit_class, unit_class,
factor, factor,
): ) -> None:
"""Test small dips in sensor readings do not trigger a reset.""" """Test small dips in sensor readings do not trigger a reset."""
period0 = dt_util.utcnow() period0 = dt_util.utcnow()
period0_end = period1 = period0 + timedelta(minutes=5) period0_end = period1 = period0 + timedelta(minutes=5)
@ -1388,7 +1399,9 @@ def test_compile_hourly_sum_statistics_total_increasing_small_dip(
assert "Error while processing event StatisticsTask" not in caplog.text assert "Error while processing event StatisticsTask" not in caplog.text
def test_compile_hourly_energy_statistics_unsupported(hass_recorder, caplog): def test_compile_hourly_energy_statistics_unsupported(
hass_recorder: Callable[..., HomeAssistant], caplog: pytest.LogCaptureFixture
) -> None:
"""Test compiling hourly statistics.""" """Test compiling hourly statistics."""
period0 = dt_util.utcnow() period0 = dt_util.utcnow()
period0_end = period1 = period0 + timedelta(minutes=5) period0_end = period1 = period0 + timedelta(minutes=5)
@ -1482,7 +1495,9 @@ def test_compile_hourly_energy_statistics_unsupported(hass_recorder, caplog):
assert "Error while processing event StatisticsTask" not in caplog.text assert "Error while processing event StatisticsTask" not in caplog.text
def test_compile_hourly_energy_statistics_multiple(hass_recorder, caplog): def test_compile_hourly_energy_statistics_multiple(
hass_recorder: Callable[..., HomeAssistant], caplog: pytest.LogCaptureFixture
) -> None:
"""Test compiling multiple hourly statistics.""" """Test compiling multiple hourly statistics."""
period0 = dt_util.utcnow() period0 = dt_util.utcnow()
period0_end = period1 = period0 + timedelta(minutes=5) period0_end = period1 = period0 + timedelta(minutes=5)
@ -1683,8 +1698,12 @@ def test_compile_hourly_energy_statistics_multiple(hass_recorder, caplog):
], ],
) )
def test_compile_hourly_statistics_unchanged( def test_compile_hourly_statistics_unchanged(
hass_recorder, caplog, device_class, state_unit, value hass_recorder: Callable[..., HomeAssistant],
): caplog: pytest.LogCaptureFixture,
device_class,
state_unit,
value,
) -> None:
"""Test compiling hourly statistics, with no changes during the hour.""" """Test compiling hourly statistics, with no changes during the hour."""
zero = dt_util.utcnow() zero = dt_util.utcnow()
hass = hass_recorder() hass = hass_recorder()
@ -1719,7 +1738,9 @@ def test_compile_hourly_statistics_unchanged(
assert "Error while processing event StatisticsTask" not in caplog.text assert "Error while processing event StatisticsTask" not in caplog.text
def test_compile_hourly_statistics_partially_unavailable(hass_recorder, caplog): def test_compile_hourly_statistics_partially_unavailable(
hass_recorder: Callable[..., HomeAssistant], caplog: pytest.LogCaptureFixture
) -> None:
"""Test compiling hourly statistics, with the sensor being partially unavailable.""" """Test compiling hourly statistics, with the sensor being partially unavailable."""
zero = dt_util.utcnow() zero = dt_util.utcnow()
hass = hass_recorder() hass = hass_recorder()
@ -1776,8 +1797,12 @@ def test_compile_hourly_statistics_partially_unavailable(hass_recorder, caplog):
], ],
) )
def test_compile_hourly_statistics_unavailable( def test_compile_hourly_statistics_unavailable(
hass_recorder, caplog, device_class, state_unit, value hass_recorder: Callable[..., HomeAssistant],
): caplog: pytest.LogCaptureFixture,
device_class,
state_unit,
value,
) -> None:
"""Test compiling hourly statistics, with one sensor being unavailable. """Test compiling hourly statistics, with one sensor being unavailable.
sensor.test1 is unavailable and should not have statistics generated sensor.test1 is unavailable and should not have statistics generated
@ -1820,7 +1845,9 @@ def test_compile_hourly_statistics_unavailable(
assert "Error while processing event StatisticsTask" not in caplog.text assert "Error while processing event StatisticsTask" not in caplog.text
def test_compile_hourly_statistics_fails(hass_recorder, caplog): def test_compile_hourly_statistics_fails(
hass_recorder: Callable[..., HomeAssistant], caplog: pytest.LogCaptureFixture
) -> None:
"""Test compiling hourly statistics throws.""" """Test compiling hourly statistics throws."""
zero = dt_util.utcnow() zero = dt_util.utcnow()
hass = hass_recorder() hass = hass_recorder()
@ -1886,8 +1913,8 @@ def test_compile_hourly_statistics_fails(hass_recorder, caplog):
], ],
) )
def test_list_statistic_ids( def test_list_statistic_ids(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
state_class, state_class,
device_class, device_class,
state_unit, state_unit,
@ -1895,7 +1922,7 @@ def test_list_statistic_ids(
statistics_unit, statistics_unit,
unit_class, unit_class,
statistic_type, statistic_type,
): ) -> None:
"""Test listing future statistic ids.""" """Test listing future statistic ids."""
hass = hass_recorder() hass = hass_recorder()
setup_component(hass, "sensor", {}) setup_component(hass, "sensor", {})
@ -1943,7 +1970,11 @@ def test_list_statistic_ids(
"_attributes", "_attributes",
[{**ENERGY_SENSOR_ATTRIBUTES, "last_reset": 0}, TEMPERATURE_SENSOR_ATTRIBUTES], [{**ENERGY_SENSOR_ATTRIBUTES, "last_reset": 0}, TEMPERATURE_SENSOR_ATTRIBUTES],
) )
def test_list_statistic_ids_unsupported(hass_recorder, caplog, _attributes): def test_list_statistic_ids_unsupported(
hass_recorder: Callable[..., HomeAssistant],
caplog: pytest.LogCaptureFixture,
_attributes,
) -> None:
"""Test listing future statistic ids for unsupported sensor.""" """Test listing future statistic ids for unsupported sensor."""
hass = hass_recorder() hass = hass_recorder()
setup_component(hass, "sensor", {}) setup_component(hass, "sensor", {})
@ -1980,8 +2011,8 @@ def test_list_statistic_ids_unsupported(hass_recorder, caplog, _attributes):
], ],
) )
def test_compile_hourly_statistics_changing_units_1( def test_compile_hourly_statistics_changing_units_1(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
device_class, device_class,
state_unit, state_unit,
state_unit2, state_unit2,
@ -1989,7 +2020,7 @@ def test_compile_hourly_statistics_changing_units_1(
mean, mean,
min, min,
max, max,
): ) -> None:
"""Test compiling hourly statistics where units change from one hour to the next. """Test compiling hourly statistics where units change from one hour to the next.
This tests the case where the recorder cannot convert between the units. This tests the case where the recorder cannot convert between the units.
@ -2101,8 +2132,8 @@ def test_compile_hourly_statistics_changing_units_1(
], ],
) )
def test_compile_hourly_statistics_changing_units_2( def test_compile_hourly_statistics_changing_units_2(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
device_class, device_class,
state_unit, state_unit,
display_unit, display_unit,
@ -2111,7 +2142,7 @@ def test_compile_hourly_statistics_changing_units_2(
mean, mean,
min, min,
max, max,
): ) -> None:
"""Test compiling hourly statistics where units change during an hour. """Test compiling hourly statistics where units change during an hour.
This tests the behaviour when the sensor units are note supported by any unit This tests the behaviour when the sensor units are note supported by any unit
@ -2174,8 +2205,8 @@ def test_compile_hourly_statistics_changing_units_2(
], ],
) )
def test_compile_hourly_statistics_changing_units_3( def test_compile_hourly_statistics_changing_units_3(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
device_class, device_class,
state_unit, state_unit,
display_unit, display_unit,
@ -2184,7 +2215,7 @@ def test_compile_hourly_statistics_changing_units_3(
mean, mean,
min, min,
max, max,
): ) -> None:
"""Test compiling hourly statistics where units change from one hour to the next. """Test compiling hourly statistics where units change from one hour to the next.
This tests the behaviour when the sensor units are note supported by any unit This tests the behaviour when the sensor units are note supported by any unit
@ -2291,8 +2322,8 @@ def test_compile_hourly_statistics_changing_units_3(
], ],
) )
def test_compile_hourly_statistics_convert_units_1( def test_compile_hourly_statistics_convert_units_1(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
state_unit_1, state_unit_1,
state_unit_2, state_unit_2,
unit_class, unit_class,
@ -2300,7 +2331,7 @@ def test_compile_hourly_statistics_convert_units_1(
min, min,
max, max,
factor, factor,
): ) -> None:
"""Test compiling hourly statistics where units change from one hour to the next. """Test compiling hourly statistics where units change from one hour to the next.
This tests the case where the recorder can convert between the units. This tests the case where the recorder can convert between the units.
@ -2427,8 +2458,8 @@ def test_compile_hourly_statistics_convert_units_1(
], ],
) )
def test_compile_hourly_statistics_equivalent_units_1( def test_compile_hourly_statistics_equivalent_units_1(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
device_class, device_class,
state_unit, state_unit,
state_unit2, state_unit2,
@ -2438,7 +2469,7 @@ def test_compile_hourly_statistics_equivalent_units_1(
mean2, mean2,
min, min,
max, max,
): ) -> None:
"""Test compiling hourly statistics where units change from one hour to the next.""" """Test compiling hourly statistics where units change from one hour to the next."""
zero = dt_util.utcnow() zero = dt_util.utcnow()
hass = hass_recorder() hass = hass_recorder()
@ -2547,8 +2578,8 @@ def test_compile_hourly_statistics_equivalent_units_1(
], ],
) )
def test_compile_hourly_statistics_equivalent_units_2( def test_compile_hourly_statistics_equivalent_units_2(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
device_class, device_class,
state_unit, state_unit,
state_unit2, state_unit2,
@ -2556,7 +2587,7 @@ def test_compile_hourly_statistics_equivalent_units_2(
mean, mean,
min, min,
max, max,
): ) -> None:
"""Test compiling hourly statistics where units change during an hour.""" """Test compiling hourly statistics where units change during an hour."""
zero = dt_util.utcnow() zero = dt_util.utcnow()
hass = hass_recorder() hass = hass_recorder()
@ -2630,8 +2661,8 @@ def test_compile_hourly_statistics_equivalent_units_2(
], ],
) )
def test_compile_hourly_statistics_changing_device_class_1( def test_compile_hourly_statistics_changing_device_class_1(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
device_class, device_class,
state_unit, state_unit,
statistic_unit, statistic_unit,
@ -2640,7 +2671,7 @@ def test_compile_hourly_statistics_changing_device_class_1(
mean2, mean2,
min, min,
max, max,
): ) -> None:
"""Test compiling hourly statistics where device class changes from one hour to the next. """Test compiling hourly statistics where device class changes from one hour to the next.
Device class is ignored, meaning changing device class should not influence the statistics. Device class is ignored, meaning changing device class should not influence the statistics.
@ -2828,8 +2859,8 @@ def test_compile_hourly_statistics_changing_device_class_1(
], ],
) )
def test_compile_hourly_statistics_changing_device_class_2( def test_compile_hourly_statistics_changing_device_class_2(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
device_class, device_class,
state_unit, state_unit,
display_unit, display_unit,
@ -2839,7 +2870,7 @@ def test_compile_hourly_statistics_changing_device_class_2(
mean2, mean2,
min, min,
max, max,
): ) -> None:
"""Test compiling hourly statistics where device class changes from one hour to the next. """Test compiling hourly statistics where device class changes from one hour to the next.
Device class is ignored, meaning changing device class should not influence the statistics. Device class is ignored, meaning changing device class should not influence the statistics.
@ -2962,8 +2993,8 @@ def test_compile_hourly_statistics_changing_device_class_2(
], ],
) )
def test_compile_hourly_statistics_changing_state_class( def test_compile_hourly_statistics_changing_state_class(
hass_recorder, hass_recorder: Callable[..., HomeAssistant],
caplog, caplog: pytest.LogCaptureFixture,
device_class, device_class,
state_unit, state_unit,
display_unit, display_unit,
@ -2972,7 +3003,7 @@ def test_compile_hourly_statistics_changing_state_class(
mean, mean,
min, min,
max, max,
): ) -> None:
"""Test compiling hourly statistics where state class changes.""" """Test compiling hourly statistics where state class changes."""
period0 = dt_util.utcnow() period0 = dt_util.utcnow()
period0_end = period1 = period0 + timedelta(minutes=5) period0_end = period1 = period0 + timedelta(minutes=5)
@ -3085,7 +3116,9 @@ def test_compile_hourly_statistics_changing_state_class(
assert "Error while processing event StatisticsTask" not in caplog.text assert "Error while processing event StatisticsTask" not in caplog.text
def test_compile_statistics_hourly_daily_monthly_summary(hass_recorder, caplog): def test_compile_statistics_hourly_daily_monthly_summary(
hass_recorder: Callable[..., HomeAssistant], caplog: pytest.LogCaptureFixture
) -> None:
"""Test compiling hourly statistics + monthly and daily summary.""" """Test compiling hourly statistics + monthly and daily summary."""
zero = dt_util.utcnow() zero = dt_util.utcnow()
# August 31st, 23:00 local time # August 31st, 23:00 local time
@ -3573,8 +3606,15 @@ def record_states(hass, zero, entity_id, attributes, seq=None):
], ],
) )
async def test_validate_unit_change_convertible( async def test_validate_unit_change_convertible(
recorder_mock, hass, hass_ws_client, units, attributes, unit, unit2, supported_unit recorder_mock: Recorder,
): hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
units,
attributes,
unit,
unit2,
supported_unit,
) -> None:
"""Test validate_statistics. """Test validate_statistics.
This tests what happens if a sensor is first recorded in a unit which supports unit This tests what happens if a sensor is first recorded in a unit which supports unit
@ -3688,8 +3728,12 @@ async def test_validate_unit_change_convertible(
], ],
) )
async def test_validate_statistics_unit_ignore_device_class( async def test_validate_statistics_unit_ignore_device_class(
recorder_mock, hass, hass_ws_client, units, attributes recorder_mock: Recorder,
): hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
units,
attributes,
) -> None:
"""Test validate_statistics. """Test validate_statistics.
The test asserts that the sensor's device class is ignored. The test asserts that the sensor's device class is ignored.
@ -3772,8 +3816,15 @@ async def test_validate_statistics_unit_ignore_device_class(
], ],
) )
async def test_validate_statistics_unit_change_no_device_class( async def test_validate_statistics_unit_change_no_device_class(
recorder_mock, hass, hass_ws_client, units, attributes, unit, unit2, supported_unit recorder_mock: Recorder,
): hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
units,
attributes,
unit,
unit2,
supported_unit,
) -> None:
"""Test validate_statistics. """Test validate_statistics.
This tests what happens if a sensor is first recorded in a unit which supports unit This tests what happens if a sensor is first recorded in a unit which supports unit
@ -3887,8 +3938,13 @@ async def test_validate_statistics_unit_change_no_device_class(
], ],
) )
async def test_validate_statistics_unsupported_state_class( async def test_validate_statistics_unsupported_state_class(
recorder_mock, hass, hass_ws_client, units, attributes, unit recorder_mock: Recorder,
): hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
units,
attributes,
unit,
) -> None:
"""Test validate_statistics.""" """Test validate_statistics."""
id = 1 id = 1
@ -3951,8 +4007,13 @@ async def test_validate_statistics_unsupported_state_class(
], ],
) )
async def test_validate_statistics_sensor_no_longer_recorded( async def test_validate_statistics_sensor_no_longer_recorded(
recorder_mock, hass, hass_ws_client, units, attributes, unit recorder_mock: Recorder,
): hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
units,
attributes,
unit,
) -> None:
"""Test validate_statistics.""" """Test validate_statistics."""
id = 1 id = 1
@ -4014,8 +4075,13 @@ async def test_validate_statistics_sensor_no_longer_recorded(
], ],
) )
async def test_validate_statistics_sensor_not_recorded( async def test_validate_statistics_sensor_not_recorded(
recorder_mock, hass, hass_ws_client, units, attributes, unit recorder_mock: Recorder,
): hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
units,
attributes,
unit,
) -> None:
"""Test validate_statistics.""" """Test validate_statistics."""
id = 1 id = 1
@ -4074,8 +4140,13 @@ async def test_validate_statistics_sensor_not_recorded(
], ],
) )
async def test_validate_statistics_sensor_removed( async def test_validate_statistics_sensor_removed(
recorder_mock, hass, hass_ws_client, units, attributes, unit recorder_mock: Recorder,
): hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
units,
attributes,
unit,
) -> None:
"""Test validate_statistics.""" """Test validate_statistics."""
id = 1 id = 1
@ -4133,8 +4204,13 @@ async def test_validate_statistics_sensor_removed(
], ],
) )
async def test_validate_statistics_unit_change_no_conversion( async def test_validate_statistics_unit_change_no_conversion(
recorder_mock, hass, hass_ws_client, attributes, unit1, unit2 recorder_mock: Recorder,
): hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
attributes,
unit1,
unit2,
) -> None:
"""Test validate_statistics.""" """Test validate_statistics."""
id = 1 id = 1
@ -4259,8 +4335,13 @@ async def test_validate_statistics_unit_change_no_conversion(
], ],
) )
async def test_validate_statistics_unit_change_equivalent_units( async def test_validate_statistics_unit_change_equivalent_units(
recorder_mock, hass, hass_ws_client, attributes, unit1, unit2 recorder_mock: Recorder,
): hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
attributes,
unit1,
unit2,
) -> None:
"""Test validate_statistics. """Test validate_statistics.
This tests no validation issue is created when a sensor's unit changes to an This tests no validation issue is created when a sensor's unit changes to an
@ -4338,8 +4419,14 @@ async def test_validate_statistics_unit_change_equivalent_units(
], ],
) )
async def test_validate_statistics_unit_change_equivalent_units_2( async def test_validate_statistics_unit_change_equivalent_units_2(
recorder_mock, hass, hass_ws_client, attributes, unit1, unit2, supported_unit recorder_mock: Recorder,
): hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
attributes,
unit1,
unit2,
supported_unit,
) -> None:
"""Test validate_statistics. """Test validate_statistics.
This tests a validation issue is created when a sensor's unit changes to an This tests a validation issue is created when a sensor's unit changes to an
@ -4424,7 +4511,9 @@ async def test_validate_statistics_unit_change_equivalent_units_2(
await assert_validation_result(client, expected) await assert_validation_result(client, expected)
async def test_validate_statistics_other_domain(recorder_mock, hass, hass_ws_client): async def test_validate_statistics_other_domain(
recorder_mock: Recorder, hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test sensor does not raise issues for statistics for other domains.""" """Test sensor does not raise issues for statistics for other domains."""
id = 1 id = 1
@ -4606,7 +4695,7 @@ def record_states_partially_unavailable(hass, zero, entity_id, attributes):
return four, states return four, states
async def test_exclude_attributes(recorder_mock: None, hass: HomeAssistant) -> None: async def test_exclude_attributes(recorder_mock: Recorder, hass: HomeAssistant) -> None:
"""Test sensor attributes to be excluded.""" """Test sensor attributes to be excluded."""
await async_setup_component(hass, DOMAIN, {DOMAIN: {"platform": "demo"}}) await async_setup_component(hass, DOMAIN, {DOMAIN: {"platform": "demo"}})
await hass.async_block_till_done() await hass.async_block_till_done()

View File

@ -55,7 +55,9 @@ TEMP_FREEDOM_ATTRS = {
("70", "fail", TEMP_FREEDOM_ATTRS, False), ("70", "fail", TEMP_FREEDOM_ATTRS, False),
], ],
) )
async def test_significant_change_temperature(old_state, new_state, attrs, result): async def test_significant_change_temperature(
old_state, new_state, attrs, result
) -> None:
"""Detect temperature significant changes.""" """Detect temperature significant changes."""
assert ( assert (
significant_change.async_check_significant_change( significant_change.async_check_significant_change(

View File

@ -5,8 +5,12 @@ from homeassistant.components.sensor.const import DOMAIN
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.typing import WebSocketGenerator
async def test_device_class_units(hass: HomeAssistant, hass_ws_client) -> None:
async def test_device_class_units(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test we can get supported units.""" """Test we can get supported units."""
assert await async_setup_component(hass, DOMAIN, {}) assert await async_setup_component(hass, DOMAIN, {})

View File

@ -156,7 +156,7 @@ async def test_process_before_send(hass: HomeAssistant) -> None:
assert user["id"] == "12345" assert user["id"] == "12345"
async def test_event_with_platform_context(hass: HomeAssistant): async def test_event_with_platform_context(hass: HomeAssistant) -> None:
"""Test extraction of platform context information during Sentry events.""" """Test extraction of platform context information during Sentry events."""
current_platform_mock = Mock() current_platform_mock = Mock()
@ -235,7 +235,7 @@ async def test_event_with_platform_context(hass: HomeAssistant):
("tuyapi.test", {"package": "tuyapi"}), ("tuyapi.test", {"package": "tuyapi"}),
], ],
) )
async def test_logger_event_extraction(hass: HomeAssistant, logger, tags): async def test_logger_event_extraction(hass: HomeAssistant, logger, tags) -> None:
"""Test extraction of information from Sentry logger events.""" """Test extraction of information from Sentry logger events."""
result = process_before_send( result = process_before_send(
@ -278,7 +278,7 @@ async def test_logger_event_extraction(hass: HomeAssistant, logger, tags):
), ),
], ],
) )
async def test_filter_log_events(hass: HomeAssistant, logger, options, event): async def test_filter_log_events(hass: HomeAssistant, logger, options, event) -> None:
"""Test filtering of events based on configuration options.""" """Test filtering of events based on configuration options."""
result = process_before_send( result = process_before_send(
hass, hass,
@ -306,7 +306,9 @@ async def test_filter_log_events(hass: HomeAssistant, logger, options, event):
("no", {CONF_EVENT_HANDLED: True}, True), ("no", {CONF_EVENT_HANDLED: True}, True),
], ],
) )
async def test_filter_handled_events(hass: HomeAssistant, handled, options, event): async def test_filter_handled_events(
hass: HomeAssistant, handled, options, event
) -> None:
"""Tests filtering of handled events based on configuration options.""" """Tests filtering of handled events based on configuration options."""
result = process_before_send( result = process_before_send(
hass, hass,

View File

@ -13,15 +13,18 @@ from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_entry_oauth2_flow from homeassistant.helpers import config_entry_oauth2_flow
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import ClientSessionGenerator
CLIENT_ID = "1234" CLIENT_ID = "1234"
CLIENT_SECRET = "5678" CLIENT_SECRET = "5678"
async def test_full_flow( async def test_full_flow(
hass: HomeAssistant, hass: HomeAssistant,
hass_client_no_auth, hass_client_no_auth: ClientSessionGenerator,
aioclient_mock, aioclient_mock: AiohttpClientMocker,
current_request_with_host, current_request_with_host: None,
) -> None: ) -> None:
"""Check full flow.""" """Check full flow."""
await async_setup_component(hass, DOMAIN, {}) await async_setup_component(hass, DOMAIN, {})

View File

@ -25,7 +25,9 @@ def override_async_setup_entry() -> Generator[AsyncMock, None, None]:
yield mock_setup_entry yield mock_setup_entry
async def test_config_flow_skip_auth(hass: HomeAssistant, mock_setup_entry: AsyncMock): async def test_config_flow_skip_auth(
hass: HomeAssistant, mock_setup_entry: AsyncMock
) -> None:
"""Test we get the form.""" """Test we get the form."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -75,7 +77,9 @@ async def test_config_flow_skip_auth(hass: HomeAssistant, mock_setup_entry: Asyn
assert len(mock_setup_entry.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
async def test_config_flow_with_auth(hass: HomeAssistant, mock_setup_entry: AsyncMock): async def test_config_flow_with_auth(
hass: HomeAssistant, mock_setup_entry: AsyncMock
) -> None:
"""Test we get the form.""" """Test we get the form."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -142,7 +146,7 @@ async def test_config_flow_with_auth(hass: HomeAssistant, mock_setup_entry: Asyn
@pytest.mark.usefixtures("config_entry") @pytest.mark.usefixtures("config_entry")
async def test_config_flow_duplicate_host( async def test_config_flow_duplicate_host(
hass: HomeAssistant, mock_setup_entry: AsyncMock hass: HomeAssistant, mock_setup_entry: AsyncMock
): ) -> None:
"""Test abort if unique_id configured.""" """Test abort if unique_id configured."""
assert len(hass.config_entries.async_entries(DOMAIN)) == 1 assert len(hass.config_entries.async_entries(DOMAIN)) == 1
@ -176,7 +180,7 @@ async def test_config_flow_duplicate_host(
@pytest.mark.usefixtures("config_entry") @pytest.mark.usefixtures("config_entry")
async def test_config_flow_duplicate_mac( async def test_config_flow_duplicate_mac(
hass: HomeAssistant, mock_setup_entry: AsyncMock hass: HomeAssistant, mock_setup_entry: AsyncMock
): ) -> None:
"""Test abort if unique_id configured.""" """Test abort if unique_id configured."""
assert len(hass.config_entries.async_entries(DOMAIN)) == 1 assert len(hass.config_entries.async_entries(DOMAIN)) == 1

View File

@ -9,6 +9,7 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from tests.components.diagnostics import get_diagnostics_for_config_entry from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
pytestmark = pytest.mark.usefixtures("system_get_info", "dsl_get_info") pytestmark = pytest.mark.usefixtures("system_get_info", "dsl_get_info")
@ -21,7 +22,7 @@ def override_platforms() -> Generator[None, None, None]:
async def test_entry_diagnostics( async def test_entry_diagnostics(
hass: HomeAssistant, config_entry: ConfigEntry, hass_client hass: HomeAssistant, config_entry: ConfigEntry, hass_client: ClientSessionGenerator
) -> None: ) -> None:
"""Test config entry diagnostics.""" """Test config entry diagnostics."""
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)

View File

@ -50,7 +50,7 @@ async def test_form(hass: HomeAssistant) -> None:
(TypeError, "unknown"), (TypeError, "unknown"),
], ],
) )
async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str) -> None:
"""Test form errors.""" """Test form errors."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -66,7 +66,7 @@ async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str):
assert result2["errors"].get("base") == base_error assert result2["errors"].get("base") == base_error
async def test_reauth_success(hass: HomeAssistant): async def test_reauth_success(hass: HomeAssistant) -> None:
"""Test reauth flow.""" """Test reauth flow."""
with patch("sharkiq.AylaApi.async_sign_in", return_value=True): with patch("sharkiq.AylaApi.async_sign_in", return_value=True):
mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG)
@ -96,7 +96,7 @@ async def test_reauth(
result_type: str, result_type: str,
msg_field: str, msg_field: str,
msg: str, msg: str,
): ) -> None:
"""Test reauth failures.""" """Test reauth failures."""
with patch("sharkiq.AylaApi.async_sign_in", side_effect=side_effect): with patch("sharkiq.AylaApi.async_sign_in", side_effect=side_effect):
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(

View File

@ -121,7 +121,7 @@ async def setup_integration(hass):
await hass.async_block_till_done() await hass.async_block_till_done()
async def test_simple_properties(hass: HomeAssistant): async def test_simple_properties(hass: HomeAssistant) -> None:
"""Test that simple properties work as intended.""" """Test that simple properties work as intended."""
state = hass.states.get(VAC_ENTITY_ID) state = hass.states.get(VAC_ENTITY_ID)
registry = er.async_get(hass) registry = er.async_get(hass)
@ -148,7 +148,7 @@ async def test_simple_properties(hass: HomeAssistant):
) )
async def test_initial_attributes( async def test_initial_attributes(
hass: HomeAssistant, attribute: str, target_value: Any hass: HomeAssistant, attribute: str, target_value: Any
): ) -> None:
"""Test initial config attributes.""" """Test initial config attributes."""
state = hass.states.get(VAC_ENTITY_ID) state = hass.states.get(VAC_ENTITY_ID)
assert state.attributes.get(attribute) == target_value assert state.attributes.get(attribute) == target_value
@ -163,7 +163,9 @@ async def test_initial_attributes(
(SERVICE_START, STATE_CLEANING), (SERVICE_START, STATE_CLEANING),
], ],
) )
async def test_cleaning_states(hass: HomeAssistant, service: str, target_state: str): async def test_cleaning_states(
hass: HomeAssistant, service: str, target_state: str
) -> None:
"""Test cleaning states.""" """Test cleaning states."""
service_data = {ATTR_ENTITY_ID: VAC_ENTITY_ID} service_data = {ATTR_ENTITY_ID: VAC_ENTITY_ID}
await hass.services.async_call("vacuum", service, service_data, blocking=True) await hass.services.async_call("vacuum", service, service_data, blocking=True)
@ -193,7 +195,7 @@ async def test_fan_speed(hass: HomeAssistant, fan_speed: str) -> None:
) )
async def test_device_properties( async def test_device_properties(
hass: HomeAssistant, device_property: str, target_value: str hass: HomeAssistant, device_property: str, target_value: str
): ) -> None:
"""Test device properties.""" """Test device properties."""
registry = dr.async_get(hass) registry = dr.async_get(hass)
device = registry.async_get_device({(DOMAIN, "AC000Wxxxxxxxxx")}) device = registry.async_get_device({(DOMAIN, "AC000Wxxxxxxxxx")})

View File

@ -63,7 +63,7 @@ async def test_config_not_valid_service_names(hass: HomeAssistant) -> None:
@patch("homeassistant.components.shell_command.asyncio.create_subprocess_shell") @patch("homeassistant.components.shell_command.asyncio.create_subprocess_shell")
async def test_template_render_no_template(mock_call, hass): async def test_template_render_no_template(mock_call, hass: HomeAssistant) -> None:
"""Ensure shell_commands without templates get rendered properly.""" """Ensure shell_commands without templates get rendered properly."""
mock_call.return_value = mock_process_creator(error=False) mock_call.return_value = mock_process_creator(error=False)
@ -83,7 +83,7 @@ async def test_template_render_no_template(mock_call, hass):
@patch("homeassistant.components.shell_command.asyncio.create_subprocess_exec") @patch("homeassistant.components.shell_command.asyncio.create_subprocess_exec")
async def test_template_render(mock_call, hass): async def test_template_render(mock_call, hass: HomeAssistant) -> None:
"""Ensure shell_commands with templates get rendered properly.""" """Ensure shell_commands with templates get rendered properly."""
hass.states.async_set("sensor.test_state", "Works") hass.states.async_set("sensor.test_state", "Works")
mock_call.return_value = mock_process_creator(error=False) mock_call.return_value = mock_process_creator(error=False)
@ -108,7 +108,7 @@ async def test_template_render(mock_call, hass):
@patch("homeassistant.components.shell_command.asyncio.create_subprocess_shell") @patch("homeassistant.components.shell_command.asyncio.create_subprocess_shell")
@patch("homeassistant.components.shell_command._LOGGER.error") @patch("homeassistant.components.shell_command._LOGGER.error")
async def test_subprocess_error(mock_error, mock_call, hass): async def test_subprocess_error(mock_error, mock_call, hass: HomeAssistant) -> None:
"""Test subprocess that returns an error.""" """Test subprocess that returns an error."""
mock_call.return_value = mock_process_creator(error=True) mock_call.return_value = mock_process_creator(error=True)
with tempfile.TemporaryDirectory() as tempdirname: with tempfile.TemporaryDirectory() as tempdirname:
@ -127,7 +127,7 @@ async def test_subprocess_error(mock_error, mock_call, hass):
@patch("homeassistant.components.shell_command._LOGGER.debug") @patch("homeassistant.components.shell_command._LOGGER.debug")
async def test_stdout_captured(mock_output, hass): async def test_stdout_captured(mock_output, hass: HomeAssistant) -> None:
"""Test subprocess that has stdout.""" """Test subprocess that has stdout."""
test_phrase = "I have output" test_phrase = "I have output"
assert await async_setup_component( assert await async_setup_component(
@ -144,7 +144,7 @@ async def test_stdout_captured(mock_output, hass):
@patch("homeassistant.components.shell_command._LOGGER.debug") @patch("homeassistant.components.shell_command._LOGGER.debug")
async def test_stderr_captured(mock_output, hass): async def test_stderr_captured(mock_output, hass: HomeAssistant) -> None:
"""Test subprocess that has stderr.""" """Test subprocess that has stderr."""
test_phrase = "I have error" test_phrase = "I have error"
assert await async_setup_component( assert await async_setup_component(

View File

@ -1,10 +1,8 @@
"""Tests for Shelly binary sensor platform.""" """Tests for Shelly binary sensor platform."""
from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN
from homeassistant.components.shelly.const import SLEEP_PERIOD_MULTIPLIER from homeassistant.components.shelly.const import SLEEP_PERIOD_MULTIPLIER
from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNKNOWN from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNKNOWN
from homeassistant.core import State from homeassistant.core import HomeAssistant, State
from homeassistant.helpers.entity_registry import async_get from homeassistant.helpers.entity_registry import async_get
from . import ( from . import (
@ -21,7 +19,9 @@ RELAY_BLOCK_ID = 0
SENSOR_BLOCK_ID = 3 SENSOR_BLOCK_ID = 3
async def test_block_binary_sensor(hass, mock_block_device, monkeypatch): async def test_block_binary_sensor(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block binary sensor.""" """Test block binary sensor."""
entity_id = f"{BINARY_SENSOR_DOMAIN}.test_name_channel_1_overpowering" entity_id = f"{BINARY_SENSOR_DOMAIN}.test_name_channel_1_overpowering"
await init_integration(hass, 1) await init_integration(hass, 1)
@ -35,8 +35,8 @@ async def test_block_binary_sensor(hass, mock_block_device, monkeypatch):
async def test_block_binary_sensor_extra_state_attr( async def test_block_binary_sensor_extra_state_attr(
hass, mock_block_device, monkeypatch hass: HomeAssistant, mock_block_device, monkeypatch
): ) -> None:
"""Test block binary sensor extra state attributes.""" """Test block binary sensor extra state attributes."""
entity_id = f"{BINARY_SENSOR_DOMAIN}.test_name_gas" entity_id = f"{BINARY_SENSOR_DOMAIN}.test_name_gas"
await init_integration(hass, 1) await init_integration(hass, 1)
@ -53,7 +53,9 @@ async def test_block_binary_sensor_extra_state_attr(
assert state.attributes.get("detected") == "none" assert state.attributes.get("detected") == "none"
async def test_block_rest_binary_sensor(hass, mock_block_device, monkeypatch): async def test_block_rest_binary_sensor(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block REST binary sensor.""" """Test block REST binary sensor."""
entity_id = register_entity(hass, BINARY_SENSOR_DOMAIN, "test_name_cloud", "cloud") entity_id = register_entity(hass, BINARY_SENSOR_DOMAIN, "test_name_cloud", "cloud")
monkeypatch.setitem(mock_block_device.status, "cloud", {"connected": False}) monkeypatch.setitem(mock_block_device.status, "cloud", {"connected": False})
@ -68,8 +70,8 @@ async def test_block_rest_binary_sensor(hass, mock_block_device, monkeypatch):
async def test_block_rest_binary_sensor_connected_battery_devices( async def test_block_rest_binary_sensor_connected_battery_devices(
hass, mock_block_device, monkeypatch hass: HomeAssistant, mock_block_device, monkeypatch
): ) -> None:
"""Test block REST binary sensor for connected battery devices.""" """Test block REST binary sensor for connected battery devices."""
entity_id = register_entity(hass, BINARY_SENSOR_DOMAIN, "test_name_cloud", "cloud") entity_id = register_entity(hass, BINARY_SENSOR_DOMAIN, "test_name_cloud", "cloud")
monkeypatch.setitem(mock_block_device.status, "cloud", {"connected": False}) monkeypatch.setitem(mock_block_device.status, "cloud", {"connected": False})
@ -90,7 +92,9 @@ async def test_block_rest_binary_sensor_connected_battery_devices(
assert hass.states.get(entity_id).state == STATE_ON assert hass.states.get(entity_id).state == STATE_ON
async def test_block_sleeping_binary_sensor(hass, mock_block_device, monkeypatch): async def test_block_sleeping_binary_sensor(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block sleeping binary sensor.""" """Test block sleeping binary sensor."""
entity_id = f"{BINARY_SENSOR_DOMAIN}.test_name_motion" entity_id = f"{BINARY_SENSOR_DOMAIN}.test_name_motion"
await init_integration(hass, 1, sleep_period=1000) await init_integration(hass, 1, sleep_period=1000)
@ -111,8 +115,8 @@ async def test_block_sleeping_binary_sensor(hass, mock_block_device, monkeypatch
async def test_block_restored_sleeping_binary_sensor( async def test_block_restored_sleeping_binary_sensor(
hass, mock_block_device, device_reg, monkeypatch hass: HomeAssistant, mock_block_device, device_reg, monkeypatch
): ) -> None:
"""Test block restored sleeping binary sensor.""" """Test block restored sleeping binary sensor."""
entry = await init_integration(hass, 1, sleep_period=1000, skip_setup=True) entry = await init_integration(hass, 1, sleep_period=1000, skip_setup=True)
register_device(device_reg, entry) register_device(device_reg, entry)
@ -135,8 +139,8 @@ async def test_block_restored_sleeping_binary_sensor(
async def test_block_restored_sleeping_binary_sensor_no_last_state( async def test_block_restored_sleeping_binary_sensor_no_last_state(
hass, mock_block_device, device_reg, monkeypatch hass: HomeAssistant, mock_block_device, device_reg, monkeypatch
): ) -> None:
"""Test block restored sleeping binary sensor missing last state.""" """Test block restored sleeping binary sensor missing last state."""
entry = await init_integration(hass, 1, sleep_period=1000, skip_setup=True) entry = await init_integration(hass, 1, sleep_period=1000, skip_setup=True)
register_device(device_reg, entry) register_device(device_reg, entry)
@ -157,7 +161,9 @@ async def test_block_restored_sleeping_binary_sensor_no_last_state(
assert hass.states.get(entity_id).state == STATE_OFF assert hass.states.get(entity_id).state == STATE_OFF
async def test_rpc_binary_sensor(hass, mock_rpc_device, monkeypatch) -> None: async def test_rpc_binary_sensor(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC binary sensor.""" """Test RPC binary sensor."""
entity_id = f"{BINARY_SENSOR_DOMAIN}.test_cover_0_overpowering" entity_id = f"{BINARY_SENSOR_DOMAIN}.test_cover_0_overpowering"
await init_integration(hass, 2) await init_integration(hass, 2)
@ -172,7 +178,9 @@ async def test_rpc_binary_sensor(hass, mock_rpc_device, monkeypatch) -> None:
assert hass.states.get(entity_id).state == STATE_ON assert hass.states.get(entity_id).state == STATE_ON
async def test_rpc_binary_sensor_removal(hass, mock_rpc_device, monkeypatch): async def test_rpc_binary_sensor_removal(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC binary sensor is removed due to removal_condition.""" """Test RPC binary sensor is removed due to removal_condition."""
entity_registry = async_get(hass) entity_registry = async_get(hass)
entity_id = register_entity( entity_id = register_entity(
@ -188,7 +196,7 @@ async def test_rpc_binary_sensor_removal(hass, mock_rpc_device, monkeypatch):
async def test_rpc_sleeping_binary_sensor( async def test_rpc_sleeping_binary_sensor(
hass, mock_rpc_device, device_reg, monkeypatch hass: HomeAssistant, mock_rpc_device, device_reg, monkeypatch
) -> None: ) -> None:
"""Test RPC online sleeping binary sensor.""" """Test RPC online sleeping binary sensor."""
entity_id = f"{BINARY_SENSOR_DOMAIN}.test_name_cloud" entity_id = f"{BINARY_SENSOR_DOMAIN}.test_name_cloud"
@ -212,8 +220,8 @@ async def test_rpc_sleeping_binary_sensor(
async def test_rpc_restored_sleeping_binary_sensor( async def test_rpc_restored_sleeping_binary_sensor(
hass, mock_rpc_device, device_reg, monkeypatch hass: HomeAssistant, mock_rpc_device, device_reg, monkeypatch
): ) -> None:
"""Test RPC restored binary sensor.""" """Test RPC restored binary sensor."""
entry = await init_integration(hass, 2, sleep_period=1000, skip_setup=True) entry = await init_integration(hass, 2, sleep_period=1000, skip_setup=True)
register_device(device_reg, entry) register_device(device_reg, entry)
@ -238,8 +246,8 @@ async def test_rpc_restored_sleeping_binary_sensor(
async def test_rpc_restored_sleeping_binary_sensor_no_last_state( async def test_rpc_restored_sleeping_binary_sensor_no_last_state(
hass, mock_rpc_device, device_reg, monkeypatch hass: HomeAssistant, mock_rpc_device, device_reg, monkeypatch
): ) -> None:
"""Test RPC restored sleeping binary sensor missing last state.""" """Test RPC restored sleeping binary sensor missing last state."""
entry = await init_integration(hass, 2, sleep_period=1000, skip_setup=True) entry = await init_integration(hass, 2, sleep_period=1000, skip_setup=True)
register_device(device_reg, entry) register_device(device_reg, entry)

View File

@ -8,7 +8,7 @@ from homeassistant.core import HomeAssistant
from . import init_integration from . import init_integration
async def test_block_button(hass: HomeAssistant, mock_block_device): async def test_block_button(hass: HomeAssistant, mock_block_device) -> None:
"""Test block device reboot button.""" """Test block device reboot button."""
await init_integration(hass, 1) await init_integration(hass, 1)
@ -24,7 +24,7 @@ async def test_block_button(hass: HomeAssistant, mock_block_device):
assert mock_block_device.trigger_reboot.call_count == 1 assert mock_block_device.trigger_reboot.call_count == 1
async def test_rpc_button(hass: HomeAssistant, mock_rpc_device): async def test_rpc_button(hass: HomeAssistant, mock_rpc_device) -> None:
"""Test rpc device OTA button.""" """Test rpc device OTA button."""
await init_integration(hass, 2) await init_integration(hass, 2)

View File

@ -19,7 +19,7 @@ from homeassistant.components.climate import (
from homeassistant.components.shelly.const import DOMAIN from homeassistant.components.shelly.const import DOMAIN
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
from homeassistant.const import ATTR_ENTITY_ID, ATTR_TEMPERATURE, STATE_UNAVAILABLE from homeassistant.const import ATTR_ENTITY_ID, ATTR_TEMPERATURE, STATE_UNAVAILABLE
from homeassistant.core import State from homeassistant.core import HomeAssistant, State
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM
@ -32,7 +32,9 @@ DEVICE_BLOCK_ID = 4
ENTITY_ID = f"{CLIMATE_DOMAIN}.test_name" ENTITY_ID = f"{CLIMATE_DOMAIN}.test_name"
async def test_climate_hvac_mode(hass, mock_block_device, monkeypatch): async def test_climate_hvac_mode(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test climate hvac mode service.""" """Test climate hvac mode service."""
monkeypatch.delattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "targetTemp") monkeypatch.delattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "targetTemp")
monkeypatch.setattr( monkeypatch.setattr(
@ -91,7 +93,9 @@ async def test_climate_hvac_mode(hass, mock_block_device, monkeypatch):
assert state.state == STATE_UNAVAILABLE assert state.state == STATE_UNAVAILABLE
async def test_climate_set_temperature(hass, mock_block_device, monkeypatch): async def test_climate_set_temperature(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test climate set temperature service.""" """Test climate set temperature service."""
monkeypatch.delattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "targetTemp") monkeypatch.delattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "targetTemp")
monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "valveError", 0) monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "valveError", 0)
@ -131,7 +135,9 @@ async def test_climate_set_temperature(hass, mock_block_device, monkeypatch):
) )
async def test_climate_set_preset_mode(hass, mock_block_device, monkeypatch): async def test_climate_set_preset_mode(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test climate set preset mode service.""" """Test climate set preset mode service."""
monkeypatch.delattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "targetTemp") monkeypatch.delattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "targetTemp")
monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "valveError", 0) monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "valveError", 0)
@ -183,7 +189,9 @@ async def test_climate_set_preset_mode(hass, mock_block_device, monkeypatch):
assert state.attributes[ATTR_PRESET_MODE] == PRESET_NONE assert state.attributes[ATTR_PRESET_MODE] == PRESET_NONE
async def test_block_restored_climate(hass, mock_block_device, device_reg, monkeypatch): async def test_block_restored_climate(
hass: HomeAssistant, mock_block_device, device_reg, monkeypatch
) -> None:
"""Test block restored climate.""" """Test block restored climate."""
monkeypatch.delattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "targetTemp") monkeypatch.delattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "targetTemp")
monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "valveError", 0) monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "valveError", 0)
@ -243,8 +251,8 @@ async def test_block_restored_climate(hass, mock_block_device, device_reg, monke
async def test_block_restored_climate_us_customery( async def test_block_restored_climate_us_customery(
hass, mock_block_device, device_reg, monkeypatch hass: HomeAssistant, mock_block_device, device_reg, monkeypatch
): ) -> None:
"""Test block restored climate with US CUSTOMATY unit system.""" """Test block restored climate with US CUSTOMATY unit system."""
hass.config.units = US_CUSTOMARY_SYSTEM hass.config.units = US_CUSTOMARY_SYSTEM
monkeypatch.delattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "targetTemp") monkeypatch.delattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "targetTemp")
@ -310,8 +318,8 @@ async def test_block_restored_climate_us_customery(
async def test_block_restored_climate_unavailable( async def test_block_restored_climate_unavailable(
hass, mock_block_device, device_reg, monkeypatch hass: HomeAssistant, mock_block_device, device_reg, monkeypatch
): ) -> None:
"""Test block restored climate unavailable state.""" """Test block restored climate unavailable state."""
monkeypatch.delattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "targetTemp") monkeypatch.delattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "targetTemp")
monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "valveError", 0) monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "valveError", 0)
@ -334,8 +342,8 @@ async def test_block_restored_climate_unavailable(
async def test_block_restored_climate_set_preset_before_online( async def test_block_restored_climate_set_preset_before_online(
hass, mock_block_device, device_reg, monkeypatch hass: HomeAssistant, mock_block_device, device_reg, monkeypatch
): ) -> None:
"""Test block restored climate set preset before device is online.""" """Test block restored climate set preset before device is online."""
monkeypatch.delattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "targetTemp") monkeypatch.delattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "targetTemp")
monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "valveError", 0) monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "valveError", 0)
@ -366,7 +374,9 @@ async def test_block_restored_climate_set_preset_before_online(
mock_block_device.http_request.assert_not_called() mock_block_device.http_request.assert_not_called()
async def test_block_set_mode_connection_error(hass, mock_block_device, monkeypatch): async def test_block_set_mode_connection_error(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device set mode connection error.""" """Test block device set mode connection error."""
monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "valveError", 0) monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "valveError", 0)
monkeypatch.setattr( monkeypatch.setattr(
@ -389,7 +399,9 @@ async def test_block_set_mode_connection_error(hass, mock_block_device, monkeypa
) )
async def test_block_set_mode_auth_error(hass, mock_block_device, monkeypatch): async def test_block_set_mode_auth_error(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device set mode authentication error.""" """Test block device set mode authentication error."""
monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "valveError", 0) monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "valveError", 0)
monkeypatch.setattr( monkeypatch.setattr(
@ -427,8 +439,8 @@ async def test_block_set_mode_auth_error(hass, mock_block_device, monkeypatch):
async def test_block_restored_climate_auth_error( async def test_block_restored_climate_auth_error(
hass, mock_block_device, device_reg, monkeypatch hass: HomeAssistant, mock_block_device, device_reg, monkeypatch
): ) -> None:
"""Test block restored climate with authentication error during init.""" """Test block restored climate with authentication error during init."""
monkeypatch.delattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "targetTemp") monkeypatch.delattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "targetTemp")
monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "valveError", 0) monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "valveError", 0)

View File

@ -26,6 +26,7 @@ from homeassistant.setup import async_setup_component
from . import init_integration from . import init_integration
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
from tests.typing import WebSocketGenerator
DISCOVERY_INFO = zeroconf.ZeroconfServiceInfo( DISCOVERY_INFO = zeroconf.ZeroconfServiceInfo(
host="1.1.1.1", host="1.1.1.1",
@ -54,7 +55,9 @@ DISCOVERY_INFO_WITH_MAC = zeroconf.ZeroconfServiceInfo(
(2, "SNSW-002P16EU"), (2, "SNSW-002P16EU"),
], ],
) )
async def test_form(hass, gen, model, mock_block_device, mock_rpc_device): async def test_form(
hass: HomeAssistant, gen, model, mock_block_device, mock_rpc_device
) -> None:
"""Test we get the form.""" """Test we get the form."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -107,8 +110,14 @@ async def test_form(hass, gen, model, mock_block_device, mock_rpc_device):
], ],
) )
async def test_form_auth( async def test_form_auth(
hass, gen, model, user_input, username, mock_block_device, mock_rpc_device hass: HomeAssistant,
): gen,
model,
user_input,
username,
mock_block_device,
mock_rpc_device,
) -> None:
"""Test manual configuration if auth is required.""" """Test manual configuration if auth is required."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -160,7 +169,7 @@ async def test_form_auth(
(ValueError, "unknown"), (ValueError, "unknown"),
], ],
) )
async def test_form_errors_get_info(hass, exc, base_error): async def test_form_errors_get_info(hass: HomeAssistant, exc, base_error) -> None:
"""Test we handle errors.""" """Test we handle errors."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -176,7 +185,9 @@ async def test_form_errors_get_info(hass, exc, base_error):
assert result2["errors"] == {"base": base_error} assert result2["errors"] == {"base": base_error}
async def test_form_missing_model_key(hass, mock_rpc_device, monkeypatch): async def test_form_missing_model_key(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test we handle missing Shelly model key.""" """Test we handle missing Shelly model key."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -195,7 +206,9 @@ async def test_form_missing_model_key(hass, mock_rpc_device, monkeypatch):
assert result2["errors"] == {"base": "firmware_not_fully_provisioned"} assert result2["errors"] == {"base": "firmware_not_fully_provisioned"}
async def test_form_missing_model_key_auth_enabled(hass, mock_rpc_device, monkeypatch): async def test_form_missing_model_key_auth_enabled(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test we handle missing Shelly model key when auth enabled.""" """Test we handle missing Shelly model key when auth enabled."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -224,8 +237,8 @@ async def test_form_missing_model_key_auth_enabled(hass, mock_rpc_device, monkey
async def test_form_missing_model_key_zeroconf( async def test_form_missing_model_key_zeroconf(
hass, mock_rpc_device, monkeypatch, caplog hass: HomeAssistant, mock_rpc_device, monkeypatch, caplog: pytest.LogCaptureFixture
): ) -> None:
"""Test we handle missing Shelly model key via zeroconf.""" """Test we handle missing Shelly model key via zeroconf."""
monkeypatch.setattr(mock_rpc_device, "shelly", {"gen": 2}) monkeypatch.setattr(mock_rpc_device, "shelly", {"gen": 2})
with patch( with patch(
@ -255,7 +268,9 @@ async def test_form_missing_model_key_zeroconf(
(ValueError, "unknown"), (ValueError, "unknown"),
], ],
) )
async def test_form_errors_test_connection(hass, exc, base_error): async def test_form_errors_test_connection(
hass: HomeAssistant, exc, base_error
) -> None:
"""Test we handle errors.""" """Test we handle errors."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -304,7 +319,9 @@ async def test_form_already_configured(hass: HomeAssistant) -> None:
assert entry.data["host"] == "1.1.1.1" assert entry.data["host"] == "1.1.1.1"
async def test_user_setup_ignored_device(hass, mock_block_device): async def test_user_setup_ignored_device(
hass: HomeAssistant, mock_block_device
) -> None:
"""Test user can successfully setup an ignored device.""" """Test user can successfully setup an ignored device."""
entry = MockConfigEntry( entry = MockConfigEntry(
@ -368,7 +385,9 @@ async def test_form_firmware_unsupported(hass: HomeAssistant) -> None:
(ValueError, "unknown"), (ValueError, "unknown"),
], ],
) )
async def test_form_auth_errors_test_connection_gen1(hass, exc, base_error): async def test_form_auth_errors_test_connection_gen1(
hass: HomeAssistant, exc, base_error
) -> None:
"""Test we handle errors in Gen1 authenticated devices.""" """Test we handle errors in Gen1 authenticated devices."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -403,7 +422,9 @@ async def test_form_auth_errors_test_connection_gen1(hass, exc, base_error):
(ValueError, "unknown"), (ValueError, "unknown"),
], ],
) )
async def test_form_auth_errors_test_connection_gen2(hass, exc, base_error): async def test_form_auth_errors_test_connection_gen2(
hass: HomeAssistant, exc, base_error
) -> None:
"""Test we handle errors in Gen2 authenticated devices.""" """Test we handle errors in Gen2 authenticated devices."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -444,7 +465,9 @@ async def test_form_auth_errors_test_connection_gen2(hass, exc, base_error):
), ),
], ],
) )
async def test_zeroconf(hass, gen, model, get_info, mock_block_device, mock_rpc_device): async def test_zeroconf(
hass: HomeAssistant, gen, model, get_info, mock_block_device, mock_rpc_device
) -> None:
"""Test we get the form.""" """Test we get the form."""
with patch( with patch(
@ -488,7 +511,9 @@ async def test_zeroconf(hass, gen, model, get_info, mock_block_device, mock_rpc_
assert len(mock_setup_entry.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
async def test_zeroconf_sleeping_device(hass, mock_block_device, monkeypatch): async def test_zeroconf_sleeping_device(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test sleeping device configuration via zeroconf.""" """Test sleeping device configuration via zeroconf."""
monkeypatch.setitem( monkeypatch.setitem(
mock_block_device.settings, mock_block_device.settings,
@ -667,7 +692,7 @@ async def test_zeroconf_cannot_connect(hass: HomeAssistant) -> None:
assert result["reason"] == "cannot_connect" assert result["reason"] == "cannot_connect"
async def test_zeroconf_require_auth(hass, mock_block_device): async def test_zeroconf_require_auth(hass: HomeAssistant, mock_block_device) -> None:
"""Test zeroconf if auth is required.""" """Test zeroconf if auth is required."""
with patch( with patch(
@ -716,8 +741,8 @@ async def test_zeroconf_require_auth(hass, mock_block_device):
], ],
) )
async def test_reauth_successful( async def test_reauth_successful(
hass, gen, user_input, mock_block_device, mock_rpc_device hass: HomeAssistant, gen, user_input, mock_block_device, mock_rpc_device
): ) -> None:
"""Test starting a reauthentication flow.""" """Test starting a reauthentication flow."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain="shelly", unique_id="test-mac", data={"host": "0.0.0.0", "gen": gen} domain="shelly", unique_id="test-mac", data={"host": "0.0.0.0", "gen": gen}
@ -753,7 +778,7 @@ async def test_reauth_successful(
(2, {"password": "test2 password"}), (2, {"password": "test2 password"}),
], ],
) )
async def test_reauth_unsuccessful(hass, gen, user_input): async def test_reauth_unsuccessful(hass: HomeAssistant, gen, user_input) -> None:
"""Test reauthentication flow failed.""" """Test reauthentication flow failed."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain="shelly", unique_id="test-mac", data={"host": "0.0.0.0", "gen": gen} domain="shelly", unique_id="test-mac", data={"host": "0.0.0.0", "gen": gen}
@ -792,7 +817,7 @@ async def test_reauth_unsuccessful(hass, gen, user_input):
"error", "error",
[DeviceConnectionError, FirmwareUnsupported], [DeviceConnectionError, FirmwareUnsupported],
) )
async def test_reauth_get_info_error(hass, error): async def test_reauth_get_info_error(hass: HomeAssistant, error) -> None:
"""Test reauthentication flow failed with error in get_info().""" """Test reauthentication flow failed with error in get_info()."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain="shelly", unique_id="test-mac", data={"host": "0.0.0.0", "gen": 2} domain="shelly", unique_id="test-mac", data={"host": "0.0.0.0", "gen": 2}
@ -821,7 +846,9 @@ async def test_reauth_get_info_error(hass, error):
assert result["reason"] == "reauth_unsuccessful" assert result["reason"] == "reauth_unsuccessful"
async def test_options_flow_disabled_gen_1(hass, mock_block_device, hass_ws_client): async def test_options_flow_disabled_gen_1(
hass: HomeAssistant, mock_block_device, hass_ws_client: WebSocketGenerator
) -> None:
"""Test options are disabled for gen1 devices.""" """Test options are disabled for gen1 devices."""
await async_setup_component(hass, "config", {}) await async_setup_component(hass, "config", {})
entry = await init_integration(hass, 1) entry = await init_integration(hass, 1)
@ -840,7 +867,9 @@ async def test_options_flow_disabled_gen_1(hass, mock_block_device, hass_ws_clie
await hass.config_entries.async_unload(entry.entry_id) await hass.config_entries.async_unload(entry.entry_id)
async def test_options_flow_enabled_gen_2(hass, mock_rpc_device, hass_ws_client): async def test_options_flow_enabled_gen_2(
hass: HomeAssistant, mock_rpc_device, hass_ws_client: WebSocketGenerator
) -> None:
"""Test options are enabled for gen2 devices.""" """Test options are enabled for gen2 devices."""
await async_setup_component(hass, "config", {}) await async_setup_component(hass, "config", {})
entry = await init_integration(hass, 2) entry = await init_integration(hass, 2)
@ -860,8 +889,8 @@ async def test_options_flow_enabled_gen_2(hass, mock_rpc_device, hass_ws_client)
async def test_options_flow_disabled_sleepy_gen_2( async def test_options_flow_disabled_sleepy_gen_2(
hass, mock_rpc_device, hass_ws_client hass: HomeAssistant, mock_rpc_device, hass_ws_client: WebSocketGenerator
): ) -> None:
"""Test options are disabled for sleepy gen2 devices.""" """Test options are disabled for sleepy gen2 devices."""
await async_setup_component(hass, "config", {}) await async_setup_component(hass, "config", {})
entry = await init_integration(hass, 2, sleep_period=10) entry = await init_integration(hass, 2, sleep_period=10)
@ -880,7 +909,7 @@ async def test_options_flow_disabled_sleepy_gen_2(
await hass.config_entries.async_unload(entry.entry_id) await hass.config_entries.async_unload(entry.entry_id)
async def test_options_flow_ble(hass, mock_rpc_device): async def test_options_flow_ble(hass: HomeAssistant, mock_rpc_device) -> None:
"""Test setting ble options for gen2 devices.""" """Test setting ble options for gen2 devices."""
entry = await init_integration(hass, 2) entry = await init_integration(hass, 2)
result = await hass.config_entries.options.async_init(entry.entry_id) result = await hass.config_entries.options.async_init(entry.entry_id)
@ -934,7 +963,9 @@ async def test_options_flow_ble(hass, mock_rpc_device):
await hass.config_entries.async_unload(entry.entry_id) await hass.config_entries.async_unload(entry.entry_id)
async def test_options_flow_pre_ble_device(hass, mock_pre_ble_rpc_device): async def test_options_flow_pre_ble_device(
hass: HomeAssistant, mock_pre_ble_rpc_device
) -> None:
"""Test setting ble options for gen2 devices with pre ble firmware.""" """Test setting ble options for gen2 devices with pre ble firmware."""
entry = await init_integration(hass, 2) entry = await init_integration(hass, 2)
result = await hass.config_entries.options.async_init(entry.entry_id) result = await hass.config_entries.options.async_init(entry.entry_id)
@ -989,8 +1020,8 @@ async def test_options_flow_pre_ble_device(hass, mock_pre_ble_rpc_device):
async def test_zeroconf_already_configured_triggers_refresh_mac_in_name( async def test_zeroconf_already_configured_triggers_refresh_mac_in_name(
hass, mock_rpc_device, monkeypatch hass: HomeAssistant, mock_rpc_device, monkeypatch
): ) -> None:
"""Test zeroconf discovery triggers refresh when the mac is in the device name.""" """Test zeroconf discovery triggers refresh when the mac is in the device name."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain="shelly", domain="shelly",
@ -1021,8 +1052,8 @@ async def test_zeroconf_already_configured_triggers_refresh_mac_in_name(
async def test_zeroconf_already_configured_triggers_refresh( async def test_zeroconf_already_configured_triggers_refresh(
hass, mock_rpc_device, monkeypatch hass: HomeAssistant, mock_rpc_device, monkeypatch
): ) -> None:
"""Test zeroconf discovery triggers refresh when the mac is obtained via get_info.""" """Test zeroconf discovery triggers refresh when the mac is obtained via get_info."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain="shelly", domain="shelly",
@ -1053,8 +1084,8 @@ async def test_zeroconf_already_configured_triggers_refresh(
async def test_zeroconf_sleeping_device_not_triggers_refresh( async def test_zeroconf_sleeping_device_not_triggers_refresh(
hass, mock_rpc_device, monkeypatch, caplog hass: HomeAssistant, mock_rpc_device, monkeypatch, caplog: pytest.LogCaptureFixture
): ) -> None:
"""Test zeroconf discovery does not triggers refresh for sleeping device.""" """Test zeroconf discovery does not triggers refresh for sleeping device."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain="shelly", domain="shelly",

View File

@ -19,6 +19,7 @@ from homeassistant.components.shelly.const import (
) )
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
from homeassistant.const import ATTR_DEVICE_ID, STATE_ON, STATE_UNAVAILABLE from homeassistant.const import ATTR_DEVICE_ID, STATE_ON, STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import ( from homeassistant.helpers.device_registry import (
async_entries_for_config_entry, async_entries_for_config_entry,
async_get as async_get_dev_reg, async_get as async_get_dev_reg,
@ -41,7 +42,9 @@ SENSOR_BLOCK_ID = 3
DEVICE_BLOCK_ID = 4 DEVICE_BLOCK_ID = 4
async def test_block_reload_on_cfg_change(hass, mock_block_device, monkeypatch): async def test_block_reload_on_cfg_change(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block reload on config change.""" """Test block reload on config change."""
await init_integration(hass, 1) await init_integration(hass, 1)
@ -68,7 +71,9 @@ async def test_block_reload_on_cfg_change(hass, mock_block_device, monkeypatch):
assert hass.states.get("switch.test_name_channel_1") is None assert hass.states.get("switch.test_name_channel_1") is None
async def test_block_no_reload_on_bulb_changes(hass, mock_block_device, monkeypatch): async def test_block_no_reload_on_bulb_changes(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block no reload on bulb mode/effect change.""" """Test block no reload on bulb mode/effect change."""
await init_integration(hass, 1, model="SHBLB-1") await init_integration(hass, 1, model="SHBLB-1")
@ -112,7 +117,9 @@ async def test_block_no_reload_on_bulb_changes(hass, mock_block_device, monkeypa
assert hass.states.get("switch.test_name_channel_1") is not None assert hass.states.get("switch.test_name_channel_1") is not None
async def test_block_polling_auth_error(hass, mock_block_device, monkeypatch): async def test_block_polling_auth_error(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device polling authentication error.""" """Test block device polling authentication error."""
monkeypatch.setattr( monkeypatch.setattr(
mock_block_device, mock_block_device,
@ -143,7 +150,9 @@ async def test_block_polling_auth_error(hass, mock_block_device, monkeypatch):
assert flow["context"].get("entry_id") == entry.entry_id assert flow["context"].get("entry_id") == entry.entry_id
async def test_block_rest_update_auth_error(hass, mock_block_device, monkeypatch): async def test_block_rest_update_auth_error(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block REST update authentication error.""" """Test block REST update authentication error."""
register_entity(hass, BINARY_SENSOR_DOMAIN, "test_name_cloud", "cloud") register_entity(hass, BINARY_SENSOR_DOMAIN, "test_name_cloud", "cloud")
monkeypatch.setitem(mock_block_device.status, "cloud", {"connected": False}) monkeypatch.setitem(mock_block_device.status, "cloud", {"connected": False})
@ -174,7 +183,9 @@ async def test_block_rest_update_auth_error(hass, mock_block_device, monkeypatch
assert flow["context"].get("entry_id") == entry.entry_id assert flow["context"].get("entry_id") == entry.entry_id
async def test_block_polling_connection_error(hass, mock_block_device, monkeypatch): async def test_block_polling_connection_error(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device polling connection error.""" """Test block device polling connection error."""
monkeypatch.setattr( monkeypatch.setattr(
mock_block_device, mock_block_device,
@ -194,7 +205,9 @@ async def test_block_polling_connection_error(hass, mock_block_device, monkeypat
assert hass.states.get("switch.test_name_channel_1").state == STATE_UNAVAILABLE assert hass.states.get("switch.test_name_channel_1").state == STATE_UNAVAILABLE
async def test_block_rest_update_connection_error(hass, mock_block_device, monkeypatch): async def test_block_rest_update_connection_error(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block REST update connection error.""" """Test block REST update connection error."""
entity_id = register_entity(hass, BINARY_SENSOR_DOMAIN, "test_name_cloud", "cloud") entity_id = register_entity(hass, BINARY_SENSOR_DOMAIN, "test_name_cloud", "cloud")
monkeypatch.setitem(mock_block_device.status, "cloud", {"connected": True}) monkeypatch.setitem(mock_block_device.status, "cloud", {"connected": True})
@ -214,7 +227,9 @@ async def test_block_rest_update_connection_error(hass, mock_block_device, monke
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
async def test_block_sleeping_device_no_periodic_updates(hass, mock_block_device): async def test_block_sleeping_device_no_periodic_updates(
hass: HomeAssistant, mock_block_device
) -> None:
"""Test block sleeping device no periodic updates.""" """Test block sleeping device no periodic updates."""
entity_id = f"{SENSOR_DOMAIN}.test_name_temperature" entity_id = f"{SENSOR_DOMAIN}.test_name_temperature"
await init_integration(hass, 1, sleep_period=1000) await init_integration(hass, 1, sleep_period=1000)
@ -234,7 +249,9 @@ async def test_block_sleeping_device_no_periodic_updates(hass, mock_block_device
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
async def test_block_button_click_event(hass, mock_block_device, events, monkeypatch): async def test_block_button_click_event(
hass: HomeAssistant, mock_block_device, events, monkeypatch
) -> None:
"""Test block click event for Shelly button.""" """Test block click event for Shelly button."""
monkeypatch.setattr(mock_block_device.blocks[RELAY_BLOCK_ID], "sensor_ids", {}) monkeypatch.setattr(mock_block_device.blocks[RELAY_BLOCK_ID], "sensor_ids", {})
monkeypatch.setattr( monkeypatch.setattr(
@ -275,7 +292,9 @@ async def test_block_button_click_event(hass, mock_block_device, events, monkeyp
assert len(events) == 1 assert len(events) == 1
async def test_rpc_reload_on_cfg_change(hass, mock_rpc_device, monkeypatch): async def test_rpc_reload_on_cfg_change(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC reload on config change.""" """Test RPC reload on config change."""
await init_integration(hass, 2) await init_integration(hass, 2)
@ -316,7 +335,9 @@ async def test_rpc_reload_on_cfg_change(hass, mock_rpc_device, monkeypatch):
assert hass.states.get("switch.test_switch_0") is None assert hass.states.get("switch.test_switch_0") is None
async def test_rpc_click_event(hass, mock_rpc_device, events, monkeypatch): async def test_rpc_click_event(
hass: HomeAssistant, mock_rpc_device, events, monkeypatch
) -> None:
"""Test RPC click event.""" """Test RPC click event."""
entry = await init_integration(hass, 2) entry = await init_integration(hass, 2)
@ -351,7 +372,9 @@ async def test_rpc_click_event(hass, mock_rpc_device, events, monkeypatch):
} }
async def test_rpc_update_entry_sleep_period(hass, mock_rpc_device, monkeypatch): async def test_rpc_update_entry_sleep_period(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC update entry sleep period.""" """Test RPC update entry sleep period."""
entry = await init_integration(hass, 2, sleep_period=600) entry = await init_integration(hass, 2, sleep_period=600)
register_entity( register_entity(
@ -379,8 +402,8 @@ async def test_rpc_update_entry_sleep_period(hass, mock_rpc_device, monkeypatch)
async def test_rpc_sleeping_device_no_periodic_updates( async def test_rpc_sleeping_device_no_periodic_updates(
hass, mock_rpc_device, monkeypatch hass: HomeAssistant, mock_rpc_device, monkeypatch
): ) -> None:
"""Test RPC sleeping device no periodic updates.""" """Test RPC sleeping device no periodic updates."""
entity_id = f"{SENSOR_DOMAIN}.test_name_temperature" entity_id = f"{SENSOR_DOMAIN}.test_name_temperature"
entry = await init_integration(hass, 2, sleep_period=1000) entry = await init_integration(hass, 2, sleep_period=1000)
@ -407,7 +430,9 @@ async def test_rpc_sleeping_device_no_periodic_updates(
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
async def test_rpc_reconnect_auth_error(hass, mock_rpc_device, monkeypatch): async def test_rpc_reconnect_auth_error(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC reconnect authentication error.""" """Test RPC reconnect authentication error."""
entry = await init_integration(hass, 2) entry = await init_integration(hass, 2)
@ -442,7 +467,9 @@ async def test_rpc_reconnect_auth_error(hass, mock_rpc_device, monkeypatch):
assert flow["context"].get("entry_id") == entry.entry_id assert flow["context"].get("entry_id") == entry.entry_id
async def test_rpc_polling_auth_error(hass, mock_rpc_device, monkeypatch) -> None: async def test_rpc_polling_auth_error(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC polling authentication error.""" """Test RPC polling authentication error."""
register_entity(hass, SENSOR_DOMAIN, "test_name_rssi", "wifi-rssi") register_entity(hass, SENSOR_DOMAIN, "test_name_rssi", "wifi-rssi")
entry = await init_integration(hass, 2) entry = await init_integration(hass, 2)
@ -473,7 +500,9 @@ async def test_rpc_polling_auth_error(hass, mock_rpc_device, monkeypatch) -> Non
assert flow["context"].get("entry_id") == entry.entry_id assert flow["context"].get("entry_id") == entry.entry_id
async def test_rpc_reconnect_error(hass, mock_rpc_device, monkeypatch): async def test_rpc_reconnect_error(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC reconnect error.""" """Test RPC reconnect error."""
await init_integration(hass, 2) await init_integration(hass, 2)
@ -497,7 +526,9 @@ async def test_rpc_reconnect_error(hass, mock_rpc_device, monkeypatch):
assert hass.states.get("switch.test_switch_0").state == STATE_UNAVAILABLE assert hass.states.get("switch.test_switch_0").state == STATE_UNAVAILABLE
async def test_rpc_polling_connection_error(hass, mock_rpc_device, monkeypatch) -> None: async def test_rpc_polling_connection_error(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC polling connection error.""" """Test RPC polling connection error."""
entity_id = register_entity(hass, SENSOR_DOMAIN, "test_name_rssi", "wifi-rssi") entity_id = register_entity(hass, SENSOR_DOMAIN, "test_name_rssi", "wifi-rssi")
await init_integration(hass, 2) await init_integration(hass, 2)
@ -517,7 +548,9 @@ async def test_rpc_polling_connection_error(hass, mock_rpc_device, monkeypatch)
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
async def test_rpc_polling_disconnected(hass, mock_rpc_device, monkeypatch) -> None: async def test_rpc_polling_disconnected(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC polling device disconnected.""" """Test RPC polling device disconnected."""
entity_id = register_entity(hass, SENSOR_DOMAIN, "test_name_rssi", "wifi-rssi") entity_id = register_entity(hass, SENSOR_DOMAIN, "test_name_rssi", "wifi-rssi")
await init_integration(hass, 2) await init_integration(hass, 2)

View File

@ -24,7 +24,9 @@ from . import init_integration, mutate_rpc_device_status
ROLLER_BLOCK_ID = 1 ROLLER_BLOCK_ID = 1
async def test_block_device_services(hass, mock_block_device, monkeypatch): async def test_block_device_services(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device cover services.""" """Test block device cover services."""
monkeypatch.setitem(mock_block_device.settings, "mode", "roller") monkeypatch.setitem(mock_block_device.settings, "mode", "roller")
await init_integration(hass, 1) await init_integration(hass, 1)
@ -63,7 +65,9 @@ async def test_block_device_services(hass, mock_block_device, monkeypatch):
assert hass.states.get("cover.test_name").state == STATE_CLOSED assert hass.states.get("cover.test_name").state == STATE_CLOSED
async def test_block_device_update(hass, mock_block_device, monkeypatch): async def test_block_device_update(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device update.""" """Test block device update."""
monkeypatch.setattr(mock_block_device.blocks[ROLLER_BLOCK_ID], "rollerPos", 0) monkeypatch.setattr(mock_block_device.blocks[ROLLER_BLOCK_ID], "rollerPos", 0)
await init_integration(hass, 1) await init_integration(hass, 1)
@ -75,7 +79,9 @@ async def test_block_device_update(hass, mock_block_device, monkeypatch):
assert hass.states.get("cover.test_name").state == STATE_OPEN assert hass.states.get("cover.test_name").state == STATE_OPEN
async def test_block_device_no_roller_blocks(hass, mock_block_device, monkeypatch): async def test_block_device_no_roller_blocks(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device without roller blocks.""" """Test block device without roller blocks."""
monkeypatch.setattr(mock_block_device.blocks[ROLLER_BLOCK_ID], "type", None) monkeypatch.setattr(mock_block_device.blocks[ROLLER_BLOCK_ID], "type", None)
await init_integration(hass, 1) await init_integration(hass, 1)

View File

@ -14,6 +14,7 @@ from homeassistant.components.shelly.const import (
EVENT_SHELLY_CLICK, EVENT_SHELLY_CLICK,
) )
from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import ( from homeassistant.helpers.device_registry import (
CONNECTION_NETWORK_MAC, CONNECTION_NETWORK_MAC,
async_entries_for_config_entry, async_entries_for_config_entry,
@ -40,8 +41,8 @@ from tests.common import (
], ],
) )
async def test_get_triggers_block_device( async def test_get_triggers_block_device(
hass, mock_block_device, monkeypatch, button_type, is_valid hass: HomeAssistant, mock_block_device, monkeypatch, button_type, is_valid
): ) -> None:
"""Test we get the expected triggers from a shelly block device.""" """Test we get the expected triggers from a shelly block device."""
monkeypatch.setitem( monkeypatch.setitem(
mock_block_device.settings, mock_block_device.settings,
@ -76,7 +77,7 @@ async def test_get_triggers_block_device(
assert_lists_same(triggers, expected_triggers) assert_lists_same(triggers, expected_triggers)
async def test_get_triggers_rpc_device(hass, mock_rpc_device): async def test_get_triggers_rpc_device(hass: HomeAssistant, mock_rpc_device) -> None:
"""Test we get the expected triggers from a shelly RPC device.""" """Test we get the expected triggers from a shelly RPC device."""
entry = await init_integration(hass, 2) entry = await init_integration(hass, 2)
dev_reg = async_get_dev_reg(hass) dev_reg = async_get_dev_reg(hass)
@ -108,7 +109,7 @@ async def test_get_triggers_rpc_device(hass, mock_rpc_device):
assert_lists_same(triggers, expected_triggers) assert_lists_same(triggers, expected_triggers)
async def test_get_triggers_button(hass, mock_block_device): async def test_get_triggers_button(hass: HomeAssistant, mock_block_device) -> None:
"""Test we get the expected triggers from a shelly button.""" """Test we get the expected triggers from a shelly button."""
entry = await init_integration(hass, 1, model="SHBTN-1") entry = await init_integration(hass, 1, model="SHBTN-1")
dev_reg = async_get_dev_reg(hass) dev_reg = async_get_dev_reg(hass)
@ -134,8 +135,8 @@ async def test_get_triggers_button(hass, mock_block_device):
async def test_get_triggers_non_initialized_devices( async def test_get_triggers_non_initialized_devices(
hass, mock_block_device, monkeypatch hass: HomeAssistant, mock_block_device, monkeypatch
): ) -> None:
"""Test we get the empty triggers for non-initialized devices.""" """Test we get the empty triggers for non-initialized devices."""
monkeypatch.setattr(mock_block_device, "initialized", False) monkeypatch.setattr(mock_block_device, "initialized", False)
entry = await init_integration(hass, 1) entry = await init_integration(hass, 1)
@ -151,7 +152,9 @@ async def test_get_triggers_non_initialized_devices(
assert_lists_same(triggers, expected_triggers) assert_lists_same(triggers, expected_triggers)
async def test_get_triggers_for_invalid_device_id(hass, device_reg, mock_block_device): async def test_get_triggers_for_invalid_device_id(
hass: HomeAssistant, device_reg, mock_block_device
) -> None:
"""Test error raised for invalid shelly device_id.""" """Test error raised for invalid shelly device_id."""
await init_integration(hass, 1) await init_integration(hass, 1)
config_entry = MockConfigEntry(domain=DOMAIN, data={}) config_entry = MockConfigEntry(domain=DOMAIN, data={})
@ -167,7 +170,9 @@ async def test_get_triggers_for_invalid_device_id(hass, device_reg, mock_block_d
) )
async def test_if_fires_on_click_event_block_device(hass, calls, mock_block_device): async def test_if_fires_on_click_event_block_device(
hass: HomeAssistant, calls, mock_block_device
) -> None:
"""Test for click_event trigger firing for block device.""" """Test for click_event trigger firing for block device."""
entry = await init_integration(hass, 1) entry = await init_integration(hass, 1)
dev_reg = async_get_dev_reg(hass) dev_reg = async_get_dev_reg(hass)
@ -207,7 +212,9 @@ async def test_if_fires_on_click_event_block_device(hass, calls, mock_block_devi
assert calls[0].data["some"] == "test_trigger_single_click" assert calls[0].data["some"] == "test_trigger_single_click"
async def test_if_fires_on_click_event_rpc_device(hass, calls, mock_rpc_device): async def test_if_fires_on_click_event_rpc_device(
hass: HomeAssistant, calls, mock_rpc_device
) -> None:
"""Test for click_event trigger firing for rpc device.""" """Test for click_event trigger firing for rpc device."""
entry = await init_integration(hass, 2) entry = await init_integration(hass, 2)
dev_reg = async_get_dev_reg(hass) dev_reg = async_get_dev_reg(hass)
@ -248,8 +255,8 @@ async def test_if_fires_on_click_event_rpc_device(hass, calls, mock_rpc_device):
async def test_validate_trigger_block_device_not_ready( async def test_validate_trigger_block_device_not_ready(
hass, calls, mock_block_device, monkeypatch hass: HomeAssistant, calls, mock_block_device, monkeypatch
): ) -> None:
"""Test validate trigger config when block device is not ready.""" """Test validate trigger config when block device is not ready."""
monkeypatch.setattr(mock_block_device, "initialized", False) monkeypatch.setattr(mock_block_device, "initialized", False)
entry = await init_integration(hass, 1) entry = await init_integration(hass, 1)
@ -290,8 +297,8 @@ async def test_validate_trigger_block_device_not_ready(
async def test_validate_trigger_rpc_device_not_ready( async def test_validate_trigger_rpc_device_not_ready(
hass, calls, mock_rpc_device, monkeypatch hass: HomeAssistant, calls, mock_rpc_device, monkeypatch
): ) -> None:
"""Test validate trigger config when RPC device is not ready.""" """Test validate trigger config when RPC device is not ready."""
monkeypatch.setattr(mock_rpc_device, "initialized", False) monkeypatch.setattr(mock_rpc_device, "initialized", False)
entry = await init_integration(hass, 2) entry = await init_integration(hass, 2)
@ -331,7 +338,9 @@ async def test_validate_trigger_rpc_device_not_ready(
assert calls[0].data["some"] == "test_trigger_single_push" assert calls[0].data["some"] == "test_trigger_single_push"
async def test_validate_trigger_invalid_triggers(hass, mock_block_device, caplog): async def test_validate_trigger_invalid_triggers(
hass: HomeAssistant, mock_block_device, caplog: pytest.LogCaptureFixture
) -> None:
"""Test for click_event with invalid triggers.""" """Test for click_event with invalid triggers."""
entry = await init_integration(hass, 1) entry = await init_integration(hass, 1)
dev_reg = async_get_dev_reg(hass) dev_reg = async_get_dev_reg(hass)

View File

@ -23,7 +23,7 @@ RELAY_BLOCK_ID = 0
async def test_block_config_entry_diagnostics( async def test_block_config_entry_diagnostics(
hass: HomeAssistant, hass_client: ClientSessionGenerator, mock_block_device hass: HomeAssistant, hass_client: ClientSessionGenerator, mock_block_device
): ) -> None:
"""Test config entry diagnostics for block device.""" """Test config entry diagnostics for block device."""
await init_integration(hass, 1) await init_integration(hass, 1)
@ -53,7 +53,7 @@ async def test_rpc_config_entry_diagnostics(
hass_client: ClientSessionGenerator, hass_client: ClientSessionGenerator,
mock_rpc_device, mock_rpc_device,
monkeypatch, monkeypatch,
): ) -> None:
"""Test config entry diagnostics for rpc device.""" """Test config entry diagnostics for rpc device."""
await init_integration( await init_integration(
hass, 2, options={CONF_BLE_SCANNER_MODE: BLEScannerMode.ACTIVE} hass, 2, options={CONF_BLE_SCANNER_MODE: BLEScannerMode.ACTIVE}

View File

@ -22,7 +22,9 @@ from . import MOCK_MAC, init_integration
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
async def test_custom_coap_port(hass, mock_block_device, caplog): async def test_custom_coap_port(
hass: HomeAssistant, mock_block_device, caplog: pytest.LogCaptureFixture
) -> None:
"""Test custom coap port.""" """Test custom coap port."""
assert await async_setup_component( assert await async_setup_component(
hass, hass,
@ -37,8 +39,13 @@ async def test_custom_coap_port(hass, mock_block_device, caplog):
@pytest.mark.parametrize("gen", [1, 2]) @pytest.mark.parametrize("gen", [1, 2])
async def test_shared_device_mac( async def test_shared_device_mac(
hass, gen, mock_block_device, mock_rpc_device, device_reg, caplog hass: HomeAssistant,
): gen,
mock_block_device,
mock_rpc_device,
device_reg,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test first time shared device with another domain.""" """Test first time shared device with another domain."""
config_entry = MockConfigEntry(domain="test", data={}, unique_id="some_id") config_entry = MockConfigEntry(domain="test", data={}, unique_id="some_id")
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -65,8 +72,8 @@ async def test_setup_entry_not_shelly(
@pytest.mark.parametrize("gen", [1, 2]) @pytest.mark.parametrize("gen", [1, 2])
async def test_device_connection_error( async def test_device_connection_error(
hass, gen, mock_block_device, mock_rpc_device, monkeypatch hass: HomeAssistant, gen, mock_block_device, mock_rpc_device, monkeypatch
): ) -> None:
"""Test device connection error.""" """Test device connection error."""
monkeypatch.setattr( monkeypatch.setattr(
mock_block_device, "initialize", AsyncMock(side_effect=DeviceConnectionError) mock_block_device, "initialize", AsyncMock(side_effect=DeviceConnectionError)
@ -81,8 +88,8 @@ async def test_device_connection_error(
@pytest.mark.parametrize("gen", [1, 2]) @pytest.mark.parametrize("gen", [1, 2])
async def test_device_auth_error( async def test_device_auth_error(
hass, gen, mock_block_device, mock_rpc_device, monkeypatch hass: HomeAssistant, gen, mock_block_device, mock_rpc_device, monkeypatch
): ) -> None:
"""Test device authentication error.""" """Test device authentication error."""
monkeypatch.setattr( monkeypatch.setattr(
mock_block_device, "initialize", AsyncMock(side_effect=InvalidAuthError) mock_block_device, "initialize", AsyncMock(side_effect=InvalidAuthError)
@ -108,8 +115,13 @@ async def test_device_auth_error(
@pytest.mark.parametrize(("entry_sleep", "device_sleep"), [(None, 0), (1000, 1000)]) @pytest.mark.parametrize(("entry_sleep", "device_sleep"), [(None, 0), (1000, 1000)])
async def test_sleeping_block_device_online( async def test_sleeping_block_device_online(
hass, entry_sleep, device_sleep, mock_block_device, device_reg, caplog hass: HomeAssistant,
): entry_sleep,
device_sleep,
mock_block_device,
device_reg,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test sleeping block device online.""" """Test sleeping block device online."""
config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id="shelly") config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id="shelly")
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -128,8 +140,12 @@ async def test_sleeping_block_device_online(
@pytest.mark.parametrize(("entry_sleep", "device_sleep"), [(None, 0), (1000, 1000)]) @pytest.mark.parametrize(("entry_sleep", "device_sleep"), [(None, 0), (1000, 1000)])
async def test_sleeping_rpc_device_online( async def test_sleeping_rpc_device_online(
hass, entry_sleep, device_sleep, mock_rpc_device, caplog hass: HomeAssistant,
): entry_sleep,
device_sleep,
mock_rpc_device,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test sleeping RPC device online.""" """Test sleeping RPC device online."""
entry = await init_integration(hass, 2, sleep_period=entry_sleep) entry = await init_integration(hass, 2, sleep_period=entry_sleep)
assert "will resume when device is online" in caplog.text assert "will resume when device is online" in caplog.text
@ -146,7 +162,9 @@ async def test_sleeping_rpc_device_online(
(2, "switch.test_switch_0"), (2, "switch.test_switch_0"),
], ],
) )
async def test_entry_unload(hass, gen, entity_id, mock_block_device, mock_rpc_device): async def test_entry_unload(
hass: HomeAssistant, gen, entity_id, mock_block_device, mock_rpc_device
) -> None:
"""Test entry unload.""" """Test entry unload."""
entry = await init_integration(hass, gen) entry = await init_integration(hass, gen)
@ -168,8 +186,8 @@ async def test_entry_unload(hass, gen, entity_id, mock_block_device, mock_rpc_de
], ],
) )
async def test_entry_unload_device_not_ready( async def test_entry_unload_device_not_ready(
hass, gen, entity_id, mock_block_device, mock_rpc_device hass: HomeAssistant, gen, entity_id, mock_block_device, mock_rpc_device
): ) -> None:
"""Test entry unload when device is not ready.""" """Test entry unload when device is not ready."""
entry = await init_integration(hass, gen, sleep_period=1000) entry = await init_integration(hass, gen, sleep_period=1000)
@ -182,7 +200,9 @@ async def test_entry_unload_device_not_ready(
assert entry.state is ConfigEntryState.NOT_LOADED assert entry.state is ConfigEntryState.NOT_LOADED
async def test_entry_unload_not_connected(hass, mock_rpc_device, monkeypatch): async def test_entry_unload_not_connected(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test entry unload when not connected.""" """Test entry unload when not connected."""
with patch( with patch(
"homeassistant.components.shelly.coordinator.async_stop_scanner" "homeassistant.components.shelly.coordinator.async_stop_scanner"
@ -206,8 +226,8 @@ async def test_entry_unload_not_connected(hass, mock_rpc_device, monkeypatch):
async def test_entry_unload_not_connected_but_we_think_we_are( async def test_entry_unload_not_connected_but_we_think_we_are(
hass, mock_rpc_device, monkeypatch hass: HomeAssistant, mock_rpc_device, monkeypatch
): ) -> None:
"""Test entry unload when not connected but we think we are still connected.""" """Test entry unload when not connected but we think we are still connected."""
with patch( with patch(
"homeassistant.components.shelly.coordinator.async_stop_scanner", "homeassistant.components.shelly.coordinator.async_stop_scanner",
@ -231,7 +251,9 @@ async def test_entry_unload_not_connected_but_we_think_we_are(
assert entry.state is ConfigEntryState.LOADED assert entry.state is ConfigEntryState.LOADED
async def test_no_attempt_to_stop_scanner_with_sleepy_devices(hass, mock_rpc_device): async def test_no_attempt_to_stop_scanner_with_sleepy_devices(
hass: HomeAssistant, mock_rpc_device
) -> None:
"""Test we do not try to stop the scanner if its disabled with a sleepy device.""" """Test we do not try to stop the scanner if its disabled with a sleepy device."""
with patch( with patch(
"homeassistant.components.shelly.coordinator.async_stop_scanner", "homeassistant.components.shelly.coordinator.async_stop_scanner",

View File

@ -1,5 +1,4 @@
"""Tests for Shelly light platform.""" """Tests for Shelly light platform."""
import pytest import pytest
from homeassistant.components.light import ( from homeassistant.components.light import (
@ -24,6 +23,7 @@ from homeassistant.const import (
STATE_OFF, STATE_OFF,
STATE_ON, STATE_ON,
) )
from homeassistant.core import HomeAssistant
from . import init_integration, mutate_rpc_device_status from . import init_integration, mutate_rpc_device_status
@ -31,7 +31,7 @@ RELAY_BLOCK_ID = 0
LIGHT_BLOCK_ID = 2 LIGHT_BLOCK_ID = 2
async def test_block_device_rgbw_bulb(hass, mock_block_device): async def test_block_device_rgbw_bulb(hass: HomeAssistant, mock_block_device) -> None:
"""Test block device RGBW bulb.""" """Test block device RGBW bulb."""
await init_integration(hass, 1, model="SHBLB-1") await init_integration(hass, 1, model="SHBLB-1")
@ -105,7 +105,12 @@ async def test_block_device_rgbw_bulb(hass, mock_block_device):
assert attributes[ATTR_COLOR_TEMP_KELVIN] == 3500 assert attributes[ATTR_COLOR_TEMP_KELVIN] == 3500
async def test_block_device_rgb_bulb(hass, mock_block_device, monkeypatch, caplog): async def test_block_device_rgb_bulb(
hass: HomeAssistant,
mock_block_device,
monkeypatch,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test block device RGB bulb.""" """Test block device RGB bulb."""
monkeypatch.delattr(mock_block_device.blocks[LIGHT_BLOCK_ID], "mode") monkeypatch.delattr(mock_block_device.blocks[LIGHT_BLOCK_ID], "mode")
await init_integration(hass, 1, model="SHCB-1") await init_integration(hass, 1, model="SHCB-1")
@ -197,7 +202,12 @@ async def test_block_device_rgb_bulb(hass, mock_block_device, monkeypatch, caplo
assert "Effect 'Breath' not supported" in caplog.text assert "Effect 'Breath' not supported" in caplog.text
async def test_block_device_white_bulb(hass, mock_block_device, monkeypatch, caplog): async def test_block_device_white_bulb(
hass: HomeAssistant,
mock_block_device,
monkeypatch,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test block device white bulb.""" """Test block device white bulb."""
monkeypatch.delattr(mock_block_device.blocks[LIGHT_BLOCK_ID], "red") monkeypatch.delattr(mock_block_device.blocks[LIGHT_BLOCK_ID], "red")
monkeypatch.delattr(mock_block_device.blocks[LIGHT_BLOCK_ID], "green") monkeypatch.delattr(mock_block_device.blocks[LIGHT_BLOCK_ID], "green")
@ -258,8 +268,8 @@ async def test_block_device_white_bulb(hass, mock_block_device, monkeypatch, cap
], ],
) )
async def test_block_device_support_transition( async def test_block_device_support_transition(
hass, mock_block_device, model, monkeypatch hass: HomeAssistant, mock_block_device, model, monkeypatch
): ) -> None:
"""Test block device supports transition.""" """Test block device supports transition."""
monkeypatch.setitem( monkeypatch.setitem(
mock_block_device.settings, "fw", "20220809-122808/v1.12-g99f7e0b" mock_block_device.settings, "fw", "20220809-122808/v1.12-g99f7e0b"
@ -300,7 +310,9 @@ async def test_block_device_support_transition(
assert state.state == STATE_OFF assert state.state == STATE_OFF
async def test_block_device_relay_app_type_light(hass, mock_block_device, monkeypatch): async def test_block_device_relay_app_type_light(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device relay in app type set to light mode.""" """Test block device relay in app type set to light mode."""
monkeypatch.delattr(mock_block_device.blocks[RELAY_BLOCK_ID], "red") monkeypatch.delattr(mock_block_device.blocks[RELAY_BLOCK_ID], "red")
monkeypatch.delattr(mock_block_device.blocks[RELAY_BLOCK_ID], "green") monkeypatch.delattr(mock_block_device.blocks[RELAY_BLOCK_ID], "green")
@ -352,14 +364,18 @@ async def test_block_device_relay_app_type_light(hass, mock_block_device, monkey
assert state.state == STATE_ON assert state.state == STATE_ON
async def test_block_device_no_light_blocks(hass, mock_block_device, monkeypatch): async def test_block_device_no_light_blocks(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device without light blocks.""" """Test block device without light blocks."""
monkeypatch.setattr(mock_block_device.blocks[LIGHT_BLOCK_ID], "type", "roller") monkeypatch.setattr(mock_block_device.blocks[LIGHT_BLOCK_ID], "type", "roller")
await init_integration(hass, 1) await init_integration(hass, 1)
assert hass.states.get("light.test_name_channel_1") is None assert hass.states.get("light.test_name_channel_1") is None
async def test_rpc_device_switch_type_lights_mode(hass, mock_rpc_device, monkeypatch): async def test_rpc_device_switch_type_lights_mode(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC device with switch in consumption type lights mode.""" """Test RPC device with switch in consumption type lights mode."""
monkeypatch.setitem( monkeypatch.setitem(
mock_rpc_device.config["sys"]["ui_data"], "consumption_types", ["lights"] mock_rpc_device.config["sys"]["ui_data"], "consumption_types", ["lights"]
@ -385,7 +401,7 @@ async def test_rpc_device_switch_type_lights_mode(hass, mock_rpc_device, monkeyp
assert hass.states.get("light.test_switch_0").state == STATE_OFF assert hass.states.get("light.test_switch_0").state == STATE_OFF
async def test_rpc_light(hass, mock_rpc_device, monkeypatch): async def test_rpc_light(hass: HomeAssistant, mock_rpc_device, monkeypatch) -> None:
"""Test RPC light.""" """Test RPC light."""
entity_id = f"{LIGHT_DOMAIN}.test_light_0" entity_id = f"{LIGHT_DOMAIN}.test_light_0"
monkeypatch.delitem(mock_rpc_device.status, "switch:0") monkeypatch.delitem(mock_rpc_device.status, "switch:0")

View File

@ -7,6 +7,7 @@ from homeassistant.components.shelly.const import (
EVENT_SHELLY_CLICK, EVENT_SHELLY_CLICK,
) )
from homeassistant.const import ATTR_DEVICE_ID from homeassistant.const import ATTR_DEVICE_ID
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import ( from homeassistant.helpers.device_registry import (
async_entries_for_config_entry, async_entries_for_config_entry,
async_get as async_get_dev_reg, async_get as async_get_dev_reg,
@ -18,7 +19,9 @@ from . import init_integration
from tests.components.logbook.common import MockRow, mock_humanify from tests.components.logbook.common import MockRow, mock_humanify
async def test_humanify_shelly_click_event_block_device(hass, mock_block_device): async def test_humanify_shelly_click_event_block_device(
hass: HomeAssistant, mock_block_device
) -> None:
"""Test humanifying Shelly click event for block device.""" """Test humanifying Shelly click event for block device."""
entry = await init_integration(hass, 1) entry = await init_integration(hass, 1)
dev_reg = async_get_dev_reg(hass) dev_reg = async_get_dev_reg(hass)
@ -66,7 +69,9 @@ async def test_humanify_shelly_click_event_block_device(hass, mock_block_device)
) )
async def test_humanify_shelly_click_event_rpc_device(hass, mock_rpc_device): async def test_humanify_shelly_click_event_rpc_device(
hass: HomeAssistant, mock_rpc_device
) -> None:
"""Test humanifying Shelly click event for rpc device.""" """Test humanifying Shelly click event for rpc device."""
entry = await init_integration(hass, 2) entry = await init_integration(hass, 2)
dev_reg = async_get_dev_reg(hass) dev_reg = async_get_dev_reg(hass)

View File

@ -12,7 +12,7 @@ from homeassistant.components.number import (
from homeassistant.components.shelly.const import DOMAIN from homeassistant.components.shelly.const import DOMAIN
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN
from homeassistant.core import State from homeassistant.core import HomeAssistant, State
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from . import init_integration, register_device, register_entity from . import init_integration, register_device, register_entity
@ -22,7 +22,9 @@ from tests.common import mock_restore_cache
DEVICE_BLOCK_ID = 4 DEVICE_BLOCK_ID = 4
async def test_block_number_update(hass, mock_block_device, monkeypatch): async def test_block_number_update(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device number update.""" """Test block device number update."""
await init_integration(hass, 1, sleep_period=1000) await init_integration(hass, 1, sleep_period=1000)
@ -40,7 +42,9 @@ async def test_block_number_update(hass, mock_block_device, monkeypatch):
assert hass.states.get("number.test_name_valve_position").state == "30" assert hass.states.get("number.test_name_valve_position").state == "30"
async def test_block_restored_number(hass, mock_block_device, device_reg, monkeypatch): async def test_block_restored_number(
hass: HomeAssistant, mock_block_device, device_reg, monkeypatch
) -> None:
"""Test block restored number.""" """Test block restored number."""
entry = await init_integration(hass, 1, sleep_period=1000, skip_setup=True) entry = await init_integration(hass, 1, sleep_period=1000, skip_setup=True)
register_device(device_reg, entry) register_device(device_reg, entry)
@ -75,8 +79,8 @@ async def test_block_restored_number(hass, mock_block_device, device_reg, monkey
async def test_block_restored_number_no_last_state( async def test_block_restored_number_no_last_state(
hass, mock_block_device, device_reg, monkeypatch hass: HomeAssistant, mock_block_device, device_reg, monkeypatch
): ) -> None:
"""Test block restored number missing last state.""" """Test block restored number missing last state."""
entry = await init_integration(hass, 1, sleep_period=1000, skip_setup=True) entry = await init_integration(hass, 1, sleep_period=1000, skip_setup=True)
register_device(device_reg, entry) register_device(device_reg, entry)
@ -108,7 +112,7 @@ async def test_block_restored_number_no_last_state(
assert hass.states.get(entity_id).state == "50" assert hass.states.get(entity_id).state == "50"
async def test_block_number_set_value(hass, mock_block_device): async def test_block_number_set_value(hass: HomeAssistant, mock_block_device) -> None:
"""Test block device number set value.""" """Test block device number set value."""
await init_integration(hass, 1, sleep_period=1000) await init_integration(hass, 1, sleep_period=1000)
@ -128,7 +132,9 @@ async def test_block_number_set_value(hass, mock_block_device):
) )
async def test_block_set_value_connection_error(hass, mock_block_device, monkeypatch): async def test_block_set_value_connection_error(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device set value connection error.""" """Test block device set value connection error."""
monkeypatch.setattr( monkeypatch.setattr(
mock_block_device, mock_block_device,
@ -150,7 +156,9 @@ async def test_block_set_value_connection_error(hass, mock_block_device, monkeyp
) )
async def test_block_set_value_auth_error(hass, mock_block_device, monkeypatch): async def test_block_set_value_auth_error(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device set value authentication error.""" """Test block device set value authentication error."""
monkeypatch.setattr( monkeypatch.setattr(
mock_block_device, mock_block_device,

View File

@ -1,9 +1,7 @@
"""Tests for Shelly sensor platform.""" """Tests for Shelly sensor platform."""
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.core import State from homeassistant.core import HomeAssistant, State
from homeassistant.helpers.entity_registry import async_get from homeassistant.helpers.entity_registry import async_get
from . import ( from . import (
@ -22,7 +20,9 @@ SENSOR_BLOCK_ID = 3
DEVICE_BLOCK_ID = 4 DEVICE_BLOCK_ID = 4
async def test_block_sensor(hass, mock_block_device, monkeypatch): async def test_block_sensor(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block sensor.""" """Test block sensor."""
entity_id = f"{SENSOR_DOMAIN}.test_name_channel_1_power" entity_id = f"{SENSOR_DOMAIN}.test_name_channel_1_power"
await init_integration(hass, 1) await init_integration(hass, 1)
@ -35,7 +35,9 @@ async def test_block_sensor(hass, mock_block_device, monkeypatch):
assert hass.states.get(entity_id).state == "60.1" assert hass.states.get(entity_id).state == "60.1"
async def test_block_rest_sensor(hass, mock_block_device, monkeypatch): async def test_block_rest_sensor(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block REST sensor.""" """Test block REST sensor."""
entity_id = register_entity(hass, SENSOR_DOMAIN, "test_name_rssi", "rssi") entity_id = register_entity(hass, SENSOR_DOMAIN, "test_name_rssi", "rssi")
await init_integration(hass, 1) await init_integration(hass, 1)
@ -48,7 +50,9 @@ async def test_block_rest_sensor(hass, mock_block_device, monkeypatch):
assert hass.states.get(entity_id).state == "-71" assert hass.states.get(entity_id).state == "-71"
async def test_block_sleeping_sensor(hass, mock_block_device, monkeypatch): async def test_block_sleeping_sensor(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block sleeping sensor.""" """Test block sleeping sensor."""
monkeypatch.setattr( monkeypatch.setattr(
mock_block_device.blocks[DEVICE_BLOCK_ID], "sensor_ids", {"battery": 98} mock_block_device.blocks[DEVICE_BLOCK_ID], "sensor_ids", {"battery": 98}
@ -72,8 +76,8 @@ async def test_block_sleeping_sensor(hass, mock_block_device, monkeypatch):
async def test_block_restored_sleeping_sensor( async def test_block_restored_sleeping_sensor(
hass, mock_block_device, device_reg, monkeypatch hass: HomeAssistant, mock_block_device, device_reg, monkeypatch
): ) -> None:
"""Test block restored sleeping sensor.""" """Test block restored sleeping sensor."""
entry = await init_integration(hass, 1, sleep_period=1000, skip_setup=True) entry = await init_integration(hass, 1, sleep_period=1000, skip_setup=True)
register_device(device_reg, entry) register_device(device_reg, entry)
@ -96,8 +100,8 @@ async def test_block_restored_sleeping_sensor(
async def test_block_restored_sleeping_sensor_no_last_state( async def test_block_restored_sleeping_sensor_no_last_state(
hass, mock_block_device, device_reg, monkeypatch hass: HomeAssistant, mock_block_device, device_reg, monkeypatch
): ) -> None:
"""Test block restored sleeping sensor missing last state.""" """Test block restored sleeping sensor missing last state."""
entry = await init_integration(hass, 1, sleep_period=1000, skip_setup=True) entry = await init_integration(hass, 1, sleep_period=1000, skip_setup=True)
register_device(device_reg, entry) register_device(device_reg, entry)
@ -118,7 +122,9 @@ async def test_block_restored_sleeping_sensor_no_last_state(
assert hass.states.get(entity_id).state == "22.1" assert hass.states.get(entity_id).state == "22.1"
async def test_block_sensor_error(hass, mock_block_device, monkeypatch): async def test_block_sensor_error(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block sensor unavailable on sensor error.""" """Test block sensor unavailable on sensor error."""
entity_id = f"{SENSOR_DOMAIN}.test_name_battery" entity_id = f"{SENSOR_DOMAIN}.test_name_battery"
await init_integration(hass, 1) await init_integration(hass, 1)
@ -131,7 +137,9 @@ async def test_block_sensor_error(hass, mock_block_device, monkeypatch):
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
async def test_block_sensor_removal(hass, mock_block_device, monkeypatch): async def test_block_sensor_removal(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block sensor is removed due to removal_condition.""" """Test block sensor is removed due to removal_condition."""
entity_registry = async_get(hass) entity_registry = async_get(hass)
entity_id = register_entity( entity_id = register_entity(
@ -147,8 +155,8 @@ async def test_block_sensor_removal(hass, mock_block_device, monkeypatch):
async def test_block_not_matched_restored_sleeping_sensor( async def test_block_not_matched_restored_sleeping_sensor(
hass, mock_block_device, device_reg, monkeypatch hass: HomeAssistant, mock_block_device, device_reg, monkeypatch
): ) -> None:
"""Test block not matched to restored sleeping sensor.""" """Test block not matched to restored sleeping sensor."""
entry = await init_integration(hass, 1, sleep_period=1000, skip_setup=True) entry = await init_integration(hass, 1, sleep_period=1000, skip_setup=True)
register_device(device_reg, entry) register_device(device_reg, entry)
@ -171,7 +179,9 @@ async def test_block_not_matched_restored_sleeping_sensor(
assert hass.states.get(entity_id).state == "20.4" assert hass.states.get(entity_id).state == "20.4"
async def test_block_sensor_without_value(hass, mock_block_device, monkeypatch): async def test_block_sensor_without_value(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block sensor without value is not created.""" """Test block sensor without value is not created."""
entity_id = f"{SENSOR_DOMAIN}.test_name_battery" entity_id = f"{SENSOR_DOMAIN}.test_name_battery"
monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "battery", None) monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "battery", None)
@ -180,7 +190,9 @@ async def test_block_sensor_without_value(hass, mock_block_device, monkeypatch):
assert hass.states.get(entity_id) is None assert hass.states.get(entity_id) is None
async def test_block_sensor_unknown_value(hass, mock_block_device, monkeypatch): async def test_block_sensor_unknown_value(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block sensor unknown value.""" """Test block sensor unknown value."""
entity_id = f"{SENSOR_DOMAIN}.test_name_battery" entity_id = f"{SENSOR_DOMAIN}.test_name_battery"
await init_integration(hass, 1) await init_integration(hass, 1)
@ -191,7 +203,7 @@ async def test_block_sensor_unknown_value(hass, mock_block_device, monkeypatch):
assert hass.states.get(entity_id).state == STATE_UNKNOWN assert hass.states.get(entity_id).state == STATE_UNKNOWN
async def test_rpc_sensor(hass, mock_rpc_device, monkeypatch) -> None: async def test_rpc_sensor(hass: HomeAssistant, mock_rpc_device, monkeypatch) -> None:
"""Test RPC sensor.""" """Test RPC sensor."""
entity_id = f"{SENSOR_DOMAIN}.test_cover_0_power" entity_id = f"{SENSOR_DOMAIN}.test_cover_0_power"
await init_integration(hass, 2) await init_integration(hass, 2)
@ -209,7 +221,9 @@ async def test_rpc_sensor(hass, mock_rpc_device, monkeypatch) -> None:
assert hass.states.get(entity_id).state == STATE_UNKNOWN assert hass.states.get(entity_id).state == STATE_UNKNOWN
async def test_rpc_sensor_error(hass, mock_rpc_device, monkeypatch): async def test_rpc_sensor_error(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC sensor unavailable on sensor error.""" """Test RPC sensor unavailable on sensor error."""
entity_id = f"{SENSOR_DOMAIN}.test_name_voltmeter" entity_id = f"{SENSOR_DOMAIN}.test_name_voltmeter"
await init_integration(hass, 2) await init_integration(hass, 2)
@ -222,7 +236,9 @@ async def test_rpc_sensor_error(hass, mock_rpc_device, monkeypatch):
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
async def test_rpc_polling_sensor(hass, mock_rpc_device, monkeypatch) -> None: async def test_rpc_polling_sensor(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC polling sensor.""" """Test RPC polling sensor."""
entity_id = register_entity(hass, SENSOR_DOMAIN, "test_name_rssi", "wifi-rssi") entity_id = register_entity(hass, SENSOR_DOMAIN, "test_name_rssi", "wifi-rssi")
await init_integration(hass, 2) await init_integration(hass, 2)
@ -236,7 +252,7 @@ async def test_rpc_polling_sensor(hass, mock_rpc_device, monkeypatch) -> None:
async def test_rpc_sleeping_sensor( async def test_rpc_sleeping_sensor(
hass, mock_rpc_device, device_reg, monkeypatch hass: HomeAssistant, mock_rpc_device, device_reg, monkeypatch
) -> None: ) -> None:
"""Test RPC online sleeping sensor.""" """Test RPC online sleeping sensor."""
entity_id = f"{SENSOR_DOMAIN}.test_name_temperature" entity_id = f"{SENSOR_DOMAIN}.test_name_temperature"
@ -266,8 +282,8 @@ async def test_rpc_sleeping_sensor(
async def test_rpc_restored_sleeping_sensor( async def test_rpc_restored_sleeping_sensor(
hass, mock_rpc_device, device_reg, monkeypatch hass: HomeAssistant, mock_rpc_device, device_reg, monkeypatch
): ) -> None:
"""Test RPC restored sensor.""" """Test RPC restored sensor."""
entry = await init_integration(hass, 2, sleep_period=1000, skip_setup=True) entry = await init_integration(hass, 2, sleep_period=1000, skip_setup=True)
register_device(device_reg, entry) register_device(device_reg, entry)
@ -296,8 +312,8 @@ async def test_rpc_restored_sleeping_sensor(
async def test_rpc_restored_sleeping_sensor_no_last_state( async def test_rpc_restored_sleeping_sensor_no_last_state(
hass, mock_rpc_device, device_reg, monkeypatch hass: HomeAssistant, mock_rpc_device, device_reg, monkeypatch
): ) -> None:
"""Test RPC restored sensor missing last state.""" """Test RPC restored sensor missing last state."""
entry = await init_integration(hass, 2, sleep_period=1000, skip_setup=True) entry = await init_integration(hass, 2, sleep_period=1000, skip_setup=True)
register_device(device_reg, entry) register_device(device_reg, entry)

View File

@ -14,6 +14,7 @@ from homeassistant.const import (
STATE_OFF, STATE_OFF,
STATE_ON, STATE_ON,
) )
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from . import init_integration from . import init_integration
@ -21,7 +22,7 @@ from . import init_integration
RELAY_BLOCK_ID = 0 RELAY_BLOCK_ID = 0
async def test_block_device_services(hass, mock_block_device): async def test_block_device_services(hass: HomeAssistant, mock_block_device) -> None:
"""Test block device turn on/off services.""" """Test block device turn on/off services."""
await init_integration(hass, 1) await init_integration(hass, 1)
@ -42,7 +43,9 @@ async def test_block_device_services(hass, mock_block_device):
assert hass.states.get("switch.test_name_channel_1").state == STATE_OFF assert hass.states.get("switch.test_name_channel_1").state == STATE_OFF
async def test_block_set_state_connection_error(hass, mock_block_device, monkeypatch): async def test_block_set_state_connection_error(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device set state connection error.""" """Test block device set state connection error."""
monkeypatch.setattr( monkeypatch.setattr(
mock_block_device.blocks[RELAY_BLOCK_ID], mock_block_device.blocks[RELAY_BLOCK_ID],
@ -60,7 +63,9 @@ async def test_block_set_state_connection_error(hass, mock_block_device, monkeyp
) )
async def test_block_set_state_auth_error(hass, mock_block_device, monkeypatch): async def test_block_set_state_auth_error(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device set state authentication error.""" """Test block device set state authentication error."""
monkeypatch.setattr( monkeypatch.setattr(
mock_block_device.blocks[RELAY_BLOCK_ID], mock_block_device.blocks[RELAY_BLOCK_ID],
@ -92,7 +97,9 @@ async def test_block_set_state_auth_error(hass, mock_block_device, monkeypatch):
assert flow["context"].get("entry_id") == entry.entry_id assert flow["context"].get("entry_id") == entry.entry_id
async def test_block_device_update(hass, mock_block_device, monkeypatch): async def test_block_device_update(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device update.""" """Test block device update."""
monkeypatch.setattr(mock_block_device.blocks[RELAY_BLOCK_ID], "output", False) monkeypatch.setattr(mock_block_device.blocks[RELAY_BLOCK_ID], "output", False)
await init_integration(hass, 1) await init_integration(hass, 1)
@ -103,21 +110,27 @@ async def test_block_device_update(hass, mock_block_device, monkeypatch):
assert hass.states.get("switch.test_name_channel_1").state == STATE_ON assert hass.states.get("switch.test_name_channel_1").state == STATE_ON
async def test_block_device_no_relay_blocks(hass, mock_block_device, monkeypatch): async def test_block_device_no_relay_blocks(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device without relay blocks.""" """Test block device without relay blocks."""
monkeypatch.setattr(mock_block_device.blocks[RELAY_BLOCK_ID], "type", "roller") monkeypatch.setattr(mock_block_device.blocks[RELAY_BLOCK_ID], "type", "roller")
await init_integration(hass, 1) await init_integration(hass, 1)
assert hass.states.get("switch.test_name_channel_1") is None assert hass.states.get("switch.test_name_channel_1") is None
async def test_block_device_mode_roller(hass, mock_block_device, monkeypatch): async def test_block_device_mode_roller(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device in roller mode.""" """Test block device in roller mode."""
monkeypatch.setitem(mock_block_device.settings, "mode", "roller") monkeypatch.setitem(mock_block_device.settings, "mode", "roller")
await init_integration(hass, 1) await init_integration(hass, 1)
assert hass.states.get("switch.test_name_channel_1") is None assert hass.states.get("switch.test_name_channel_1") is None
async def test_block_device_app_type_light(hass, mock_block_device, monkeypatch): async def test_block_device_app_type_light(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device in app type set to light mode.""" """Test block device in app type set to light mode."""
monkeypatch.setitem( monkeypatch.setitem(
mock_block_device.settings["relays"][RELAY_BLOCK_ID], "appliance_type", "light" mock_block_device.settings["relays"][RELAY_BLOCK_ID], "appliance_type", "light"
@ -126,7 +139,9 @@ async def test_block_device_app_type_light(hass, mock_block_device, monkeypatch)
assert hass.states.get("switch.test_name_channel_1") is None assert hass.states.get("switch.test_name_channel_1") is None
async def test_rpc_device_services(hass, mock_rpc_device, monkeypatch): async def test_rpc_device_services(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC device turn on/off services.""" """Test RPC device turn on/off services."""
await init_integration(hass, 2) await init_integration(hass, 2)
@ -149,7 +164,9 @@ async def test_rpc_device_services(hass, mock_rpc_device, monkeypatch):
assert hass.states.get("switch.test_switch_0").state == STATE_OFF assert hass.states.get("switch.test_switch_0").state == STATE_OFF
async def test_rpc_device_switch_type_lights_mode(hass, mock_rpc_device, monkeypatch): async def test_rpc_device_switch_type_lights_mode(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC device with switch in consumption type lights mode.""" """Test RPC device with switch in consumption type lights mode."""
monkeypatch.setitem( monkeypatch.setitem(
mock_rpc_device.config["sys"]["ui_data"], "consumption_types", ["lights"] mock_rpc_device.config["sys"]["ui_data"], "consumption_types", ["lights"]
@ -159,7 +176,9 @@ async def test_rpc_device_switch_type_lights_mode(hass, mock_rpc_device, monkeyp
@pytest.mark.parametrize("exc", [DeviceConnectionError, RpcCallError(-1, "error")]) @pytest.mark.parametrize("exc", [DeviceConnectionError, RpcCallError(-1, "error")])
async def test_rpc_set_state_errors(hass, exc, mock_rpc_device, monkeypatch): async def test_rpc_set_state_errors(
hass: HomeAssistant, exc, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC device set state connection/call errors.""" """Test RPC device set state connection/call errors."""
monkeypatch.setattr(mock_rpc_device, "call_rpc", AsyncMock(side_effect=exc)) monkeypatch.setattr(mock_rpc_device, "call_rpc", AsyncMock(side_effect=exc))
await init_integration(hass, 2) await init_integration(hass, 2)
@ -173,7 +192,9 @@ async def test_rpc_set_state_errors(hass, exc, mock_rpc_device, monkeypatch):
) )
async def test_rpc_auth_error(hass, mock_rpc_device, monkeypatch): async def test_rpc_auth_error(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC device set state authentication error.""" """Test RPC device set state authentication error."""
monkeypatch.setattr( monkeypatch.setattr(
mock_rpc_device, mock_rpc_device,

View File

@ -36,7 +36,9 @@ from . import (
from tests.common import mock_restore_cache from tests.common import mock_restore_cache
async def test_block_update(hass: HomeAssistant, mock_block_device, monkeypatch): async def test_block_update(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device update entity.""" """Test block device update entity."""
entity_registry = async_get(hass) entity_registry = async_get(hass)
entity_registry.async_get_or_create( entity_registry.async_get_or_create(
@ -82,7 +84,9 @@ async def test_block_update(hass: HomeAssistant, mock_block_device, monkeypatch)
assert state.attributes[ATTR_IN_PROGRESS] is False assert state.attributes[ATTR_IN_PROGRESS] is False
async def test_block_beta_update(hass: HomeAssistant, mock_block_device, monkeypatch): async def test_block_beta_update(
hass: HomeAssistant, mock_block_device, monkeypatch
) -> None:
"""Test block device beta update entity.""" """Test block device beta update entity."""
entity_registry = async_get(hass) entity_registry = async_get(hass)
entity_registry.async_get_or_create( entity_registry.async_get_or_create(
@ -137,8 +141,11 @@ async def test_block_beta_update(hass: HomeAssistant, mock_block_device, monkeyp
async def test_block_update_connection_error( async def test_block_update_connection_error(
hass: HomeAssistant, mock_block_device, monkeypatch, caplog hass: HomeAssistant,
): mock_block_device,
monkeypatch,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test block device update connection error.""" """Test block device update connection error."""
entity_registry = async_get(hass) entity_registry = async_get(hass)
entity_registry.async_get_or_create( entity_registry.async_get_or_create(
@ -169,7 +176,7 @@ async def test_block_update_connection_error(
async def test_block_update_auth_error( async def test_block_update_auth_error(
hass: HomeAssistant, mock_block_device, monkeypatch hass: HomeAssistant, mock_block_device, monkeypatch
): ) -> None:
"""Test block device update authentication error.""" """Test block device update authentication error."""
entity_registry = async_get(hass) entity_registry = async_get(hass)
entity_registry.async_get_or_create( entity_registry.async_get_or_create(
@ -211,7 +218,7 @@ async def test_block_update_auth_error(
assert flow["context"].get("entry_id") == entry.entry_id assert flow["context"].get("entry_id") == entry.entry_id
async def test_rpc_update(hass: HomeAssistant, mock_rpc_device, monkeypatch): async def test_rpc_update(hass: HomeAssistant, mock_rpc_device, monkeypatch) -> None:
"""Test RPC device update entity.""" """Test RPC device update entity."""
monkeypatch.setitem(mock_rpc_device.shelly, "ver", "1") monkeypatch.setitem(mock_rpc_device.shelly, "ver", "1")
monkeypatch.setitem( monkeypatch.setitem(
@ -255,7 +262,9 @@ async def test_rpc_update(hass: HomeAssistant, mock_rpc_device, monkeypatch):
assert state.attributes[ATTR_IN_PROGRESS] is False assert state.attributes[ATTR_IN_PROGRESS] is False
async def test_rpc_sleeping_update(hass: HomeAssistant, mock_rpc_device, monkeypatch): async def test_rpc_sleeping_update(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC sleeping device update entity.""" """Test RPC sleeping device update entity."""
monkeypatch.setitem(mock_rpc_device.shelly, "ver", "1") monkeypatch.setitem(mock_rpc_device.shelly, "ver", "1")
monkeypatch.setitem( monkeypatch.setitem(
@ -294,8 +303,8 @@ async def test_rpc_sleeping_update(hass: HomeAssistant, mock_rpc_device, monkeyp
async def test_rpc_restored_sleeping_update( async def test_rpc_restored_sleeping_update(
hass, mock_rpc_device, device_reg, monkeypatch hass: HomeAssistant, mock_rpc_device, device_reg, monkeypatch
): ) -> None:
"""Test RPC restored update entity.""" """Test RPC restored update entity."""
entry = await init_integration(hass, 2, sleep_period=1000, skip_setup=True) entry = await init_integration(hass, 2, sleep_period=1000, skip_setup=True)
register_device(device_reg, entry) register_device(device_reg, entry)
@ -337,8 +346,8 @@ async def test_rpc_restored_sleeping_update(
async def test_rpc_restored_sleeping_update_no_last_state( async def test_rpc_restored_sleeping_update_no_last_state(
hass, mock_rpc_device, device_reg, monkeypatch hass: HomeAssistant, mock_rpc_device, device_reg, monkeypatch
): ) -> None:
"""Test RPC restored update entity missing last state.""" """Test RPC restored update entity missing last state."""
monkeypatch.setitem(mock_rpc_device.shelly, "ver", "1") monkeypatch.setitem(mock_rpc_device.shelly, "ver", "1")
monkeypatch.setitem( monkeypatch.setitem(
@ -378,7 +387,9 @@ async def test_rpc_restored_sleeping_update_no_last_state(
assert state.attributes[ATTR_SUPPORTED_FEATURES] == UpdateEntityFeature(0) assert state.attributes[ATTR_SUPPORTED_FEATURES] == UpdateEntityFeature(0)
async def test_rpc_beta_update(hass: HomeAssistant, mock_rpc_device, monkeypatch): async def test_rpc_beta_update(
hass: HomeAssistant, mock_rpc_device, monkeypatch
) -> None:
"""Test RPC device beta update entity.""" """Test RPC device beta update entity."""
entity_registry = async_get(hass) entity_registry = async_get(hass)
entity_registry.async_get_or_create( entity_registry.async_get_or_create(
@ -453,8 +464,13 @@ async def test_rpc_beta_update(hass: HomeAssistant, mock_rpc_device, monkeypatch
], ],
) )
async def test_rpc_update__errors( async def test_rpc_update__errors(
hass: HomeAssistant, exc, error, mock_rpc_device, monkeypatch, caplog hass: HomeAssistant,
): exc,
error,
mock_rpc_device,
monkeypatch,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test RPC device update connection/call errors.""" """Test RPC device update connection/call errors."""
entity_registry = async_get(hass) entity_registry = async_get(hass)
entity_registry.async_get_or_create( entity_registry.async_get_or_create(
@ -489,8 +505,8 @@ async def test_rpc_update__errors(
async def test_rpc_update_auth_error( async def test_rpc_update_auth_error(
hass: HomeAssistant, mock_rpc_device, monkeypatch, caplog hass: HomeAssistant, mock_rpc_device, monkeypatch, caplog: pytest.LogCaptureFixture
): ) -> None:
"""Test RPC device update authentication error.""" """Test RPC device update authentication error."""
entity_registry = async_get(hass) entity_registry = async_get(hass)
entity_registry.async_get_or_create( entity_registry.async_get_or_create(

View File

@ -17,7 +17,7 @@ from homeassistant.util import dt
DEVICE_BLOCK_ID = 4 DEVICE_BLOCK_ID = 4
async def test_block_get_number_of_channels(mock_block_device, monkeypatch): async def test_block_get_number_of_channels(mock_block_device, monkeypatch) -> None:
"""Test block get number of channels.""" """Test block get number of channels."""
monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "type", "emeter") monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "type", "emeter")
monkeypatch.setitem(mock_block_device.shelly, "num_emeters", 3) monkeypatch.setitem(mock_block_device.shelly, "num_emeters", 3)
@ -50,7 +50,7 @@ async def test_block_get_number_of_channels(mock_block_device, monkeypatch):
) )
async def test_block_get_block_channel_name(mock_block_device, monkeypatch): async def test_block_get_block_channel_name(mock_block_device, monkeypatch) -> None:
"""Test block get block channel name.""" """Test block get block channel name."""
monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "type", "relay") monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "type", "relay")
@ -85,7 +85,7 @@ async def test_block_get_block_channel_name(mock_block_device, monkeypatch):
) )
async def test_is_block_momentary_input(mock_block_device, monkeypatch): async def test_is_block_momentary_input(mock_block_device, monkeypatch) -> None:
"""Test is block momentary input.""" """Test is block momentary input."""
monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "type", "relay") monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "type", "relay")
@ -145,7 +145,7 @@ async def test_is_block_momentary_input(mock_block_device, monkeypatch):
({"sleep_mode": {"period": 5, "unit": "h"}}, 5 * 3600), ({"sleep_mode": {"period": 5, "unit": "h"}}, 5 * 3600),
], ],
) )
async def test_get_block_device_sleep_period(settings, sleep_period): async def test_get_block_device_sleep_period(settings, sleep_period) -> None:
"""Test get block device sleep period.""" """Test get block device sleep period."""
assert get_block_device_sleep_period(settings) == sleep_period assert get_block_device_sleep_period(settings) == sleep_period
@ -162,7 +162,7 @@ async def test_get_device_uptime() -> None:
) == dt.as_utc(dt.parse_datetime("2019-01-10 18:42:10+00:00")) ) == dt.as_utc(dt.parse_datetime("2019-01-10 18:42:10+00:00"))
async def test_get_block_input_triggers(mock_block_device, monkeypatch): async def test_get_block_input_triggers(mock_block_device, monkeypatch) -> None:
"""Test get block input triggers.""" """Test get block input triggers."""
monkeypatch.setattr( monkeypatch.setattr(
mock_block_device.blocks[DEVICE_BLOCK_ID], mock_block_device.blocks[DEVICE_BLOCK_ID],
@ -205,13 +205,13 @@ async def test_get_block_input_triggers(mock_block_device, monkeypatch):
} }
async def test_get_rpc_channel_name(mock_rpc_device): async def test_get_rpc_channel_name(mock_rpc_device) -> None:
"""Test get RPC channel name.""" """Test get RPC channel name."""
assert get_rpc_channel_name(mock_rpc_device, "input:0") == "test switch_0" assert get_rpc_channel_name(mock_rpc_device, "input:0") == "test switch_0"
assert get_rpc_channel_name(mock_rpc_device, "input:3") == "Test name switch_3" assert get_rpc_channel_name(mock_rpc_device, "input:3") == "Test name switch_3"
async def test_get_rpc_input_triggers(mock_rpc_device, monkeypatch): async def test_get_rpc_input_triggers(mock_rpc_device, monkeypatch) -> None:
"""Test get RPC input triggers.""" """Test get RPC input triggers."""
monkeypatch.setattr(mock_rpc_device, "config", {"input:0": {"type": "button"}}) monkeypatch.setattr(mock_rpc_device, "config", {"input:0": {"type": "button"}})
assert set(get_rpc_input_triggers(mock_rpc_device)) == { assert set(get_rpc_input_triggers(mock_rpc_device)) == {

View File

@ -18,12 +18,14 @@ from homeassistant.components.websocket_api.const import (
TYPE_RESULT, TYPE_RESULT,
) )
from homeassistant.const import ATTR_NAME from homeassistant.const import ATTR_NAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers import intent from homeassistant.helpers import intent
from tests.common import async_capture_events from tests.common import async_capture_events
from tests.typing import ClientSessionGenerator, WebSocketGenerator
async def test_add_item(hass, sl_setup): async def test_add_item(hass: HomeAssistant, sl_setup) -> None:
"""Test adding an item intent.""" """Test adding an item intent."""
response = await intent.async_handle( response = await intent.async_handle(
@ -33,7 +35,7 @@ async def test_add_item(hass, sl_setup):
assert response.speech["plain"]["speech"] == "I've added beer to your shopping list" assert response.speech["plain"]["speech"] == "I've added beer to your shopping list"
async def test_remove_item(hass, sl_setup): async def test_remove_item(hass: HomeAssistant, sl_setup) -> None:
"""Test removiung list items.""" """Test removiung list items."""
await intent.async_handle( await intent.async_handle(
hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}} hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}}
@ -59,7 +61,7 @@ async def test_remove_item(hass, sl_setup):
await hass.data[DOMAIN].async_remove(item_id) await hass.data[DOMAIN].async_remove(item_id)
async def test_update_list(hass, sl_setup): async def test_update_list(hass: HomeAssistant, sl_setup) -> None:
"""Test updating all list items.""" """Test updating all list items."""
await intent.async_handle( await intent.async_handle(
hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}} hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}}
@ -92,7 +94,7 @@ async def test_update_list(hass, sl_setup):
assert cheese["complete"] is False assert cheese["complete"] is False
async def test_clear_completed_items(hass, sl_setup): async def test_clear_completed_items(hass: HomeAssistant, sl_setup) -> None:
"""Test clear completed list items.""" """Test clear completed list items."""
await intent.async_handle( await intent.async_handle(
hass, hass,
@ -115,7 +117,7 @@ async def test_clear_completed_items(hass, sl_setup):
assert len(hass.data[DOMAIN].items) == 0 assert len(hass.data[DOMAIN].items) == 0
async def test_recent_items_intent(hass, sl_setup): async def test_recent_items_intent(hass: HomeAssistant, sl_setup) -> None:
"""Test recent items.""" """Test recent items."""
await intent.async_handle( await intent.async_handle(
@ -136,7 +138,9 @@ async def test_recent_items_intent(hass, sl_setup):
) )
async def test_deprecated_api_get_all(hass, hass_client, sl_setup): async def test_deprecated_api_get_all(
hass: HomeAssistant, hass_client: ClientSessionGenerator, sl_setup
) -> None:
"""Test the API.""" """Test the API."""
await intent.async_handle( await intent.async_handle(
@ -158,7 +162,9 @@ async def test_deprecated_api_get_all(hass, hass_client, sl_setup):
assert not data[1]["complete"] assert not data[1]["complete"]
async def test_ws_get_items(hass, hass_ws_client, sl_setup): async def test_ws_get_items(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, sl_setup
) -> None:
"""Test get shopping_list items websocket command.""" """Test get shopping_list items websocket command."""
await intent.async_handle( await intent.async_handle(
@ -187,7 +193,9 @@ async def test_ws_get_items(hass, hass_ws_client, sl_setup):
assert not data[1]["complete"] assert not data[1]["complete"]
async def test_deprecated_api_update(hass, hass_client, sl_setup): async def test_deprecated_api_update(
hass: HomeAssistant, hass_client: ClientSessionGenerator, sl_setup
) -> None:
"""Test the API.""" """Test the API."""
await intent.async_handle( await intent.async_handle(
@ -225,7 +233,9 @@ async def test_deprecated_api_update(hass, hass_client, sl_setup):
assert wine == {"id": wine_id, "name": "wine", "complete": True} assert wine == {"id": wine_id, "name": "wine", "complete": True}
async def test_ws_update_item(hass, hass_ws_client, sl_setup): async def test_ws_update_item(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, sl_setup
) -> None:
"""Test update shopping_list item websocket command.""" """Test update shopping_list item websocket command."""
await intent.async_handle( await intent.async_handle(
hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}} hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}}
@ -271,7 +281,9 @@ async def test_ws_update_item(hass, hass_ws_client, sl_setup):
assert wine == {"id": wine_id, "name": "wine", "complete": True} assert wine == {"id": wine_id, "name": "wine", "complete": True}
async def test_api_update_fails(hass, hass_client, sl_setup): async def test_api_update_fails(
hass: HomeAssistant, hass_client: ClientSessionGenerator, sl_setup
) -> None:
"""Test the API.""" """Test the API."""
await intent.async_handle( await intent.async_handle(
@ -291,7 +303,9 @@ async def test_api_update_fails(hass, hass_client, sl_setup):
assert resp.status == HTTPStatus.BAD_REQUEST assert resp.status == HTTPStatus.BAD_REQUEST
async def test_ws_update_item_fail(hass, hass_ws_client, sl_setup): async def test_ws_update_item_fail(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, sl_setup
) -> None:
"""Test failure of update shopping_list item websocket command.""" """Test failure of update shopping_list item websocket command."""
await intent.async_handle( await intent.async_handle(
hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}} hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}}
@ -318,7 +332,9 @@ async def test_ws_update_item_fail(hass, hass_ws_client, sl_setup):
assert len(events) == 0 assert len(events) == 0
async def test_deprecated_api_clear_completed(hass, hass_client, sl_setup): async def test_deprecated_api_clear_completed(
hass: HomeAssistant, hass_client: ClientSessionGenerator, sl_setup
) -> None:
"""Test the API.""" """Test the API."""
await intent.async_handle( await intent.async_handle(
@ -351,7 +367,9 @@ async def test_deprecated_api_clear_completed(hass, hass_client, sl_setup):
assert items[0] == {"id": wine_id, "name": "wine", "complete": False} assert items[0] == {"id": wine_id, "name": "wine", "complete": False}
async def test_ws_clear_items(hass, hass_ws_client, sl_setup): async def test_ws_clear_items(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, sl_setup
) -> None:
"""Test clearing shopping_list items websocket command.""" """Test clearing shopping_list items websocket command."""
await intent.async_handle( await intent.async_handle(
hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}} hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}}
@ -384,7 +402,9 @@ async def test_ws_clear_items(hass, hass_ws_client, sl_setup):
assert len(events) == 2 assert len(events) == 2
async def test_deprecated_api_create(hass, hass_client, sl_setup): async def test_deprecated_api_create(
hass: HomeAssistant, hass_client: ClientSessionGenerator, sl_setup
) -> None:
"""Test the API.""" """Test the API."""
client = await hass_client() client = await hass_client()
@ -403,7 +423,9 @@ async def test_deprecated_api_create(hass, hass_client, sl_setup):
assert items[0]["complete"] is False assert items[0]["complete"] is False
async def test_deprecated_api_create_fail(hass, hass_client, sl_setup): async def test_deprecated_api_create_fail(
hass: HomeAssistant, hass_client: ClientSessionGenerator, sl_setup
) -> None:
"""Test the API.""" """Test the API."""
client = await hass_client() client = await hass_client()
@ -415,7 +437,9 @@ async def test_deprecated_api_create_fail(hass, hass_client, sl_setup):
assert len(events) == 0 assert len(events) == 0
async def test_ws_add_item(hass, hass_ws_client, sl_setup): async def test_ws_add_item(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, sl_setup
) -> None:
"""Test adding shopping_list item websocket command.""" """Test adding shopping_list item websocket command."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
events = async_capture_events(hass, EVENT_SHOPPING_LIST_UPDATED) events = async_capture_events(hass, EVENT_SHOPPING_LIST_UPDATED)
@ -433,7 +457,9 @@ async def test_ws_add_item(hass, hass_ws_client, sl_setup):
assert items[0]["complete"] is False assert items[0]["complete"] is False
async def test_ws_add_item_fail(hass, hass_ws_client, sl_setup): async def test_ws_add_item_fail(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, sl_setup
) -> None:
"""Test adding shopping_list item failure websocket command.""" """Test adding shopping_list item failure websocket command."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
events = async_capture_events(hass, EVENT_SHOPPING_LIST_UPDATED) events = async_capture_events(hass, EVENT_SHOPPING_LIST_UPDATED)
@ -444,7 +470,9 @@ async def test_ws_add_item_fail(hass, hass_ws_client, sl_setup):
assert len(hass.data["shopping_list"].items) == 0 assert len(hass.data["shopping_list"].items) == 0
async def test_ws_remove_item(hass, hass_ws_client, sl_setup): async def test_ws_remove_item(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, sl_setup
) -> None:
"""Test removing shopping_list item websocket command.""" """Test removing shopping_list item websocket command."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
events = async_capture_events(hass, EVENT_SHOPPING_LIST_UPDATED) events = async_capture_events(hass, EVENT_SHOPPING_LIST_UPDATED)
@ -472,7 +500,9 @@ async def test_ws_remove_item(hass, hass_ws_client, sl_setup):
assert items[0]["name"] == "cheese" assert items[0]["name"] == "cheese"
async def test_ws_remove_item_fail(hass, hass_ws_client, sl_setup): async def test_ws_remove_item_fail(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, sl_setup
) -> None:
"""Test removing shopping_list item failure websocket command.""" """Test removing shopping_list item failure websocket command."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
events = async_capture_events(hass, EVENT_SHOPPING_LIST_UPDATED) events = async_capture_events(hass, EVENT_SHOPPING_LIST_UPDATED)
@ -485,7 +515,9 @@ async def test_ws_remove_item_fail(hass, hass_ws_client, sl_setup):
assert len(hass.data["shopping_list"].items) == 1 assert len(hass.data["shopping_list"].items) == 1
async def test_ws_reorder_items(hass, hass_ws_client, sl_setup): async def test_ws_reorder_items(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, sl_setup
) -> None:
"""Test reordering shopping_list items websocket command.""" """Test reordering shopping_list items websocket command."""
await intent.async_handle( await intent.async_handle(
hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}} hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}}
@ -568,7 +600,9 @@ async def test_ws_reorder_items(hass, hass_ws_client, sl_setup):
} }
async def test_ws_reorder_items_failure(hass, hass_ws_client, sl_setup): async def test_ws_reorder_items_failure(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, sl_setup
) -> None:
"""Test reordering shopping_list items websocket command.""" """Test reordering shopping_list items websocket command."""
await intent.async_handle( await intent.async_handle(
hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}} hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}}
@ -614,7 +648,7 @@ async def test_ws_reorder_items_failure(hass, hass_ws_client, sl_setup):
assert len(events) == 0 assert len(events) == 0
async def test_add_item_service(hass, sl_setup): async def test_add_item_service(hass: HomeAssistant, sl_setup) -> None:
"""Test adding shopping_list item service.""" """Test adding shopping_list item service."""
events = async_capture_events(hass, EVENT_SHOPPING_LIST_UPDATED) events = async_capture_events(hass, EVENT_SHOPPING_LIST_UPDATED)
await hass.services.async_call( await hass.services.async_call(
@ -629,7 +663,7 @@ async def test_add_item_service(hass, sl_setup):
assert len(events) == 1 assert len(events) == 1
async def test_remove_item_service(hass, sl_setup): async def test_remove_item_service(hass: HomeAssistant, sl_setup) -> None:
"""Test removing shopping_list item service.""" """Test removing shopping_list item service."""
events = async_capture_events(hass, EVENT_SHOPPING_LIST_UPDATED) events = async_capture_events(hass, EVENT_SHOPPING_LIST_UPDATED)
await hass.services.async_call( await hass.services.async_call(
@ -663,7 +697,7 @@ async def test_remove_item_service(hass, sl_setup):
assert len(events) == 3 assert len(events) == 3
async def test_clear_completed_items_service(hass, sl_setup): async def test_clear_completed_items_service(hass: HomeAssistant, sl_setup) -> None:
"""Test clearing completed shopping_list items service.""" """Test clearing completed shopping_list items service."""
events = async_capture_events(hass, EVENT_SHOPPING_LIST_UPDATED) events = async_capture_events(hass, EVENT_SHOPPING_LIST_UPDATED)
await hass.services.async_call( await hass.services.async_call(

View File

@ -1,8 +1,9 @@
"""Test Shopping List intents.""" """Test Shopping List intents."""
from homeassistant.core import HomeAssistant
from homeassistant.helpers import intent from homeassistant.helpers import intent
async def test_recent_items_intent(hass, sl_setup): async def test_recent_items_intent(hass: HomeAssistant, sl_setup) -> None:
"""Test recent items.""" """Test recent items."""
await intent.async_handle( await intent.async_handle(
hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}} hass, "test", "HassShoppingListAddItem", {"item": {"value": "beer"}}
@ -22,7 +23,7 @@ async def test_recent_items_intent(hass, sl_setup):
) )
async def test_recent_items_intent_no_items(hass, sl_setup): async def test_recent_items_intent_no_items(hass: HomeAssistant, sl_setup) -> None:
"""Test recent items.""" """Test recent items."""
response = await intent.async_handle(hass, "test", "HassShoppingListLastItems") response = await intent.async_handle(hass, "test", "HassShoppingListLastItems")

View File

@ -145,21 +145,23 @@ async def setup_sia(hass, config_entry: MockConfigEntry):
await hass.async_block_till_done() await hass.async_block_till_done()
async def test_form_start_user(hass, flow_at_user_step): async def test_form_start_user(hass: HomeAssistant, flow_at_user_step) -> None:
"""Start the form and check if you get the right id and schema for the user step.""" """Start the form and check if you get the right id and schema for the user step."""
assert flow_at_user_step["step_id"] == "user" assert flow_at_user_step["step_id"] == "user"
assert flow_at_user_step["errors"] is None assert flow_at_user_step["errors"] is None
assert flow_at_user_step["data_schema"] == HUB_SCHEMA assert flow_at_user_step["data_schema"] == HUB_SCHEMA
async def test_form_start_account(hass, flow_at_add_account_step): async def test_form_start_account(
hass: HomeAssistant, flow_at_add_account_step
) -> None:
"""Start the form and check if you get the right id and schema for the additional account step.""" """Start the form and check if you get the right id and schema for the additional account step."""
assert flow_at_add_account_step["step_id"] == "add_account" assert flow_at_add_account_step["step_id"] == "add_account"
assert flow_at_add_account_step["errors"] is None assert flow_at_add_account_step["errors"] is None
assert flow_at_add_account_step["data_schema"] == ACCOUNT_SCHEMA assert flow_at_add_account_step["data_schema"] == ACCOUNT_SCHEMA
async def test_create(hass, entry_with_basic_config): async def test_create(hass: HomeAssistant, entry_with_basic_config) -> None:
"""Test we create a entry through the form.""" """Test we create a entry through the form."""
assert ( assert (
entry_with_basic_config["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY entry_with_basic_config["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
@ -172,7 +174,9 @@ async def test_create(hass, entry_with_basic_config):
assert entry_with_basic_config["options"] == BASE_OUT["options"] assert entry_with_basic_config["options"] == BASE_OUT["options"]
async def test_create_additional_account(hass, entry_with_additional_account_config): async def test_create_additional_account(
hass: HomeAssistant, entry_with_additional_account_config
) -> None:
"""Test we create a config with two accounts.""" """Test we create a config with two accounts."""
assert ( assert (
entry_with_additional_account_config["type"] entry_with_additional_account_config["type"]
@ -227,12 +231,12 @@ def mock_sia():
], ],
) )
async def test_validation_errors_user( async def test_validation_errors_user(
hass, hass: HomeAssistant,
flow_at_user_step, flow_at_user_step,
field, field,
value, value,
error, error,
): ) -> None:
"""Test we handle the different invalid inputs, in the user flow.""" """Test we handle the different invalid inputs, in the user flow."""
config = BASIC_CONFIG.copy() config = BASIC_CONFIG.copy()
flow_id = flow_at_user_step["flow_id"] flow_id = flow_at_user_step["flow_id"]
@ -254,12 +258,12 @@ async def test_validation_errors_user(
], ],
) )
async def test_validation_errors_account( async def test_validation_errors_account(
hass, hass: HomeAssistant,
flow_at_user_step, flow_at_user_step,
field, field,
value, value,
error, error,
): ) -> None:
"""Test we handle the different invalid inputs, in the add_account flow.""" """Test we handle the different invalid inputs, in the add_account flow."""
flow_at_add_account_step = await hass.config_entries.flow.async_configure( flow_at_add_account_step = await hass.config_entries.flow.async_configure(
flow_at_user_step["flow_id"], BASIC_CONFIG_ADDITIONAL flow_at_user_step["flow_id"], BASIC_CONFIG_ADDITIONAL
@ -272,7 +276,7 @@ async def test_validation_errors_account(
assert result_err["errors"] == {"base": error} assert result_err["errors"] == {"base": error}
async def test_unknown_user(hass, flow_at_user_step): async def test_unknown_user(hass: HomeAssistant, flow_at_user_step) -> None:
"""Test unknown exceptions.""" """Test unknown exceptions."""
flow_id = flow_at_user_step["flow_id"] flow_id = flow_at_user_step["flow_id"]
with patch( with patch(
@ -287,7 +291,7 @@ async def test_unknown_user(hass, flow_at_user_step):
assert result_err["data_schema"] == HUB_SCHEMA assert result_err["data_schema"] == HUB_SCHEMA
async def test_unknown_account(hass, flow_at_user_step): async def test_unknown_account(hass: HomeAssistant, flow_at_user_step) -> None:
"""Test unknown exceptions.""" """Test unknown exceptions."""
flow_at_add_account_step = await hass.config_entries.flow.async_configure( flow_at_add_account_step = await hass.config_entries.flow.async_configure(
flow_at_user_step["flow_id"], BASIC_CONFIG_ADDITIONAL flow_at_user_step["flow_id"], BASIC_CONFIG_ADDITIONAL

View File

@ -95,14 +95,14 @@ async def test_bad_api_key(
assert not hass.states.get(VALID_ENTITY_ID) assert not hass.states.get(VALID_ENTITY_ID)
async def test_setup_platform(hass, mock_detections): async def test_setup_platform(hass: HomeAssistant, mock_detections) -> None:
"""Set up platform with one entity.""" """Set up platform with one entity."""
await async_setup_component(hass, ip.DOMAIN, VALID_CONFIG) await async_setup_component(hass, ip.DOMAIN, VALID_CONFIG)
await hass.async_block_till_done() await hass.async_block_till_done()
assert hass.states.get(VALID_ENTITY_ID) assert hass.states.get(VALID_ENTITY_ID)
async def test_process_image(hass, mock_image, mock_detections): async def test_process_image(hass: HomeAssistant, mock_image, mock_detections) -> None:
"""Process an image.""" """Process an image."""
await async_setup_component(hass, ip.DOMAIN, VALID_CONFIG) await async_setup_component(hass, ip.DOMAIN, VALID_CONFIG)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -127,8 +127,12 @@ async def test_process_image(hass, mock_image, mock_detections):
async def test_catch_bad_image( async def test_catch_bad_image(
hass, caplog, mock_image, mock_detections, mock_bad_image_data hass: HomeAssistant,
): caplog: pytest.LogCaptureFixture,
mock_image,
mock_detections,
mock_bad_image_data,
) -> None:
"""Process an image.""" """Process an image."""
valid_config_save_file = deepcopy(VALID_CONFIG) valid_config_save_file = deepcopy(VALID_CONFIG)
valid_config_save_file[ip.DOMAIN].update({sh.CONF_SAVE_FILE_FOLDER: TEST_DIR}) valid_config_save_file[ip.DOMAIN].update({sh.CONF_SAVE_FILE_FOLDER: TEST_DIR})
@ -142,7 +146,7 @@ async def test_catch_bad_image(
assert "Sighthound unable to process image" in caplog.text assert "Sighthound unable to process image" in caplog.text
async def test_save_image(hass, mock_image, mock_detections): async def test_save_image(hass: HomeAssistant, mock_image, mock_detections) -> None:
"""Save a processed image.""" """Save a processed image."""
valid_config_save_file = deepcopy(VALID_CONFIG) valid_config_save_file = deepcopy(VALID_CONFIG)
valid_config_save_file[ip.DOMAIN].update({sh.CONF_SAVE_FILE_FOLDER: TEST_DIR}) valid_config_save_file[ip.DOMAIN].update({sh.CONF_SAVE_FILE_FOLDER: TEST_DIR})
@ -167,7 +171,9 @@ async def test_save_image(hass, mock_image, mock_detections):
assert pil_img.save.call_args_list[0] == mock.call(latest_save_path) assert pil_img.save.call_args_list[0] == mock.call(latest_save_path)
async def test_save_timestamped_image(hass, mock_image, mock_detections, mock_now): async def test_save_timestamped_image(
hass: HomeAssistant, mock_image, mock_detections, mock_now
) -> None:
"""Save a processed image.""" """Save a processed image."""
valid_config_save_ts_file = deepcopy(VALID_CONFIG) valid_config_save_ts_file = deepcopy(VALID_CONFIG)
valid_config_save_ts_file[ip.DOMAIN].update({sh.CONF_SAVE_FILE_FOLDER: TEST_DIR}) valid_config_save_ts_file[ip.DOMAIN].update({sh.CONF_SAVE_FILE_FOLDER: TEST_DIR})