Add type hints to integration tests (part 20) (#88179)

This commit is contained in:
epenet 2023-02-15 15:23:34 +01:00 committed by GitHub
parent 793e51ac76
commit 3a9adacdde
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
55 changed files with 537 additions and 292 deletions

View file

@ -15,7 +15,9 @@ from homeassistant.data_entry_flow import FlowResultType
VALID_AUTH_CODE = "code12345123451234512345123451234512345123451" VALID_AUTH_CODE = "code12345123451234512345123451234512345123451"
async def test_duplicate_error(config_entry, hass, setup_simplisafe): async def test_duplicate_error(
config_entry, hass: HomeAssistant, setup_simplisafe
) -> None:
"""Test that errors are shown when duplicates are added.""" """Test that errors are shown when duplicates are added."""
with patch( with patch(
"homeassistant.components.simplisafe.async_setup_entry", return_value=True "homeassistant.components.simplisafe.async_setup_entry", return_value=True
@ -68,7 +70,7 @@ async def test_invalid_credentials(hass: HomeAssistant) -> None:
assert result["errors"] == {CONF_AUTH_CODE: "invalid_auth"} assert result["errors"] == {CONF_AUTH_CODE: "invalid_auth"}
async def test_options_flow(config_entry, hass): async def test_options_flow(config_entry, hass: HomeAssistant) -> None:
"""Test config flow options.""" """Test config flow options."""
with patch( with patch(
"homeassistant.components.simplisafe.async_setup_entry", return_value=True "homeassistant.components.simplisafe.async_setup_entry", return_value=True
@ -87,7 +89,7 @@ async def test_options_flow(config_entry, hass):
assert config_entry.options == {CONF_CODE: "4321"} assert config_entry.options == {CONF_CODE: "4321"}
async def test_step_reauth(config_entry, hass, setup_simplisafe): async def test_step_reauth(config_entry, hass: HomeAssistant, setup_simplisafe) -> None:
"""Test the re-auth step.""" """Test the re-auth step."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,
@ -111,7 +113,9 @@ async def test_step_reauth(config_entry, hass, setup_simplisafe):
@pytest.mark.parametrize("unique_id", ["some_other_id"]) @pytest.mark.parametrize("unique_id", ["some_other_id"])
async def test_step_reauth_wrong_account(config_entry, hass, setup_simplisafe): async def test_step_reauth_wrong_account(
config_entry, hass: HomeAssistant, setup_simplisafe
) -> None:
"""Test the re-auth step where the wrong account is used during login.""" """Test the re-auth step where the wrong account is used during login."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,
@ -143,7 +147,13 @@ async def test_step_reauth_wrong_account(config_entry, hass, setup_simplisafe):
), ),
], ],
) )
async def test_step_user(auth_code, caplog, hass, log_statement, setup_simplisafe): async def test_step_user(
auth_code,
caplog: pytest.LogCaptureFixture,
hass: HomeAssistant,
log_statement,
setup_simplisafe,
) -> None:
"""Test successfully completion of the user step.""" """Test successfully completion of the user step."""
caplog.set_level = logging.DEBUG caplog.set_level = logging.DEBUG
@ -168,7 +178,7 @@ async def test_step_user(auth_code, caplog, hass, log_statement, setup_simplisaf
assert config_entry.data == {CONF_USERNAME: "12345", CONF_TOKEN: "token123"} assert config_entry.data == {CONF_USERNAME: "12345", CONF_TOKEN: "token123"}
async def test_unknown_error(hass, setup_simplisafe): async def test_unknown_error(hass: HomeAssistant, setup_simplisafe) -> None:
"""Test that an unknown error shows ohe correct error.""" """Test that an unknown error shows ohe correct error."""
with patch( with patch(
"homeassistant.components.simplisafe.config_flow.API.async_from_auth", "homeassistant.components.simplisafe.config_flow.API.async_from_auth",

View file

@ -1,10 +1,17 @@
"""Test SimpliSafe diagnostics.""" """Test SimpliSafe diagnostics."""
from homeassistant.components.diagnostics import REDACTED from homeassistant.components.diagnostics import REDACTED
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
async def test_entry_diagnostics(hass, config_entry, hass_client, setup_simplisafe): async def test_entry_diagnostics(
hass: HomeAssistant,
config_entry,
hass_client: ClientSessionGenerator,
setup_simplisafe,
) -> None:
"""Test config entry diagnostics.""" """Test config entry diagnostics."""
assert await get_diagnostics_for_config_entry(hass, hass_client, config_entry) == { assert await get_diagnostics_for_config_entry(hass, hass_client, config_entry) == {
"entry": { "entry": {

View file

@ -2,11 +2,14 @@
from unittest.mock import patch from unittest.mock import patch
from homeassistant.components.simplisafe import DOMAIN from homeassistant.components.simplisafe import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr from homeassistant.helpers import device_registry as dr
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
async def test_base_station_migration(hass, api, config, config_entry): async def test_base_station_migration(
hass: HomeAssistant, api, config, config_entry
) -> None:
"""Test that errors are shown when duplicates are added.""" """Test that errors are shown when duplicates are added."""
old_identifers = (DOMAIN, 12345) old_identifers = (DOMAIN, 12345)
new_identifiers = (DOMAIN, "12345") new_identifiers = (DOMAIN, "12345")

View file

@ -4,11 +4,12 @@ from __future__ import annotations
from datetime import timedelta from datetime import timedelta
from homeassistant.components import siren from homeassistant.components import siren
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.siren import ATTR_AVAILABLE_TONES from homeassistant.components.siren import ATTR_AVAILABLE_TONES
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 siren registered attributes to be excluded.""" """Test siren registered attributes to be excluded."""
await async_setup_component( await async_setup_component(
hass, siren.DOMAIN, {siren.DOMAIN: {"platform": "demo"}} hass, siren.DOMAIN, {siren.DOMAIN: {"platform": "demo"}}

View file

@ -7,6 +7,7 @@ from homeassistant.const import (
STATE_OFF, STATE_OFF,
STATE_ON, STATE_ON,
) )
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from .conftest import ( from .conftest import (
@ -22,7 +23,7 @@ from .conftest import (
) )
async def test_binary_sensors(hass, mock_asyncsleepiq): async def test_binary_sensors(hass: HomeAssistant, mock_asyncsleepiq) -> None:
"""Test the SleepIQ binary sensors.""" """Test the SleepIQ binary sensors."""
await setup_platform(hass, DOMAIN) await setup_platform(hass, DOMAIN)
entity_registry = er.async_get(hass) entity_registry = er.async_get(hass)

View file

@ -1,12 +1,13 @@
"""The tests for SleepIQ binary sensor platform.""" """The tests for SleepIQ binary sensor platform."""
from homeassistant.components.button import DOMAIN from homeassistant.components.button import DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME from homeassistant.const import ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from .conftest import BED_ID, BED_NAME, BED_NAME_LOWER, setup_platform from .conftest import BED_ID, BED_NAME, BED_NAME_LOWER, setup_platform
async def test_button_calibrate(hass, mock_asyncsleepiq): async def test_button_calibrate(hass: HomeAssistant, mock_asyncsleepiq) -> None:
"""Test the SleepIQ calibrate button.""" """Test the SleepIQ calibrate button."""
await setup_platform(hass, DOMAIN) await setup_platform(hass, DOMAIN)
entity_registry = er.async_get(hass) entity_registry = er.async_get(hass)
@ -31,7 +32,7 @@ async def test_button_calibrate(hass, mock_asyncsleepiq):
mock_asyncsleepiq.beds[BED_ID].calibrate.assert_called_once() mock_asyncsleepiq.beds[BED_ID].calibrate.assert_called_once()
async def test_button_stop_pump(hass, mock_asyncsleepiq): async def test_button_stop_pump(hass: HomeAssistant, mock_asyncsleepiq) -> None:
"""Test the SleepIQ stop pump button.""" """Test the SleepIQ stop pump button."""
await setup_platform(hass, DOMAIN) await setup_platform(hass, DOMAIN)
entity_registry = er.async_get(hass) entity_registry = er.async_get(hass)

View file

@ -2,6 +2,7 @@
from homeassistant.components.light import DOMAIN from homeassistant.components.light import DOMAIN
from homeassistant.components.sleepiq.coordinator import LONGER_UPDATE_INTERVAL from homeassistant.components.sleepiq.coordinator import LONGER_UPDATE_INTERVAL
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from homeassistant.util.dt import utcnow from homeassistant.util.dt import utcnow
@ -10,7 +11,7 @@ from .conftest import BED_ID, BED_NAME, BED_NAME_LOWER, setup_platform
from tests.common import async_fire_time_changed from tests.common import async_fire_time_changed
async def test_setup(hass, mock_asyncsleepiq): async def test_setup(hass: HomeAssistant, mock_asyncsleepiq) -> None:
"""Test for successfully setting up the SleepIQ platform.""" """Test for successfully setting up the SleepIQ platform."""
entry = await setup_platform(hass, DOMAIN) entry = await setup_platform(hass, DOMAIN)
entity_registry = er.async_get(hass) entity_registry = er.async_get(hass)
@ -28,7 +29,7 @@ async def test_setup(hass, mock_asyncsleepiq):
assert entry.unique_id == f"{BED_ID}-light-2" assert entry.unique_id == f"{BED_ID}-light-2"
async def test_light_set_states(hass, mock_asyncsleepiq): async def test_light_set_states(hass: HomeAssistant, mock_asyncsleepiq) -> None:
"""Test light change.""" """Test light change."""
await setup_platform(hass, DOMAIN) await setup_platform(hass, DOMAIN)
@ -51,7 +52,7 @@ async def test_light_set_states(hass, mock_asyncsleepiq):
mock_asyncsleepiq.beds[BED_ID].foundation.lights[0].turn_off.assert_called_once() mock_asyncsleepiq.beds[BED_ID].foundation.lights[0].turn_off.assert_called_once()
async def test_switch_get_states(hass, mock_asyncsleepiq): async def test_switch_get_states(hass: HomeAssistant, mock_asyncsleepiq) -> None:
"""Test light update.""" """Test light update."""
await setup_platform(hass, DOMAIN) await setup_platform(hass, DOMAIN)

View file

@ -8,6 +8,7 @@ from homeassistant.components.number import (
SERVICE_SET_VALUE, SERVICE_SET_VALUE,
) )
from homeassistant.const import ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, ATTR_ICON from homeassistant.const import ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, ATTR_ICON
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from .conftest import ( from .conftest import (
@ -24,7 +25,7 @@ from .conftest import (
) )
async def test_firmness(hass, mock_asyncsleepiq): async def test_firmness(hass: HomeAssistant, mock_asyncsleepiq) -> None:
"""Test the SleepIQ firmness number values for a bed with two sides.""" """Test the SleepIQ firmness number values for a bed with two sides."""
entry = await setup_platform(hass, DOMAIN) entry = await setup_platform(hass, DOMAIN)
entity_registry = er.async_get(hass) entity_registry = er.async_get(hass)
@ -82,7 +83,7 @@ async def test_firmness(hass, mock_asyncsleepiq):
mock_asyncsleepiq.beds[BED_ID].sleepers[0].set_sleepnumber.assert_called_with(42) mock_asyncsleepiq.beds[BED_ID].sleepers[0].set_sleepnumber.assert_called_with(42)
async def test_actuators(hass, mock_asyncsleepiq): async def test_actuators(hass: HomeAssistant, mock_asyncsleepiq) -> None:
"""Test the SleepIQ actuator position values for a bed with adjustable head and foot.""" """Test the SleepIQ actuator position values for a bed with adjustable head and foot."""
entry = await setup_platform(hass, DOMAIN) entry = await setup_platform(hass, DOMAIN)
entity_registry = er.async_get(hass) entity_registry = er.async_get(hass)

View file

@ -1,6 +1,7 @@
"""The tests for SleepIQ sensor platform.""" """The tests for SleepIQ sensor platform."""
from homeassistant.components.sensor import DOMAIN from homeassistant.components.sensor import DOMAIN
from homeassistant.const import ATTR_FRIENDLY_NAME, ATTR_ICON from homeassistant.const import ATTR_FRIENDLY_NAME, ATTR_ICON
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from .conftest import ( from .conftest import (
@ -16,7 +17,7 @@ from .conftest import (
) )
async def test_sleepnumber_sensors(hass, mock_asyncsleepiq): async def test_sleepnumber_sensors(hass: HomeAssistant, mock_asyncsleepiq) -> None:
"""Test the SleepIQ sleepnumber for a bed with two sides.""" """Test the SleepIQ sleepnumber for a bed with two sides."""
entry = await setup_platform(hass, DOMAIN) entry = await setup_platform(hass, DOMAIN)
entity_registry = er.async_get(hass) entity_registry = er.async_get(hass)
@ -54,7 +55,7 @@ async def test_sleepnumber_sensors(hass, mock_asyncsleepiq):
assert entry.unique_id == f"{SLEEPER_R_ID}_sleep_number" assert entry.unique_id == f"{SLEEPER_R_ID}_sleep_number"
async def test_pressure_sensors(hass, mock_asyncsleepiq): async def test_pressure_sensors(hass: HomeAssistant, mock_asyncsleepiq) -> None:
"""Test the SleepIQ pressure for a bed with two sides.""" """Test the SleepIQ pressure for a bed with two sides."""
entry = await setup_platform(hass, DOMAIN) entry = await setup_platform(hass, DOMAIN)
entity_registry = er.async_get(hass) entity_registry = er.async_get(hass)

View file

@ -2,6 +2,7 @@
from homeassistant.components.sleepiq.coordinator import LONGER_UPDATE_INTERVAL from homeassistant.components.sleepiq.coordinator import LONGER_UPDATE_INTERVAL
from homeassistant.components.switch import DOMAIN from homeassistant.components.switch import DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from homeassistant.util.dt import utcnow from homeassistant.util.dt import utcnow
@ -10,7 +11,7 @@ from .conftest import BED_ID, BED_NAME, BED_NAME_LOWER, setup_platform
from tests.common import async_fire_time_changed from tests.common import async_fire_time_changed
async def test_setup(hass, mock_asyncsleepiq): async def test_setup(hass: HomeAssistant, mock_asyncsleepiq) -> None:
"""Test for successfully setting up the SleepIQ platform.""" """Test for successfully setting up the SleepIQ platform."""
entry = await setup_platform(hass, DOMAIN) entry = await setup_platform(hass, DOMAIN)
entity_registry = er.async_get(hass) entity_registry = er.async_get(hass)
@ -23,7 +24,7 @@ async def test_setup(hass, mock_asyncsleepiq):
assert entry.unique_id == f"{BED_ID}-pause-mode" assert entry.unique_id == f"{BED_ID}-pause-mode"
async def test_switch_set_states(hass, mock_asyncsleepiq): async def test_switch_set_states(hass: HomeAssistant, mock_asyncsleepiq) -> None:
"""Test button press.""" """Test button press."""
await setup_platform(hass, DOMAIN) await setup_platform(hass, DOMAIN)
@ -46,7 +47,7 @@ async def test_switch_set_states(hass, mock_asyncsleepiq):
mock_asyncsleepiq.beds[BED_ID].set_pause_mode.assert_called_with(True) mock_asyncsleepiq.beds[BED_ID].set_pause_mode.assert_called_with(True)
async def test_switch_get_states(hass, mock_asyncsleepiq): async def test_switch_get_states(hass: HomeAssistant, mock_asyncsleepiq) -> None:
"""Test button press.""" """Test button press."""
await setup_platform(hass, DOMAIN) await setup_platform(hass, DOMAIN)

View file

@ -116,7 +116,7 @@ async def test_form_unexpected_exception(hass: HomeAssistant) -> None:
assert len(mock_setup_entry.mock_calls) == 0 assert len(mock_setup_entry.mock_calls) == 0
async def test_form_already_configured(hass, mock_config_entry): async def test_form_already_configured(hass: HomeAssistant, mock_config_entry) -> None:
"""Test starting a flow by user when already configured.""" """Test starting a flow by user when already configured."""
mock_config_entry.add_to_hass(hass) mock_config_entry.add_to_hass(hass)

View file

@ -1,8 +1,9 @@
"""Test the sma sensor platform.""" """Test the sma sensor platform."""
from homeassistant.const import ATTR_UNIT_OF_MEASUREMENT, UnitOfPower from homeassistant.const import ATTR_UNIT_OF_MEASUREMENT, UnitOfPower
from homeassistant.core import HomeAssistant
async def test_sensors(hass, init_integration): async def test_sensors(hass: HomeAssistant, init_integration) -> None:
"""Test states of the sensors.""" """Test states of the sensors."""
state = hass.states.get("sensor.sma_device_grid_power") state = hass.states.get("sensor.sma_device_grid_power")
assert state assert state

View file

@ -17,6 +17,8 @@ from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_entry_oauth2_flow from homeassistant.helpers import config_entry_oauth2_flow
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import ClientSessionGenerator
CLIENT_ID = "1234" CLIENT_ID = "1234"
CLIENT_SECRET = "5678" CLIENT_SECRET = "5678"
@ -407,8 +409,11 @@ async def test_abort_cloud_flow_if_local_device_exists(hass: HomeAssistant) -> N
async def test_full_user_flow( async def test_full_user_flow(
hass, hass_client_no_auth, aioclient_mock, current_request_with_host hass: HomeAssistant,
): hass_client_no_auth: ClientSessionGenerator,
aioclient_mock: AiohttpClientMocker,
current_request_with_host: None,
) -> None:
"""Check full flow.""" """Check full flow."""
assert await setup.async_setup_component( assert await setup.async_setup_component(
hass, hass,

View file

@ -65,7 +65,7 @@ async def test_form_invalid_auth(hass: HomeAssistant) -> None:
@pytest.mark.parametrize( @pytest.mark.parametrize(
"side_effect", [asyncio.TimeoutError, ClientError, SmartMeterTexasAPIError] "side_effect", [asyncio.TimeoutError, ClientError, SmartMeterTexasAPIError]
) )
async def test_form_cannot_connect(hass, side_effect): async def test_form_cannot_connect(hass: HomeAssistant, side_effect) -> None:
"""Test we handle cannot connect error.""" """Test we handle cannot connect error."""
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}

View file

@ -13,6 +13,8 @@ from homeassistant.setup import async_setup_component
from .conftest import TEST_ENTITY_ID, setup_integration from .conftest import TEST_ENTITY_ID, setup_integration
from tests.test_util.aiohttp import AiohttpClientMocker
async def test_setup_with_no_config(hass: HomeAssistant) -> None: async def test_setup_with_no_config(hass: HomeAssistant) -> None:
"""Test that no config is successful.""" """Test that no config is successful."""
@ -23,21 +25,27 @@ async def test_setup_with_no_config(hass: HomeAssistant) -> None:
assert len(hass.config_entries.flow.async_progress()) == 0 assert len(hass.config_entries.flow.async_progress()) == 0
async def test_auth_failure(hass, config_entry, aioclient_mock): async def test_auth_failure(
hass: HomeAssistant, config_entry, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test if user's username or password is not accepted.""" """Test if user's username or password is not accepted."""
await setup_integration(hass, config_entry, aioclient_mock, auth_fail=True) await setup_integration(hass, config_entry, aioclient_mock, auth_fail=True)
assert config_entry.state is ConfigEntryState.SETUP_ERROR assert config_entry.state is ConfigEntryState.SETUP_ERROR
async def test_api_timeout(hass, config_entry, aioclient_mock): async def test_api_timeout(
hass: HomeAssistant, config_entry, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test that a timeout results in ConfigEntryNotReady.""" """Test that a timeout results in ConfigEntryNotReady."""
await setup_integration(hass, config_entry, aioclient_mock, auth_timeout=True) await setup_integration(hass, config_entry, aioclient_mock, auth_timeout=True)
assert config_entry.state is ConfigEntryState.SETUP_RETRY assert config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_update_failure(hass, config_entry, aioclient_mock): async def test_update_failure(
hass: HomeAssistant, config_entry, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test that the coordinator handles a bad response.""" """Test that the coordinator handles a bad response."""
await setup_integration(hass, config_entry, aioclient_mock, bad_reading=True) await setup_integration(hass, config_entry, aioclient_mock, bad_reading=True)
await async_setup_component(hass, HA_DOMAIN, {}) await async_setup_component(hass, HA_DOMAIN, {})
@ -53,7 +61,9 @@ async def test_update_failure(hass, config_entry, aioclient_mock):
updater.assert_called_once() updater.assert_called_once()
async def test_unload_config_entry(hass, config_entry, aioclient_mock): async def test_unload_config_entry(
hass: HomeAssistant, config_entry, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test entry unloading.""" """Test entry unloading."""
await setup_integration(hass, config_entry, aioclient_mock) await setup_integration(hass, config_entry, aioclient_mock)

View file

@ -11,12 +11,17 @@ from homeassistant.components.smart_meter_texas.const import (
METER_NUMBER, METER_NUMBER,
) )
from homeassistant.const import ATTR_ENTITY_ID, CONF_ADDRESS from homeassistant.const import ATTR_ENTITY_ID, CONF_ADDRESS
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from .conftest import TEST_ENTITY_ID, refresh_data, setup_integration from .conftest import TEST_ENTITY_ID, refresh_data, setup_integration
from tests.test_util.aiohttp import AiohttpClientMocker
async def test_sensor(hass, config_entry, aioclient_mock):
async def test_sensor(
hass: HomeAssistant, config_entry, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test that the sensor is setup.""" """Test that the sensor is setup."""
await setup_integration(hass, config_entry, aioclient_mock) await setup_integration(hass, config_entry, aioclient_mock)
await refresh_data(hass, config_entry, aioclient_mock) await refresh_data(hass, config_entry, aioclient_mock)
@ -26,7 +31,9 @@ async def test_sensor(hass, config_entry, aioclient_mock):
assert meter.state == "9751.212" assert meter.state == "9751.212"
async def test_name(hass, config_entry, aioclient_mock): async def test_name(
hass: HomeAssistant, config_entry, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test sensor name property.""" """Test sensor name property."""
await setup_integration(hass, config_entry, aioclient_mock) await setup_integration(hass, config_entry, aioclient_mock)
await refresh_data(hass, config_entry, aioclient_mock) await refresh_data(hass, config_entry, aioclient_mock)
@ -35,7 +42,9 @@ async def test_name(hass, config_entry, aioclient_mock):
assert meter.name == f"{ELECTRIC_METER} 123456789" assert meter.name == f"{ELECTRIC_METER} 123456789"
async def test_attributes(hass, config_entry, aioclient_mock): async def test_attributes(
hass: HomeAssistant, config_entry, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test meter attributes.""" """Test meter attributes."""
await setup_integration(hass, config_entry, aioclient_mock) await setup_integration(hass, config_entry, aioclient_mock)
await refresh_data(hass, config_entry, aioclient_mock) await refresh_data(hass, config_entry, aioclient_mock)
@ -46,7 +55,9 @@ async def test_attributes(hass, config_entry, aioclient_mock):
assert meter.attributes[CONF_ADDRESS] == "123 MAIN ST" assert meter.attributes[CONF_ADDRESS] == "123 MAIN ST"
async def test_generic_entity_update_service(hass, config_entry, aioclient_mock): async def test_generic_entity_update_service(
hass: HomeAssistant, config_entry, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test generic update entity service homeasasistant/update_entity.""" """Test generic update entity service homeasasistant/update_entity."""
await setup_integration(hass, config_entry, aioclient_mock) await setup_integration(hass, config_entry, aioclient_mock)
await async_setup_component(hass, HA_DOMAIN, {}) await async_setup_component(hass, HA_DOMAIN, {})

View file

@ -13,6 +13,7 @@ from homeassistant.components.smartthings import binary_sensor
from homeassistant.components.smartthings.const import DOMAIN, SIGNAL_SMARTTHINGS_UPDATE from homeassistant.components.smartthings.const import DOMAIN, SIGNAL_SMARTTHINGS_UPDATE
from homeassistant.config_entries import ConfigEntryState from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import ATTR_FRIENDLY_NAME, STATE_UNAVAILABLE, EntityCategory from homeassistant.const import ATTR_FRIENDLY_NAME, STATE_UNAVAILABLE, EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.dispatcher import async_dispatcher_send
@ -33,7 +34,7 @@ async def test_mapping_integrity() -> None:
assert device_class in DEVICE_CLASSES, device_class assert device_class in DEVICE_CLASSES, device_class
async def test_entity_state(hass, device_factory): async def test_entity_state(hass: HomeAssistant, device_factory) -> None:
"""Tests the state attributes properly match the light types.""" """Tests the state attributes properly match the light types."""
device = device_factory( device = device_factory(
"Motion Sensor 1", [Capability.motion_sensor], {Attribute.motion: "inactive"} "Motion Sensor 1", [Capability.motion_sensor], {Attribute.motion: "inactive"}
@ -44,7 +45,9 @@ async def test_entity_state(hass, device_factory):
assert state.attributes[ATTR_FRIENDLY_NAME] == f"{device.label} {Attribute.motion}" assert state.attributes[ATTR_FRIENDLY_NAME] == f"{device.label} {Attribute.motion}"
async def test_entity_and_device_attributes(hass, device_factory): async def test_entity_and_device_attributes(
hass: HomeAssistant, device_factory
) -> None:
"""Test the attributes of the entity are correct.""" """Test the attributes of the entity are correct."""
# Arrange # Arrange
device = device_factory( device = device_factory(
@ -67,7 +70,7 @@ async def test_entity_and_device_attributes(hass, device_factory):
assert entry.manufacturer == "Unavailable" assert entry.manufacturer == "Unavailable"
async def test_update_from_signal(hass, device_factory): async def test_update_from_signal(hass: HomeAssistant, device_factory) -> None:
"""Test the binary_sensor updates when receiving a signal.""" """Test the binary_sensor updates when receiving a signal."""
# Arrange # Arrange
device = device_factory( device = device_factory(
@ -86,7 +89,7 @@ async def test_update_from_signal(hass, device_factory):
assert state.state == "on" assert state.state == "on"
async def test_unload_config_entry(hass, device_factory): async def test_unload_config_entry(hass: HomeAssistant, device_factory) -> None:
"""Test the binary_sensor is removed when the config entry is unloaded.""" """Test the binary_sensor is removed when the config entry is unloaded."""
# Arrange # Arrange
device = device_factory( device = device_factory(
@ -103,7 +106,7 @@ async def test_unload_config_entry(hass, device_factory):
) )
async def test_entity_category(hass, device_factory): async def test_entity_category(hass: HomeAssistant, device_factory) -> None:
"""Tests the state attributes properly match the light types.""" """Tests the state attributes properly match the light types."""
device1 = device_factory( device1 = device_factory(
"Motion Sensor 1", [Capability.motion_sensor], {Attribute.motion: "inactive"} "Motion Sensor 1", [Capability.motion_sensor], {Attribute.motion: "inactive"}

View file

@ -35,6 +35,7 @@ from homeassistant.const import (
SERVICE_TURN_ON, SERVICE_TURN_ON,
STATE_UNKNOWN, STATE_UNKNOWN,
) )
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers import device_registry as dr, entity_registry as er
from .conftest import setup_platform from .conftest import setup_platform
@ -183,7 +184,9 @@ def air_conditioner_fixture(device_factory):
return device return device
async def test_legacy_thermostat_entity_state(hass, legacy_thermostat): async def test_legacy_thermostat_entity_state(
hass: HomeAssistant, legacy_thermostat
) -> None:
"""Tests the state attributes properly match the thermostat type.""" """Tests the state attributes properly match the thermostat type."""
await setup_platform(hass, CLIMATE_DOMAIN, devices=[legacy_thermostat]) await setup_platform(hass, CLIMATE_DOMAIN, devices=[legacy_thermostat])
state = hass.states.get("climate.legacy_thermostat") state = hass.states.get("climate.legacy_thermostat")
@ -209,7 +212,9 @@ async def test_legacy_thermostat_entity_state(hass, legacy_thermostat):
assert state.attributes[ATTR_CURRENT_TEMPERATURE] == 21.1 # celsius assert state.attributes[ATTR_CURRENT_TEMPERATURE] == 21.1 # celsius
async def test_basic_thermostat_entity_state(hass, basic_thermostat): async def test_basic_thermostat_entity_state(
hass: HomeAssistant, basic_thermostat
) -> None:
"""Tests the state attributes properly match the thermostat type.""" """Tests the state attributes properly match the thermostat type."""
await setup_platform(hass, CLIMATE_DOMAIN, devices=[basic_thermostat]) await setup_platform(hass, CLIMATE_DOMAIN, devices=[basic_thermostat])
state = hass.states.get("climate.basic_thermostat") state = hass.states.get("climate.basic_thermostat")
@ -229,7 +234,7 @@ async def test_basic_thermostat_entity_state(hass, basic_thermostat):
assert state.attributes[ATTR_CURRENT_TEMPERATURE] == 21.1 # celsius assert state.attributes[ATTR_CURRENT_TEMPERATURE] == 21.1 # celsius
async def test_thermostat_entity_state(hass, thermostat): async def test_thermostat_entity_state(hass: HomeAssistant, thermostat) -> None:
"""Tests the state attributes properly match the thermostat type.""" """Tests the state attributes properly match the thermostat type."""
await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat]) await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat])
state = hass.states.get("climate.thermostat") state = hass.states.get("climate.thermostat")
@ -255,7 +260,9 @@ async def test_thermostat_entity_state(hass, thermostat):
assert state.attributes[ATTR_CURRENT_HUMIDITY] == 34 assert state.attributes[ATTR_CURRENT_HUMIDITY] == 34
async def test_buggy_thermostat_entity_state(hass, buggy_thermostat): async def test_buggy_thermostat_entity_state(
hass: HomeAssistant, buggy_thermostat
) -> None:
"""Tests the state attributes properly match the thermostat type.""" """Tests the state attributes properly match the thermostat type."""
await setup_platform(hass, CLIMATE_DOMAIN, devices=[buggy_thermostat]) await setup_platform(hass, CLIMATE_DOMAIN, devices=[buggy_thermostat])
state = hass.states.get("climate.buggy_thermostat") state = hass.states.get("climate.buggy_thermostat")
@ -271,7 +278,9 @@ async def test_buggy_thermostat_entity_state(hass, buggy_thermostat):
assert state.attributes[ATTR_HVAC_MODES] == [] assert state.attributes[ATTR_HVAC_MODES] == []
async def test_buggy_thermostat_invalid_mode(hass, buggy_thermostat): async def test_buggy_thermostat_invalid_mode(
hass: HomeAssistant, buggy_thermostat
) -> None:
"""Tests when an invalid operation mode is included.""" """Tests when an invalid operation mode is included."""
buggy_thermostat.status.update_attribute_value( buggy_thermostat.status.update_attribute_value(
Attribute.supported_thermostat_modes, ["heat", "emergency heat", "other"] Attribute.supported_thermostat_modes, ["heat", "emergency heat", "other"]
@ -281,7 +290,9 @@ async def test_buggy_thermostat_invalid_mode(hass, buggy_thermostat):
assert state.attributes[ATTR_HVAC_MODES] == [HVACMode.HEAT] assert state.attributes[ATTR_HVAC_MODES] == [HVACMode.HEAT]
async def test_air_conditioner_entity_state(hass, air_conditioner): async def test_air_conditioner_entity_state(
hass: HomeAssistant, air_conditioner
) -> None:
"""Tests when an invalid operation mode is included.""" """Tests when an invalid operation mode is included."""
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner]) await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner])
state = hass.states.get("climate.air_conditioner") state = hass.states.get("climate.air_conditioner")
@ -314,7 +325,7 @@ async def test_air_conditioner_entity_state(hass, air_conditioner):
assert state.attributes["drlc_status_override"] is False assert state.attributes["drlc_status_override"] is False
async def test_set_fan_mode(hass, thermostat, air_conditioner): async def test_set_fan_mode(hass: HomeAssistant, thermostat, air_conditioner) -> None:
"""Test the fan mode is set successfully.""" """Test the fan mode is set successfully."""
await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat, air_conditioner]) await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat, air_conditioner])
entity_ids = ["climate.thermostat", "climate.air_conditioner"] entity_ids = ["climate.thermostat", "climate.air_conditioner"]
@ -329,7 +340,7 @@ async def test_set_fan_mode(hass, thermostat, air_conditioner):
assert state.attributes[ATTR_FAN_MODE] == "auto", entity_id assert state.attributes[ATTR_FAN_MODE] == "auto", entity_id
async def test_set_hvac_mode(hass, thermostat, air_conditioner): async def test_set_hvac_mode(hass: HomeAssistant, thermostat, air_conditioner) -> None:
"""Test the hvac mode is set successfully.""" """Test the hvac mode is set successfully."""
await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat, air_conditioner]) await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat, air_conditioner])
entity_ids = ["climate.thermostat", "climate.air_conditioner"] entity_ids = ["climate.thermostat", "climate.air_conditioner"]
@ -345,7 +356,7 @@ async def test_set_hvac_mode(hass, thermostat, air_conditioner):
assert state.state == HVACMode.COOL, entity_id assert state.state == HVACMode.COOL, entity_id
async def test_ac_set_hvac_mode_from_off(hass, air_conditioner): async def test_ac_set_hvac_mode_from_off(hass: HomeAssistant, air_conditioner) -> None:
"""Test setting HVAC mode when the unit is off.""" """Test setting HVAC mode when the unit is off."""
air_conditioner.status.update_attribute_value( air_conditioner.status.update_attribute_value(
Attribute.air_conditioner_mode, "heat" Attribute.air_conditioner_mode, "heat"
@ -367,7 +378,7 @@ async def test_ac_set_hvac_mode_from_off(hass, air_conditioner):
assert state.state == HVACMode.HEAT_COOL assert state.state == HVACMode.HEAT_COOL
async def test_ac_set_hvac_mode_off(hass, air_conditioner): async def test_ac_set_hvac_mode_off(hass: HomeAssistant, air_conditioner) -> None:
"""Test the AC HVAC mode can be turned off set successfully.""" """Test the AC HVAC mode can be turned off set successfully."""
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner]) await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner])
state = hass.states.get("climate.air_conditioner") state = hass.states.get("climate.air_conditioner")
@ -382,7 +393,7 @@ async def test_ac_set_hvac_mode_off(hass, air_conditioner):
assert state.state == HVACMode.OFF assert state.state == HVACMode.OFF
async def test_set_temperature_heat_mode(hass, thermostat): async def test_set_temperature_heat_mode(hass: HomeAssistant, thermostat) -> None:
"""Test the temperature is set successfully when in heat mode.""" """Test the temperature is set successfully when in heat mode."""
thermostat.status.thermostat_mode = "heat" thermostat.status.thermostat_mode = "heat"
await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat]) await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat])
@ -398,7 +409,7 @@ async def test_set_temperature_heat_mode(hass, thermostat):
assert thermostat.status.heating_setpoint == 69.8 assert thermostat.status.heating_setpoint == 69.8
async def test_set_temperature_cool_mode(hass, thermostat): async def test_set_temperature_cool_mode(hass: HomeAssistant, thermostat) -> None:
"""Test the temperature is set successfully when in cool mode.""" """Test the temperature is set successfully when in cool mode."""
thermostat.status.thermostat_mode = "cool" thermostat.status.thermostat_mode = "cool"
await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat]) await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat])
@ -412,7 +423,7 @@ async def test_set_temperature_cool_mode(hass, thermostat):
assert state.attributes[ATTR_TEMPERATURE] == 21 assert state.attributes[ATTR_TEMPERATURE] == 21
async def test_set_temperature(hass, thermostat): async def test_set_temperature(hass: HomeAssistant, thermostat) -> None:
"""Test the temperature is set successfully.""" """Test the temperature is set successfully."""
thermostat.status.thermostat_mode = "auto" thermostat.status.thermostat_mode = "auto"
await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat]) await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat])
@ -431,7 +442,7 @@ async def test_set_temperature(hass, thermostat):
assert state.attributes[ATTR_TARGET_TEMP_LOW] == 22.2 assert state.attributes[ATTR_TARGET_TEMP_LOW] == 22.2
async def test_set_temperature_ac(hass, air_conditioner): async def test_set_temperature_ac(hass: HomeAssistant, air_conditioner) -> None:
"""Test the temperature is set successfully.""" """Test the temperature is set successfully."""
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner]) await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner])
await hass.services.async_call( await hass.services.async_call(
@ -444,7 +455,9 @@ async def test_set_temperature_ac(hass, air_conditioner):
assert state.attributes[ATTR_TEMPERATURE] == 27 assert state.attributes[ATTR_TEMPERATURE] == 27
async def test_set_temperature_ac_with_mode(hass, air_conditioner): async def test_set_temperature_ac_with_mode(
hass: HomeAssistant, air_conditioner
) -> None:
"""Test the temperature is set successfully.""" """Test the temperature is set successfully."""
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner]) await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner])
await hass.services.async_call( await hass.services.async_call(
@ -462,7 +475,9 @@ async def test_set_temperature_ac_with_mode(hass, air_conditioner):
assert state.state == HVACMode.COOL assert state.state == HVACMode.COOL
async def test_set_temperature_ac_with_mode_from_off(hass, air_conditioner): async def test_set_temperature_ac_with_mode_from_off(
hass: HomeAssistant, air_conditioner
) -> None:
"""Test the temp and mode is set successfully when the unit is off.""" """Test the temp and mode is set successfully when the unit is off."""
air_conditioner.status.update_attribute_value( air_conditioner.status.update_attribute_value(
Attribute.air_conditioner_mode, "heat" Attribute.air_conditioner_mode, "heat"
@ -485,7 +500,9 @@ async def test_set_temperature_ac_with_mode_from_off(hass, air_conditioner):
assert state.state == HVACMode.COOL assert state.state == HVACMode.COOL
async def test_set_temperature_ac_with_mode_to_off(hass, air_conditioner): async def test_set_temperature_ac_with_mode_to_off(
hass: HomeAssistant, air_conditioner
) -> None:
"""Test the temp and mode is set successfully to turn off the unit.""" """Test the temp and mode is set successfully to turn off the unit."""
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner]) await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner])
assert hass.states.get("climate.air_conditioner").state != HVACMode.OFF assert hass.states.get("climate.air_conditioner").state != HVACMode.OFF
@ -504,7 +521,7 @@ async def test_set_temperature_ac_with_mode_to_off(hass, air_conditioner):
assert state.state == HVACMode.OFF assert state.state == HVACMode.OFF
async def test_set_temperature_with_mode(hass, thermostat): async def test_set_temperature_with_mode(hass: HomeAssistant, thermostat) -> None:
"""Test the temperature and mode is set successfully.""" """Test the temperature and mode is set successfully."""
await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat]) await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat])
await hass.services.async_call( await hass.services.async_call(
@ -524,7 +541,7 @@ async def test_set_temperature_with_mode(hass, thermostat):
assert state.state == HVACMode.HEAT_COOL assert state.state == HVACMode.HEAT_COOL
async def test_set_turn_off(hass, air_conditioner): async def test_set_turn_off(hass: HomeAssistant, air_conditioner) -> None:
"""Test the a/c is turned off successfully.""" """Test the a/c is turned off successfully."""
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner]) await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner])
state = hass.states.get("climate.air_conditioner") state = hass.states.get("climate.air_conditioner")
@ -536,7 +553,7 @@ async def test_set_turn_off(hass, air_conditioner):
assert state.state == HVACMode.OFF assert state.state == HVACMode.OFF
async def test_set_turn_on(hass, air_conditioner): async def test_set_turn_on(hass: HomeAssistant, air_conditioner) -> None:
"""Test the a/c is turned on successfully.""" """Test the a/c is turned on successfully."""
air_conditioner.status.update_attribute_value(Attribute.switch, "off") air_conditioner.status.update_attribute_value(Attribute.switch, "off")
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner]) await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner])
@ -549,7 +566,7 @@ async def test_set_turn_on(hass, air_conditioner):
assert state.state == HVACMode.HEAT_COOL assert state.state == HVACMode.HEAT_COOL
async def test_entity_and_device_attributes(hass, thermostat): async def test_entity_and_device_attributes(hass: HomeAssistant, thermostat) -> None:
"""Test the attributes of the entries are correct.""" """Test the attributes of the entries are correct."""
await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat]) await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat])
entity_registry = er.async_get(hass) entity_registry = er.async_get(hass)

View file

@ -35,7 +35,9 @@ async def test_import_shows_user_step(hass: HomeAssistant) -> None:
] == smartapp.get_webhook_url(hass) ] == smartapp.get_webhook_url(hass)
async def test_entry_created(hass, app, app_oauth_client, location, smartthings_mock): async def test_entry_created(
hass: HomeAssistant, app, app_oauth_client, location, smartthings_mock
) -> None:
"""Test local webhook, new app, install event creates entry.""" """Test local webhook, new app, install event creates entry."""
token = str(uuid4()) token = str(uuid4())
installed_app_id = str(uuid4()) installed_app_id = str(uuid4())
@ -105,8 +107,8 @@ async def test_entry_created(hass, app, app_oauth_client, location, smartthings_
async def test_entry_created_from_update_event( async def test_entry_created_from_update_event(
hass, app, app_oauth_client, location, smartthings_mock hass: HomeAssistant, app, app_oauth_client, location, smartthings_mock
): ) -> None:
"""Test local webhook, new app, update event creates entry.""" """Test local webhook, new app, update event creates entry."""
token = str(uuid4()) token = str(uuid4())
installed_app_id = str(uuid4()) installed_app_id = str(uuid4())
@ -176,8 +178,8 @@ async def test_entry_created_from_update_event(
async def test_entry_created_existing_app_new_oauth_client( async def test_entry_created_existing_app_new_oauth_client(
hass, app, app_oauth_client, location, smartthings_mock hass: HomeAssistant, app, app_oauth_client, location, smartthings_mock
): ) -> None:
"""Test entry is created with an existing app and generation of a new oauth client.""" """Test entry is created with an existing app and generation of a new oauth client."""
token = str(uuid4()) token = str(uuid4())
installed_app_id = str(uuid4()) installed_app_id = str(uuid4())
@ -247,8 +249,8 @@ async def test_entry_created_existing_app_new_oauth_client(
async def test_entry_created_existing_app_copies_oauth_client( async def test_entry_created_existing_app_copies_oauth_client(
hass, app, location, smartthings_mock hass: HomeAssistant, app, location, smartthings_mock
): ) -> None:
"""Test entry is created with an existing app and copies the oauth client from another entry.""" """Test entry is created with an existing app and copies the oauth client from another entry."""
token = str(uuid4()) token = str(uuid4())
installed_app_id = str(uuid4()) installed_app_id = str(uuid4())
@ -337,8 +339,8 @@ async def test_entry_created_existing_app_copies_oauth_client(
async def test_entry_created_with_cloudhook( async def test_entry_created_with_cloudhook(
hass, app, app_oauth_client, location, smartthings_mock hass: HomeAssistant, app, app_oauth_client, location, smartthings_mock
): ) -> None:
"""Test cloud, new app, install event creates entry.""" """Test cloud, new app, install event creates entry."""
hass.config.components.add("cloud") hass.config.components.add("cloud")
# Unload the endpoint so we can reload it under the cloud. # Unload the endpoint so we can reload it under the cloud.
@ -473,7 +475,9 @@ async def test_invalid_token_shows_error(hass: HomeAssistant) -> None:
assert "component_url" in result["description_placeholders"] assert "component_url" in result["description_placeholders"]
async def test_unauthorized_token_shows_error(hass, smartthings_mock): async def test_unauthorized_token_shows_error(
hass: HomeAssistant, smartthings_mock
) -> None:
"""Test an error is shown for unauthorized token formats.""" """Test an error is shown for unauthorized token formats."""
token = str(uuid4()) token = str(uuid4())
request_info = Mock(real_url="http://example.com") request_info = Mock(real_url="http://example.com")
@ -510,7 +514,9 @@ async def test_unauthorized_token_shows_error(hass, smartthings_mock):
assert "component_url" in result["description_placeholders"] assert "component_url" in result["description_placeholders"]
async def test_forbidden_token_shows_error(hass, smartthings_mock): async def test_forbidden_token_shows_error(
hass: HomeAssistant, smartthings_mock
) -> None:
"""Test an error is shown for forbidden token formats.""" """Test an error is shown for forbidden token formats."""
token = str(uuid4()) token = str(uuid4())
request_info = Mock(real_url="http://example.com") request_info = Mock(real_url="http://example.com")
@ -547,7 +553,9 @@ async def test_forbidden_token_shows_error(hass, smartthings_mock):
assert "component_url" in result["description_placeholders"] assert "component_url" in result["description_placeholders"]
async def test_webhook_problem_shows_error(hass, smartthings_mock): async def test_webhook_problem_shows_error(
hass: HomeAssistant, smartthings_mock
) -> None:
"""Test an error is shown when there's an problem with the webhook endpoint.""" """Test an error is shown when there's an problem with the webhook endpoint."""
token = str(uuid4()) token = str(uuid4())
data = {"error": {}} data = {"error": {}}
@ -590,7 +598,7 @@ async def test_webhook_problem_shows_error(hass, smartthings_mock):
assert "component_url" in result["description_placeholders"] assert "component_url" in result["description_placeholders"]
async def test_api_error_shows_error(hass, smartthings_mock): async def test_api_error_shows_error(hass: HomeAssistant, smartthings_mock) -> None:
"""Test an error is shown when other API errors occur.""" """Test an error is shown when other API errors occur."""
token = str(uuid4()) token = str(uuid4())
data = {"error": {}} data = {"error": {}}
@ -632,7 +640,9 @@ async def test_api_error_shows_error(hass, smartthings_mock):
assert "component_url" in result["description_placeholders"] assert "component_url" in result["description_placeholders"]
async def test_unknown_response_error_shows_error(hass, smartthings_mock): async def test_unknown_response_error_shows_error(
hass: HomeAssistant, smartthings_mock
) -> None:
"""Test an error is shown when there is an unknown API error.""" """Test an error is shown when there is an unknown API error."""
token = str(uuid4()) token = str(uuid4())
request_info = Mock(real_url="http://example.com") request_info = Mock(real_url="http://example.com")
@ -670,7 +680,7 @@ async def test_unknown_response_error_shows_error(hass, smartthings_mock):
assert "component_url" in result["description_placeholders"] assert "component_url" in result["description_placeholders"]
async def test_unknown_error_shows_error(hass, smartthings_mock): async def test_unknown_error_shows_error(hass: HomeAssistant, smartthings_mock) -> None:
"""Test an error is shown when there is an unknown API error.""" """Test an error is shown when there is an unknown API error."""
token = str(uuid4()) token = str(uuid4())
smartthings_mock.apps.side_effect = Exception("Unknown error") smartthings_mock.apps.side_effect = Exception("Unknown error")
@ -705,8 +715,8 @@ async def test_unknown_error_shows_error(hass, smartthings_mock):
async def test_no_available_locations_aborts( async def test_no_available_locations_aborts(
hass, app, app_oauth_client, location, smartthings_mock hass: HomeAssistant, app, app_oauth_client, location, smartthings_mock
): ) -> None:
"""Test select location aborts if no available locations.""" """Test select location aborts if no available locations."""
token = str(uuid4()) token = str(uuid4())
smartthings_mock.apps.return_value = [] smartthings_mock.apps.return_value = []

View file

@ -20,13 +20,16 @@ from homeassistant.components.cover import (
from homeassistant.components.smartthings.const import DOMAIN, SIGNAL_SMARTTHINGS_UPDATE from homeassistant.components.smartthings.const import DOMAIN, SIGNAL_SMARTTHINGS_UPDATE
from homeassistant.config_entries import ConfigEntryState from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import ATTR_BATTERY_LEVEL, ATTR_ENTITY_ID, STATE_UNAVAILABLE from homeassistant.const import ATTR_BATTERY_LEVEL, ATTR_ENTITY_ID, STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.dispatcher import async_dispatcher_send
from .conftest import setup_platform from .conftest import setup_platform
async def test_entity_and_device_attributes(hass, device_factory): async def test_entity_and_device_attributes(
hass: HomeAssistant, device_factory
) -> None:
"""Test the attributes of the entity are correct.""" """Test the attributes of the entity are correct."""
# Arrange # Arrange
device = device_factory( device = device_factory(
@ -50,7 +53,7 @@ async def test_entity_and_device_attributes(hass, device_factory):
assert entry.manufacturer == "Unavailable" assert entry.manufacturer == "Unavailable"
async def test_open(hass, device_factory): async def test_open(hass: HomeAssistant, device_factory) -> None:
"""Test the cover opens doors, garages, and shades successfully.""" """Test the cover opens doors, garages, and shades successfully."""
# Arrange # Arrange
devices = { devices = {
@ -75,7 +78,7 @@ async def test_open(hass, device_factory):
assert state.state == STATE_OPENING assert state.state == STATE_OPENING
async def test_close(hass, device_factory): async def test_close(hass: HomeAssistant, device_factory) -> None:
"""Test the cover closes doors, garages, and shades successfully.""" """Test the cover closes doors, garages, and shades successfully."""
# Arrange # Arrange
devices = { devices = {
@ -100,7 +103,7 @@ async def test_close(hass, device_factory):
assert state.state == STATE_CLOSING assert state.state == STATE_CLOSING
async def test_set_cover_position(hass, device_factory): async def test_set_cover_position(hass: HomeAssistant, device_factory) -> None:
"""Test the cover sets to the specific position.""" """Test the cover sets to the specific position."""
# Arrange # Arrange
device = device_factory( device = device_factory(
@ -127,7 +130,9 @@ async def test_set_cover_position(hass, device_factory):
assert device._api.post_device_command.call_count == 1 # type: ignore assert device._api.post_device_command.call_count == 1 # type: ignore
async def test_set_cover_position_unsupported(hass, device_factory): async def test_set_cover_position_unsupported(
hass: HomeAssistant, device_factory
) -> None:
"""Test set position does nothing when not supported by device.""" """Test set position does nothing when not supported by device."""
# Arrange # Arrange
device = device_factory( device = device_factory(
@ -150,7 +155,7 @@ async def test_set_cover_position_unsupported(hass, device_factory):
assert device._api.post_device_command.call_count == 0 # type: ignore assert device._api.post_device_command.call_count == 0 # type: ignore
async def test_update_to_open_from_signal(hass, device_factory): async def test_update_to_open_from_signal(hass: HomeAssistant, device_factory) -> None:
"""Test the cover updates to open when receiving a signal.""" """Test the cover updates to open when receiving a signal."""
# Arrange # Arrange
device = device_factory( device = device_factory(
@ -168,7 +173,9 @@ async def test_update_to_open_from_signal(hass, device_factory):
assert state.state == STATE_OPEN assert state.state == STATE_OPEN
async def test_update_to_closed_from_signal(hass, device_factory): async def test_update_to_closed_from_signal(
hass: HomeAssistant, device_factory
) -> None:
"""Test the cover updates to closed when receiving a signal.""" """Test the cover updates to closed when receiving a signal."""
# Arrange # Arrange
device = device_factory( device = device_factory(
@ -186,7 +193,7 @@ async def test_update_to_closed_from_signal(hass, device_factory):
assert state.state == STATE_CLOSED assert state.state == STATE_CLOSED
async def test_unload_config_entry(hass, device_factory): async def test_unload_config_entry(hass: HomeAssistant, device_factory) -> None:
"""Test the lock is removed when the config entry is unloaded.""" """Test the lock is removed when the config entry is unloaded."""
# Arrange # Arrange
device = device_factory( device = device_factory(

View file

@ -17,13 +17,14 @@ from homeassistant.const import (
ATTR_SUPPORTED_FEATURES, ATTR_SUPPORTED_FEATURES,
STATE_UNAVAILABLE, STATE_UNAVAILABLE,
) )
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.dispatcher import async_dispatcher_send
from .conftest import setup_platform from .conftest import setup_platform
async def test_entity_state(hass, device_factory): async def test_entity_state(hass: HomeAssistant, device_factory) -> None:
"""Tests the state attributes properly match the fan types.""" """Tests the state attributes properly match the fan types."""
device = device_factory( device = device_factory(
"Fan 1", "Fan 1",
@ -39,7 +40,9 @@ async def test_entity_state(hass, device_factory):
assert state.attributes[ATTR_PERCENTAGE] == 66 assert state.attributes[ATTR_PERCENTAGE] == 66
async def test_entity_and_device_attributes(hass, device_factory): async def test_entity_and_device_attributes(
hass: HomeAssistant, device_factory
) -> None:
"""Test the attributes of the entity are correct.""" """Test the attributes of the entity are correct."""
# Arrange # Arrange
device = device_factory( device = device_factory(
@ -65,7 +68,7 @@ async def test_entity_and_device_attributes(hass, device_factory):
assert entry.manufacturer == "Unavailable" assert entry.manufacturer == "Unavailable"
async def test_turn_off(hass, device_factory): async def test_turn_off(hass: HomeAssistant, device_factory) -> None:
"""Test the fan turns of successfully.""" """Test the fan turns of successfully."""
# Arrange # Arrange
device = device_factory( device = device_factory(
@ -84,7 +87,7 @@ async def test_turn_off(hass, device_factory):
assert state.state == "off" assert state.state == "off"
async def test_turn_on(hass, device_factory): async def test_turn_on(hass: HomeAssistant, device_factory) -> None:
"""Test the fan turns of successfully.""" """Test the fan turns of successfully."""
# Arrange # Arrange
device = device_factory( device = device_factory(
@ -103,7 +106,7 @@ async def test_turn_on(hass, device_factory):
assert state.state == "on" assert state.state == "on"
async def test_turn_on_with_speed(hass, device_factory): async def test_turn_on_with_speed(hass: HomeAssistant, device_factory) -> None:
"""Test the fan turns on to the specified speed.""" """Test the fan turns on to the specified speed."""
# Arrange # Arrange
device = device_factory( device = device_factory(
@ -126,7 +129,7 @@ async def test_turn_on_with_speed(hass, device_factory):
assert state.attributes[ATTR_PERCENTAGE] == 100 assert state.attributes[ATTR_PERCENTAGE] == 100
async def test_set_percentage(hass, device_factory): async def test_set_percentage(hass: HomeAssistant, device_factory) -> None:
"""Test setting to specific fan speed.""" """Test setting to specific fan speed."""
# Arrange # Arrange
device = device_factory( device = device_factory(
@ -149,7 +152,7 @@ async def test_set_percentage(hass, device_factory):
assert state.attributes[ATTR_PERCENTAGE] == 100 assert state.attributes[ATTR_PERCENTAGE] == 100
async def test_update_from_signal(hass, device_factory): async def test_update_from_signal(hass: HomeAssistant, device_factory) -> None:
"""Test the fan updates when receiving a signal.""" """Test the fan updates when receiving a signal."""
# Arrange # Arrange
device = device_factory( device = device_factory(
@ -168,7 +171,7 @@ async def test_update_from_signal(hass, device_factory):
assert state.state == "on" assert state.state == "on"
async def test_unload_config_entry(hass, device_factory): async def test_unload_config_entry(hass: HomeAssistant, device_factory) -> None:
"""Test the fan is removed when the config entry is unloaded.""" """Test the fan is removed when the config entry is unloaded."""
# Arrange # Arrange
device = device_factory( device = device_factory(

View file

@ -20,13 +20,16 @@ from homeassistant.components.smartthings.const import (
SIGNAL_SMARTTHINGS_UPDATE, SIGNAL_SMARTTHINGS_UPDATE,
) )
from homeassistant.config import async_process_ha_core_config from homeassistant.config import async_process_ha_core_config
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
async def test_migration_creates_new_flow(hass, smartthings_mock, config_entry): async def test_migration_creates_new_flow(
hass: HomeAssistant, smartthings_mock, config_entry
) -> None:
"""Test migration deletes app and creates new flow.""" """Test migration deletes app and creates new flow."""
config_entry.version = 1 config_entry.version = 1
@ -45,8 +48,8 @@ async def test_migration_creates_new_flow(hass, smartthings_mock, config_entry):
async def test_unrecoverable_api_errors_create_new_flow( async def test_unrecoverable_api_errors_create_new_flow(
hass, config_entry, smartthings_mock hass: HomeAssistant, config_entry, smartthings_mock
): ) -> None:
"""Test a new config flow is initiated when there are API errors. """Test a new config flow is initiated when there are API errors.
401 (unauthorized): Occurs when the access token is no longer valid. 401 (unauthorized): Occurs when the access token is no longer valid.
@ -75,8 +78,8 @@ async def test_unrecoverable_api_errors_create_new_flow(
async def test_recoverable_api_errors_raise_not_ready( async def test_recoverable_api_errors_raise_not_ready(
hass, config_entry, smartthings_mock hass: HomeAssistant, config_entry, smartthings_mock
): ) -> None:
"""Test config entry not ready raised for recoverable API errors.""" """Test config entry not ready raised for recoverable API errors."""
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
request_info = Mock(real_url="http://example.com") request_info = Mock(real_url="http://example.com")
@ -91,8 +94,8 @@ async def test_recoverable_api_errors_raise_not_ready(
async def test_scenes_api_errors_raise_not_ready( async def test_scenes_api_errors_raise_not_ready(
hass, config_entry, app, installed_app, smartthings_mock hass: HomeAssistant, config_entry, app, installed_app, smartthings_mock
): ) -> None:
"""Test if scenes are unauthorized we continue to load platforms.""" """Test if scenes are unauthorized we continue to load platforms."""
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
request_info = Mock(real_url="http://example.com") request_info = Mock(real_url="http://example.com")
@ -107,7 +110,9 @@ async def test_scenes_api_errors_raise_not_ready(
await smartthings.async_setup_entry(hass, config_entry) await smartthings.async_setup_entry(hass, config_entry)
async def test_connection_errors_raise_not_ready(hass, config_entry, smartthings_mock): async def test_connection_errors_raise_not_ready(
hass: HomeAssistant, config_entry, smartthings_mock
) -> None:
"""Test config entry not ready raised for connection errors.""" """Test config entry not ready raised for connection errors."""
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
smartthings_mock.app.side_effect = ClientConnectionError() smartthings_mock.app.side_effect = ClientConnectionError()
@ -117,8 +122,8 @@ async def test_connection_errors_raise_not_ready(hass, config_entry, smartthings
async def test_base_url_no_longer_https_does_not_load( async def test_base_url_no_longer_https_does_not_load(
hass, config_entry, app, smartthings_mock hass: HomeAssistant, config_entry, app, smartthings_mock
): ) -> None:
"""Test base_url no longer valid creates a new flow.""" """Test base_url no longer valid creates a new flow."""
await async_process_ha_core_config( await async_process_ha_core_config(
hass, hass,
@ -133,8 +138,8 @@ async def test_base_url_no_longer_https_does_not_load(
async def test_unauthorized_installed_app_raises_not_ready( async def test_unauthorized_installed_app_raises_not_ready(
hass, config_entry, app, installed_app, smartthings_mock hass: HomeAssistant, config_entry, app, installed_app, smartthings_mock
): ) -> None:
"""Test config entry not ready raised when the app isn't authorized.""" """Test config entry not ready raised when the app isn't authorized."""
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
installed_app.installed_app_status = InstalledAppStatus.PENDING installed_app.installed_app_status = InstalledAppStatus.PENDING
@ -147,14 +152,14 @@ async def test_unauthorized_installed_app_raises_not_ready(
async def test_scenes_unauthorized_loads_platforms( async def test_scenes_unauthorized_loads_platforms(
hass, hass: HomeAssistant,
config_entry, config_entry,
app, app,
installed_app, installed_app,
device, device,
smartthings_mock, smartthings_mock,
subscription_factory, subscription_factory,
): ) -> None:
"""Test if scenes are unauthorized we continue to load platforms.""" """Test if scenes are unauthorized we continue to load platforms."""
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
request_info = Mock(real_url="http://example.com") request_info = Mock(real_url="http://example.com")
@ -181,7 +186,7 @@ async def test_scenes_unauthorized_loads_platforms(
async def test_config_entry_loads_platforms( async def test_config_entry_loads_platforms(
hass, hass: HomeAssistant,
config_entry, config_entry,
app, app,
installed_app, installed_app,
@ -189,7 +194,7 @@ async def test_config_entry_loads_platforms(
smartthings_mock, smartthings_mock,
subscription_factory, subscription_factory,
scene, scene,
): ) -> None:
"""Test config entry loads properly and proxies to platforms.""" """Test config entry loads properly and proxies to platforms."""
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
smartthings_mock.app.return_value = app smartthings_mock.app.return_value = app
@ -213,7 +218,7 @@ async def test_config_entry_loads_platforms(
async def test_config_entry_loads_unconnected_cloud( async def test_config_entry_loads_unconnected_cloud(
hass, hass: HomeAssistant,
config_entry, config_entry,
app, app,
installed_app, installed_app,
@ -221,7 +226,7 @@ async def test_config_entry_loads_unconnected_cloud(
smartthings_mock, smartthings_mock,
subscription_factory, subscription_factory,
scene, scene,
): ) -> None:
"""Test entry loads during startup when cloud isn't connected.""" """Test entry loads during startup when cloud isn't connected."""
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
hass.data[DOMAIN][CONF_CLOUDHOOK_URL] = "https://test.cloud" hass.data[DOMAIN][CONF_CLOUDHOOK_URL] = "https://test.cloud"
@ -243,7 +248,7 @@ async def test_config_entry_loads_unconnected_cloud(
assert forward_mock.call_count == len(PLATFORMS) assert forward_mock.call_count == len(PLATFORMS)
async def test_unload_entry(hass, config_entry): async def test_unload_entry(hass: HomeAssistant, config_entry) -> None:
"""Test entries are unloaded correctly.""" """Test entries are unloaded correctly."""
connect_disconnect = Mock() connect_disconnect = Mock()
smart_app = Mock() smart_app = Mock()
@ -264,7 +269,9 @@ async def test_unload_entry(hass, config_entry):
assert forward_mock.call_count == len(PLATFORMS) assert forward_mock.call_count == len(PLATFORMS)
async def test_remove_entry(hass, config_entry, smartthings_mock): async def test_remove_entry(
hass: HomeAssistant, config_entry, smartthings_mock
) -> None:
"""Test that the installed app and app are removed up.""" """Test that the installed app and app are removed up."""
# Act # Act
await smartthings.async_remove_entry(hass, config_entry) await smartthings.async_remove_entry(hass, config_entry)
@ -273,7 +280,9 @@ async def test_remove_entry(hass, config_entry, smartthings_mock):
assert smartthings_mock.delete_app.call_count == 1 assert smartthings_mock.delete_app.call_count == 1
async def test_remove_entry_cloudhook(hass, config_entry, smartthings_mock): async def test_remove_entry_cloudhook(
hass: HomeAssistant, config_entry, smartthings_mock
) -> None:
"""Test that the installed app, app, and cloudhook are removed up.""" """Test that the installed app, app, and cloudhook are removed up."""
hass.config.components.add("cloud") hass.config.components.add("cloud")
# Arrange # Arrange
@ -293,7 +302,9 @@ async def test_remove_entry_cloudhook(hass, config_entry, smartthings_mock):
assert mock_async_delete_cloudhook.call_count == 1 assert mock_async_delete_cloudhook.call_count == 1
async def test_remove_entry_app_in_use(hass, config_entry, smartthings_mock): async def test_remove_entry_app_in_use(
hass: HomeAssistant, config_entry, smartthings_mock
) -> None:
"""Test app is not removed if in use by another config entry.""" """Test app is not removed if in use by another config entry."""
# Arrange # Arrange
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -308,7 +319,9 @@ async def test_remove_entry_app_in_use(hass, config_entry, smartthings_mock):
assert smartthings_mock.delete_app.call_count == 0 assert smartthings_mock.delete_app.call_count == 0
async def test_remove_entry_already_deleted(hass, config_entry, smartthings_mock): async def test_remove_entry_already_deleted(
hass: HomeAssistant, config_entry, smartthings_mock
) -> None:
"""Test handles when the apps have already been removed.""" """Test handles when the apps have already been removed."""
request_info = Mock(real_url="http://example.com") request_info = Mock(real_url="http://example.com")
# Arrange # Arrange
@ -326,8 +339,8 @@ async def test_remove_entry_already_deleted(hass, config_entry, smartthings_mock
async def test_remove_entry_installedapp_api_error( async def test_remove_entry_installedapp_api_error(
hass, config_entry, smartthings_mock hass: HomeAssistant, config_entry, smartthings_mock
): ) -> None:
"""Test raises exceptions removing the installed app.""" """Test raises exceptions removing the installed app."""
request_info = Mock(real_url="http://example.com") request_info = Mock(real_url="http://example.com")
# Arrange # Arrange
@ -345,8 +358,8 @@ async def test_remove_entry_installedapp_api_error(
async def test_remove_entry_installedapp_unknown_error( async def test_remove_entry_installedapp_unknown_error(
hass, config_entry, smartthings_mock hass: HomeAssistant, config_entry, smartthings_mock
): ) -> None:
"""Test raises exceptions removing the installed app.""" """Test raises exceptions removing the installed app."""
# Arrange # Arrange
smartthings_mock.delete_installed_app.side_effect = Exception smartthings_mock.delete_installed_app.side_effect = Exception
@ -358,7 +371,9 @@ async def test_remove_entry_installedapp_unknown_error(
assert smartthings_mock.delete_app.call_count == 0 assert smartthings_mock.delete_app.call_count == 0
async def test_remove_entry_app_api_error(hass, config_entry, smartthings_mock): async def test_remove_entry_app_api_error(
hass: HomeAssistant, config_entry, smartthings_mock
) -> None:
"""Test raises exceptions removing the app.""" """Test raises exceptions removing the app."""
# Arrange # Arrange
request_info = Mock(real_url="http://example.com") request_info = Mock(real_url="http://example.com")
@ -375,7 +390,9 @@ async def test_remove_entry_app_api_error(hass, config_entry, smartthings_mock):
assert smartthings_mock.delete_app.call_count == 1 assert smartthings_mock.delete_app.call_count == 1
async def test_remove_entry_app_unknown_error(hass, config_entry, smartthings_mock): async def test_remove_entry_app_unknown_error(
hass: HomeAssistant, config_entry, smartthings_mock
) -> None:
"""Test raises exceptions removing the app.""" """Test raises exceptions removing the app."""
# Arrange # Arrange
smartthings_mock.delete_app.side_effect = Exception smartthings_mock.delete_app.side_effect = Exception
@ -387,7 +404,7 @@ async def test_remove_entry_app_unknown_error(hass, config_entry, smartthings_mo
assert smartthings_mock.delete_app.call_count == 1 assert smartthings_mock.delete_app.call_count == 1
async def test_broker_regenerates_token(hass, config_entry): async def test_broker_regenerates_token(hass: HomeAssistant, config_entry) -> None:
"""Test the device broker regenerates the refresh token.""" """Test the device broker regenerates the refresh token."""
token = Mock(OAuthToken) token = Mock(OAuthToken)
token.refresh_token = str(uuid4()) token.refresh_token = str(uuid4())
@ -411,8 +428,12 @@ async def test_broker_regenerates_token(hass, config_entry):
async def test_event_handler_dispatches_updated_devices( async def test_event_handler_dispatches_updated_devices(
hass, config_entry, device_factory, event_request_factory, event_factory hass: HomeAssistant,
): config_entry,
device_factory,
event_request_factory,
event_factory,
) -> None:
"""Test the event handler dispatches updated devices.""" """Test the event handler dispatches updated devices."""
devices = [ devices = [
device_factory("Bedroom 1 Switch", ["switch"]), device_factory("Bedroom 1 Switch", ["switch"]),
@ -461,8 +482,8 @@ async def test_event_handler_dispatches_updated_devices(
async def test_event_handler_ignores_other_installed_app( async def test_event_handler_ignores_other_installed_app(
hass, config_entry, device_factory, event_request_factory hass: HomeAssistant, config_entry, device_factory, event_request_factory
): ) -> None:
"""Test the event handler dispatches updated devices.""" """Test the event handler dispatches updated devices."""
device = device_factory("Bedroom 1 Switch", ["switch"]) device = device_factory("Bedroom 1 Switch", ["switch"])
request = event_request_factory([device.device_id]) request = event_request_factory([device.device_id])
@ -483,8 +504,12 @@ async def test_event_handler_ignores_other_installed_app(
async def test_event_handler_fires_button_events( async def test_event_handler_fires_button_events(
hass, config_entry, device_factory, event_factory, event_request_factory hass: HomeAssistant,
): config_entry,
device_factory,
event_factory,
event_request_factory,
) -> None:
"""Test the event handler fires button events.""" """Test the event handler fires button events."""
device = device_factory("Button 1", ["button"]) device = device_factory("Button 1", ["button"])
event = event_factory( event = event_factory(

View file

@ -23,6 +23,7 @@ from homeassistant.const import (
ATTR_SUPPORTED_FEATURES, ATTR_SUPPORTED_FEATURES,
STATE_UNAVAILABLE, STATE_UNAVAILABLE,
) )
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.dispatcher import async_dispatcher_send
@ -71,7 +72,7 @@ def light_devices_fixture(device_factory):
] ]
async def test_entity_state(hass, light_devices): async def test_entity_state(hass: HomeAssistant, light_devices) -> None:
"""Tests the state attributes properly match the light types.""" """Tests the state attributes properly match the light types."""
await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices) await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices)
@ -103,7 +104,9 @@ async def test_entity_state(hass, light_devices):
assert state.attributes[ATTR_COLOR_TEMP] == 222 assert state.attributes[ATTR_COLOR_TEMP] == 222
async def test_entity_and_device_attributes(hass, device_factory): async def test_entity_and_device_attributes(
hass: HomeAssistant, device_factory
) -> None:
"""Test the attributes of the entity are correct.""" """Test the attributes of the entity are correct."""
# Arrange # Arrange
device = device_factory("Light 1", [Capability.switch, Capability.switch_level]) device = device_factory("Light 1", [Capability.switch, Capability.switch_level])
@ -125,7 +128,7 @@ async def test_entity_and_device_attributes(hass, device_factory):
assert entry.manufacturer == "Unavailable" assert entry.manufacturer == "Unavailable"
async def test_turn_off(hass, light_devices): async def test_turn_off(hass: HomeAssistant, light_devices) -> None:
"""Test the light turns of successfully.""" """Test the light turns of successfully."""
# Arrange # Arrange
await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices) await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices)
@ -139,7 +142,7 @@ async def test_turn_off(hass, light_devices):
assert state.state == "off" assert state.state == "off"
async def test_turn_off_with_transition(hass, light_devices): async def test_turn_off_with_transition(hass: HomeAssistant, light_devices) -> None:
"""Test the light turns of successfully with transition.""" """Test the light turns of successfully with transition."""
# Arrange # Arrange
await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices) await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices)
@ -156,7 +159,7 @@ async def test_turn_off_with_transition(hass, light_devices):
assert state.state == "off" assert state.state == "off"
async def test_turn_on(hass, light_devices): async def test_turn_on(hass: HomeAssistant, light_devices) -> None:
"""Test the light turns of successfully.""" """Test the light turns of successfully."""
# Arrange # Arrange
await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices) await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices)
@ -170,7 +173,7 @@ async def test_turn_on(hass, light_devices):
assert state.state == "on" assert state.state == "on"
async def test_turn_on_with_brightness(hass, light_devices): async def test_turn_on_with_brightness(hass: HomeAssistant, light_devices) -> None:
"""Test the light turns on to the specified brightness.""" """Test the light turns on to the specified brightness."""
# Arrange # Arrange
await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices) await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices)
@ -193,7 +196,9 @@ async def test_turn_on_with_brightness(hass, light_devices):
assert state.attributes[ATTR_BRIGHTNESS] == 74 assert state.attributes[ATTR_BRIGHTNESS] == 74
async def test_turn_on_with_minimal_brightness(hass, light_devices): async def test_turn_on_with_minimal_brightness(
hass: HomeAssistant, light_devices
) -> None:
"""Test lights set to lowest brightness when converted scale would be zero. """Test lights set to lowest brightness when converted scale would be zero.
SmartThings light brightness is a percentage (0-100), but Home Assistant uses a SmartThings light brightness is a percentage (0-100), but Home Assistant uses a
@ -217,7 +222,7 @@ async def test_turn_on_with_minimal_brightness(hass, light_devices):
assert state.attributes[ATTR_BRIGHTNESS] == 3 assert state.attributes[ATTR_BRIGHTNESS] == 3
async def test_turn_on_with_color(hass, light_devices): async def test_turn_on_with_color(hass: HomeAssistant, light_devices) -> None:
"""Test the light turns on with color.""" """Test the light turns on with color."""
# Arrange # Arrange
await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices) await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices)
@ -235,7 +240,7 @@ async def test_turn_on_with_color(hass, light_devices):
assert state.attributes[ATTR_HS_COLOR] == (180, 50) assert state.attributes[ATTR_HS_COLOR] == (180, 50)
async def test_turn_on_with_color_temp(hass, light_devices): async def test_turn_on_with_color_temp(hass: HomeAssistant, light_devices) -> None:
"""Test the light turns on with color temp.""" """Test the light turns on with color temp."""
# Arrange # Arrange
await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices) await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices)
@ -253,7 +258,7 @@ async def test_turn_on_with_color_temp(hass, light_devices):
assert state.attributes[ATTR_COLOR_TEMP] == 300 assert state.attributes[ATTR_COLOR_TEMP] == 300
async def test_update_from_signal(hass, device_factory): async def test_update_from_signal(hass: HomeAssistant, device_factory) -> None:
"""Test the light updates when receiving a signal.""" """Test the light updates when receiving a signal."""
# Arrange # Arrange
device = device_factory( device = device_factory(
@ -283,7 +288,7 @@ async def test_update_from_signal(hass, device_factory):
assert state.state == "on" assert state.state == "on"
async def test_unload_config_entry(hass, device_factory): async def test_unload_config_entry(hass: HomeAssistant, device_factory) -> None:
"""Test the light is removed when the config entry is unloaded.""" """Test the light is removed when the config entry is unloaded."""
# Arrange # Arrange
device = device_factory( device = device_factory(

View file

@ -10,13 +10,16 @@ from homeassistant.components.lock import DOMAIN as LOCK_DOMAIN
from homeassistant.components.smartthings.const import DOMAIN, SIGNAL_SMARTTHINGS_UPDATE from homeassistant.components.smartthings.const import DOMAIN, SIGNAL_SMARTTHINGS_UPDATE
from homeassistant.config_entries import ConfigEntryState from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.dispatcher import async_dispatcher_send
from .conftest import setup_platform from .conftest import setup_platform
async def test_entity_and_device_attributes(hass, device_factory): async def test_entity_and_device_attributes(
hass: HomeAssistant, device_factory
) -> None:
"""Test the attributes of the entity are correct.""" """Test the attributes of the entity are correct."""
# Arrange # Arrange
device = device_factory("Lock_1", [Capability.lock], {Attribute.lock: "unlocked"}) device = device_factory("Lock_1", [Capability.lock], {Attribute.lock: "unlocked"})
@ -38,7 +41,7 @@ async def test_entity_and_device_attributes(hass, device_factory):
assert entry.manufacturer == "Unavailable" assert entry.manufacturer == "Unavailable"
async def test_lock(hass, device_factory): async def test_lock(hass: HomeAssistant, device_factory) -> None:
"""Test the lock locks successfully.""" """Test the lock locks successfully."""
# Arrange # Arrange
device = device_factory("Lock_1", [Capability.lock]) device = device_factory("Lock_1", [Capability.lock])
@ -70,7 +73,7 @@ async def test_lock(hass, device_factory):
assert "code_id" not in state.attributes assert "code_id" not in state.attributes
async def test_unlock(hass, device_factory): async def test_unlock(hass: HomeAssistant, device_factory) -> None:
"""Test the lock unlocks successfully.""" """Test the lock unlocks successfully."""
# Arrange # Arrange
device = device_factory("Lock_1", [Capability.lock], {Attribute.lock: "locked"}) device = device_factory("Lock_1", [Capability.lock], {Attribute.lock: "locked"})
@ -85,7 +88,7 @@ async def test_unlock(hass, device_factory):
assert state.state == "unlocked" assert state.state == "unlocked"
async def test_update_from_signal(hass, device_factory): async def test_update_from_signal(hass: HomeAssistant, device_factory) -> None:
"""Test the lock updates when receiving a signal.""" """Test the lock updates when receiving a signal."""
# Arrange # Arrange
device = device_factory("Lock_1", [Capability.lock], {Attribute.lock: "unlocked"}) device = device_factory("Lock_1", [Capability.lock], {Attribute.lock: "unlocked"})
@ -100,7 +103,7 @@ async def test_update_from_signal(hass, device_factory):
assert state.state == "locked" assert state.state == "locked"
async def test_unload_config_entry(hass, device_factory): async def test_unload_config_entry(hass: HomeAssistant, device_factory) -> None:
"""Test the lock is removed when the config entry is unloaded.""" """Test the lock is removed when the config entry is unloaded."""
# Arrange # Arrange
device = device_factory("Lock_1", [Capability.lock], {Attribute.lock: "locked"}) device = device_factory("Lock_1", [Capability.lock], {Attribute.lock: "locked"})

View file

@ -6,12 +6,13 @@ real HTTP calls are not initiated during testing.
from homeassistant.components.scene import DOMAIN as SCENE_DOMAIN from homeassistant.components.scene import DOMAIN as SCENE_DOMAIN
from homeassistant.config_entries import ConfigEntryState from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_ON, STATE_UNAVAILABLE from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_ON, STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from .conftest import setup_platform from .conftest import setup_platform
async def test_entity_and_device_attributes(hass, scene): async def test_entity_and_device_attributes(hass: HomeAssistant, scene) -> None:
"""Test the attributes of the entity are correct.""" """Test the attributes of the entity are correct."""
# Arrange # Arrange
entity_registry = er.async_get(hass) entity_registry = er.async_get(hass)
@ -23,7 +24,7 @@ async def test_entity_and_device_attributes(hass, scene):
assert entry.unique_id == scene.scene_id assert entry.unique_id == scene.scene_id
async def test_scene_activate(hass, scene): async def test_scene_activate(hass: HomeAssistant, scene) -> None:
"""Test the scene is activated.""" """Test the scene is activated."""
await setup_platform(hass, SCENE_DOMAIN, scenes=[scene]) await setup_platform(hass, SCENE_DOMAIN, scenes=[scene])
await hass.services.async_call( await hass.services.async_call(
@ -39,7 +40,7 @@ async def test_scene_activate(hass, scene):
assert scene.execute.call_count == 1 # type: ignore assert scene.execute.call_count == 1 # type: ignore
async def test_unload_config_entry(hass, scene): async def test_unload_config_entry(hass: HomeAssistant, scene) -> None:
"""Test the scene is removed when the config entry is unloaded.""" """Test the scene is removed when the config entry is unloaded."""
# Arrange # Arrange
config_entry = await setup_platform(hass, SCENE_DOMAIN, scenes=[scene]) config_entry = await setup_platform(hass, SCENE_DOMAIN, scenes=[scene])

View file

@ -21,6 +21,7 @@ from homeassistant.const import (
STATE_UNKNOWN, STATE_UNKNOWN,
EntityCategory, EntityCategory,
) )
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.dispatcher import async_dispatcher_send
@ -41,7 +42,7 @@ async def test_mapping_integrity() -> None:
assert sensor_map.state_class in STATE_CLASSES, sensor_map.state_class assert sensor_map.state_class in STATE_CLASSES, sensor_map.state_class
async def test_entity_state(hass, device_factory): async def test_entity_state(hass: HomeAssistant, device_factory) -> None:
"""Tests the state attributes properly match the sensor types.""" """Tests the state attributes properly match the sensor types."""
device = device_factory("Sensor 1", [Capability.battery], {Attribute.battery: 100}) device = device_factory("Sensor 1", [Capability.battery], {Attribute.battery: 100})
await setup_platform(hass, SENSOR_DOMAIN, devices=[device]) await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
@ -51,7 +52,7 @@ async def test_entity_state(hass, device_factory):
assert state.attributes[ATTR_FRIENDLY_NAME] == f"{device.label} Battery" assert state.attributes[ATTR_FRIENDLY_NAME] == f"{device.label} Battery"
async def test_entity_three_axis_state(hass, device_factory): async def test_entity_three_axis_state(hass: HomeAssistant, device_factory) -> None:
"""Tests the state attributes properly match the three axis types.""" """Tests the state attributes properly match the three axis types."""
device = device_factory( device = device_factory(
"Three Axis", [Capability.three_axis], {Attribute.three_axis: [100, 75, 25]} "Three Axis", [Capability.three_axis], {Attribute.three_axis: [100, 75, 25]}
@ -68,7 +69,9 @@ async def test_entity_three_axis_state(hass, device_factory):
assert state.attributes[ATTR_FRIENDLY_NAME] == f"{device.label} Z Coordinate" assert state.attributes[ATTR_FRIENDLY_NAME] == f"{device.label} Z Coordinate"
async def test_entity_three_axis_invalid_state(hass, device_factory): async def test_entity_three_axis_invalid_state(
hass: HomeAssistant, device_factory
) -> None:
"""Tests the state attributes properly match the three axis types.""" """Tests the state attributes properly match the three axis types."""
device = device_factory( device = device_factory(
"Three Axis", [Capability.three_axis], {Attribute.three_axis: []} "Three Axis", [Capability.three_axis], {Attribute.three_axis: []}
@ -82,7 +85,9 @@ async def test_entity_three_axis_invalid_state(hass, device_factory):
assert state.state == STATE_UNKNOWN assert state.state == STATE_UNKNOWN
async def test_entity_and_device_attributes(hass, device_factory): async def test_entity_and_device_attributes(
hass: HomeAssistant, device_factory
) -> None:
"""Test the attributes of the entity are correct.""" """Test the attributes of the entity are correct."""
# Arrange # Arrange
device = device_factory("Sensor 1", [Capability.battery], {Attribute.battery: 100}) device = device_factory("Sensor 1", [Capability.battery], {Attribute.battery: 100})
@ -104,7 +109,9 @@ async def test_entity_and_device_attributes(hass, device_factory):
assert entry.manufacturer == "Unavailable" assert entry.manufacturer == "Unavailable"
async def test_energy_sensors_for_switch_device(hass, device_factory): async def test_energy_sensors_for_switch_device(
hass: HomeAssistant, device_factory
) -> None:
"""Test the attributes of the entity are correct.""" """Test the attributes of the entity are correct."""
# Arrange # Arrange
device = device_factory( device = device_factory(
@ -148,7 +155,7 @@ async def test_energy_sensors_for_switch_device(hass, device_factory):
assert entry.manufacturer == "Unavailable" assert entry.manufacturer == "Unavailable"
async def test_power_consumption_sensor(hass, device_factory): async def test_power_consumption_sensor(hass: HomeAssistant, device_factory) -> None:
"""Test the attributes of the entity are correct.""" """Test the attributes of the entity are correct."""
# Arrange # Arrange
device = device_factory( device = device_factory(
@ -227,7 +234,7 @@ async def test_power_consumption_sensor(hass, device_factory):
assert entry.manufacturer == "Unavailable" assert entry.manufacturer == "Unavailable"
async def test_update_from_signal(hass, device_factory): async def test_update_from_signal(hass: HomeAssistant, device_factory) -> None:
"""Test the binary_sensor updates when receiving a signal.""" """Test the binary_sensor updates when receiving a signal."""
# Arrange # Arrange
device = device_factory("Sensor 1", [Capability.battery], {Attribute.battery: 100}) device = device_factory("Sensor 1", [Capability.battery], {Attribute.battery: 100})
@ -244,7 +251,7 @@ async def test_update_from_signal(hass, device_factory):
assert state.state == "75" assert state.state == "75"
async def test_unload_config_entry(hass, device_factory): async def test_unload_config_entry(hass: HomeAssistant, device_factory) -> None:
"""Test the binary_sensor is removed when the config entry is unloaded.""" """Test the binary_sensor is removed when the config entry is unloaded."""
# Arrange # Arrange
device = device_factory("Sensor 1", [Capability.battery], {Attribute.battery: 100}) device = device_factory("Sensor 1", [Capability.battery], {Attribute.battery: 100})

View file

@ -3,6 +3,7 @@ from unittest.mock import AsyncMock, Mock, patch
from uuid import uuid4 from uuid import uuid4
from pysmartthings import CAPABILITIES, AppEntity, Capability from pysmartthings import CAPABILITIES, AppEntity, Capability
import pytest
from homeassistant.components.smartthings import smartapp from homeassistant.components.smartthings import smartapp
from homeassistant.components.smartthings.const import ( from homeassistant.components.smartthings.const import (
@ -15,13 +16,13 @@ from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
async def test_update_app(hass, app): async def test_update_app(hass: HomeAssistant, app) -> None:
"""Test update_app does not save if app is current.""" """Test update_app does not save if app is current."""
await smartapp.update_app(hass, app) await smartapp.update_app(hass, app)
assert app.save.call_count == 0 assert app.save.call_count == 0
async def test_update_app_updated_needed(hass, app): async def test_update_app_updated_needed(hass: HomeAssistant, app) -> None:
"""Test update_app updates when an app is needed.""" """Test update_app updates when an app is needed."""
mock_app = Mock(AppEntity) mock_app = Mock(AppEntity)
mock_app.app_name = "Test" mock_app.app_name = "Test"
@ -39,8 +40,8 @@ async def test_update_app_updated_needed(hass, app):
async def test_smartapp_update_saves_token( async def test_smartapp_update_saves_token(
hass, smartthings_mock, location, device_factory hass: HomeAssistant, smartthings_mock, location, device_factory
): ) -> None:
"""Test update saves token.""" """Test update saves token."""
# Arrange # Arrange
entry = MockConfigEntry( entry = MockConfigEntry(
@ -61,7 +62,7 @@ async def test_smartapp_update_saves_token(
assert entry.data[CONF_REFRESH_TOKEN] == request.refresh_token assert entry.data[CONF_REFRESH_TOKEN] == request.refresh_token
async def test_smartapp_uninstall(hass, config_entry): async def test_smartapp_uninstall(hass: HomeAssistant, config_entry) -> None:
"""Test the config entry is unloaded when the app is uninstalled.""" """Test the config entry is unloaded when the app is uninstalled."""
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
app = Mock() app = Mock()
@ -88,8 +89,8 @@ async def test_smartapp_webhook(hass: HomeAssistant) -> None:
async def test_smartapp_sync_subscriptions( async def test_smartapp_sync_subscriptions(
hass, smartthings_mock, device_factory, subscription_factory hass: HomeAssistant, smartthings_mock, device_factory, subscription_factory
): ) -> None:
"""Test synchronization adds and removes and ignores unused.""" """Test synchronization adds and removes and ignores unused."""
smartthings_mock.subscriptions.return_value = [ smartthings_mock.subscriptions.return_value = [
subscription_factory(Capability.thermostat), subscription_factory(Capability.thermostat),
@ -112,8 +113,8 @@ async def test_smartapp_sync_subscriptions(
async def test_smartapp_sync_subscriptions_up_to_date( async def test_smartapp_sync_subscriptions_up_to_date(
hass, smartthings_mock, device_factory, subscription_factory hass: HomeAssistant, smartthings_mock, device_factory, subscription_factory
): ) -> None:
"""Test synchronization does nothing when current.""" """Test synchronization does nothing when current."""
smartthings_mock.subscriptions.return_value = [ smartthings_mock.subscriptions.return_value = [
subscription_factory(Capability.battery), subscription_factory(Capability.battery),
@ -136,8 +137,12 @@ async def test_smartapp_sync_subscriptions_up_to_date(
async def test_smartapp_sync_subscriptions_limit_warning( async def test_smartapp_sync_subscriptions_limit_warning(
hass, smartthings_mock, device_factory, subscription_factory, caplog hass: HomeAssistant,
): smartthings_mock,
device_factory,
subscription_factory,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test synchronization over the limit logs a warning.""" """Test synchronization over the limit logs a warning."""
smartthings_mock.subscriptions.return_value = [] smartthings_mock.subscriptions.return_value = []
devices = [ devices = [
@ -155,8 +160,8 @@ async def test_smartapp_sync_subscriptions_limit_warning(
async def test_smartapp_sync_subscriptions_handles_exceptions( async def test_smartapp_sync_subscriptions_handles_exceptions(
hass, smartthings_mock, device_factory, subscription_factory hass: HomeAssistant, smartthings_mock, device_factory, subscription_factory
): ) -> None:
"""Test synchronization does nothing when current.""" """Test synchronization does nothing when current."""
smartthings_mock.delete_subscription.side_effect = Exception smartthings_mock.delete_subscription.side_effect = Exception
smartthings_mock.create_subscription.side_effect = Exception smartthings_mock.create_subscription.side_effect = Exception

View file

@ -9,13 +9,16 @@ from homeassistant.components.smartthings.const import DOMAIN, SIGNAL_SMARTTHING
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.config_entries import ConfigEntryState from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.dispatcher import async_dispatcher_send
from .conftest import setup_platform from .conftest import setup_platform
async def test_entity_and_device_attributes(hass, device_factory): async def test_entity_and_device_attributes(
hass: HomeAssistant, device_factory
) -> None:
"""Test the attributes of the entity are correct.""" """Test the attributes of the entity are correct."""
# Arrange # Arrange
device = device_factory("Switch_1", [Capability.switch], {Attribute.switch: "on"}) device = device_factory("Switch_1", [Capability.switch], {Attribute.switch: "on"})
@ -37,7 +40,7 @@ async def test_entity_and_device_attributes(hass, device_factory):
assert entry.manufacturer == "Unavailable" assert entry.manufacturer == "Unavailable"
async def test_turn_off(hass, device_factory): async def test_turn_off(hass: HomeAssistant, device_factory) -> None:
"""Test the switch turns of successfully.""" """Test the switch turns of successfully."""
# Arrange # Arrange
device = device_factory("Switch_1", [Capability.switch], {Attribute.switch: "on"}) device = device_factory("Switch_1", [Capability.switch], {Attribute.switch: "on"})
@ -52,7 +55,7 @@ async def test_turn_off(hass, device_factory):
assert state.state == "off" assert state.state == "off"
async def test_turn_on(hass, device_factory): async def test_turn_on(hass: HomeAssistant, device_factory) -> None:
"""Test the switch turns of successfully.""" """Test the switch turns of successfully."""
# Arrange # Arrange
device = device_factory( device = device_factory(
@ -71,7 +74,7 @@ async def test_turn_on(hass, device_factory):
assert state.state == "on" assert state.state == "on"
async def test_update_from_signal(hass, device_factory): async def test_update_from_signal(hass: HomeAssistant, device_factory) -> None:
"""Test the switch updates when receiving a signal.""" """Test the switch updates when receiving a signal."""
# Arrange # Arrange
device = device_factory("Switch_1", [Capability.switch], {Attribute.switch: "off"}) device = device_factory("Switch_1", [Capability.switch], {Attribute.switch: "off"})
@ -86,7 +89,7 @@ async def test_update_from_signal(hass, device_factory):
assert state.state == "on" assert state.state == "on"
async def test_unload_config_entry(hass, device_factory): async def test_unload_config_entry(hass: HomeAssistant, device_factory) -> None:
"""Test the switch is removed when the config entry is unloaded.""" """Test the switch is removed when the config entry is unloaded."""
# Arrange # Arrange
device = device_factory("Switch 1", [Capability.switch], {Attribute.switch: "on"}) device = device_factory("Switch 1", [Capability.switch], {Attribute.switch: "on"})

View file

@ -6,9 +6,10 @@ import pytest
import smarttub import smarttub
from homeassistant.components.binary_sensor import STATE_OFF, STATE_ON from homeassistant.components.binary_sensor import STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
async def test_binary_sensors(spa, setup_entry, hass): async def test_binary_sensors(spa, setup_entry, hass: HomeAssistant) -> None:
"""Test simple binary sensors.""" """Test simple binary sensors."""
entity_id = f"binary_sensor.{spa.brand}_{spa.model}_online" entity_id = f"binary_sensor.{spa.brand}_{spa.model}_online"
@ -22,7 +23,7 @@ async def test_binary_sensors(spa, setup_entry, hass):
assert state.state == STATE_OFF assert state.state == STATE_OFF
async def test_reminders(spa, setup_entry, hass): async def test_reminders(spa, setup_entry, hass: HomeAssistant) -> None:
"""Test the reminder sensor.""" """Test the reminder sensor."""
entity_id = f"binary_sensor.{spa.brand}_{spa.model}_myfilter_reminder" entity_id = f"binary_sensor.{spa.brand}_{spa.model}_myfilter_reminder"
@ -47,7 +48,7 @@ def mock_error(spa):
return error return error
async def test_error(spa, hass, config_entry, mock_error): async def test_error(spa, hass: HomeAssistant, config_entry, mock_error) -> None:
"""Test the error sensor.""" """Test the error sensor."""
spa.get_errors.return_value = [mock_error] spa.get_errors.return_value = [mock_error]
@ -64,7 +65,7 @@ async def test_error(spa, hass, config_entry, mock_error):
assert state.attributes["error_code"] == 11 assert state.attributes["error_code"] == 11
async def test_snooze_reminder(spa, setup_entry, hass): async def test_snooze_reminder(spa, setup_entry, hass: HomeAssistant) -> None:
"""Test snoozing a reminder.""" """Test snoozing a reminder."""
entity_id = f"binary_sensor.{spa.brand}_{spa.model}_myfilter_reminder" entity_id = f"binary_sensor.{spa.brand}_{spa.model}_myfilter_reminder"
@ -84,7 +85,7 @@ async def test_snooze_reminder(spa, setup_entry, hass):
reminder.snooze.assert_called_with(days) reminder.snooze.assert_called_with(days)
async def test_reset_reminder(spa, setup_entry, hass): async def test_reset_reminder(spa, setup_entry, hass: HomeAssistant) -> None:
"""Test snoozing a reminder.""" """Test snoozing a reminder."""
entity_id = f"binary_sensor.{spa.brand}_{spa.model}_myfilter_reminder" entity_id = f"binary_sensor.{spa.brand}_{spa.model}_myfilter_reminder"

View file

@ -26,11 +26,14 @@ from homeassistant.const import (
ATTR_SUPPORTED_FEATURES, ATTR_SUPPORTED_FEATURES,
ATTR_TEMPERATURE, ATTR_TEMPERATURE,
) )
from homeassistant.core import HomeAssistant
from . import trigger_update from . import trigger_update
async def test_thermostat_update(spa, spa_state, setup_entry, hass): async def test_thermostat_update(
spa, spa_state, setup_entry, hass: HomeAssistant
) -> None:
"""Test the thermostat entity.""" """Test the thermostat entity."""
entity_id = f"climate.{spa.brand}_{spa.model}_thermostat" entity_id = f"climate.{spa.brand}_{spa.model}_thermostat"

View file

@ -38,7 +38,7 @@ async def test_form(hass: HomeAssistant) -> None:
mock_setup_entry.assert_called_once() mock_setup_entry.assert_called_once()
async def test_form_invalid_auth(hass, smarttub_api): async def test_form_invalid_auth(hass: HomeAssistant, smarttub_api) -> 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}
@ -55,7 +55,7 @@ async def test_form_invalid_auth(hass, smarttub_api):
assert result["errors"] == {"base": "invalid_auth"} assert result["errors"] == {"base": "invalid_auth"}
async def test_reauth_success(hass, smarttub_api, account): async def test_reauth_success(hass: HomeAssistant, smarttub_api, account) -> None:
"""Test reauthentication flow.""" """Test reauthentication flow."""
mock_entry = MockConfigEntry( mock_entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,
@ -87,7 +87,7 @@ async def test_reauth_success(hass, smarttub_api, account):
assert mock_entry.data[CONF_PASSWORD] == "test-password3" assert mock_entry.data[CONF_PASSWORD] == "test-password3"
async def test_reauth_wrong_account(hass, smarttub_api, account): async def test_reauth_wrong_account(hass: HomeAssistant, smarttub_api, account) -> None:
"""Test reauthentication flow if the user enters credentials for a different already-configured account.""" """Test reauthentication flow if the user enters credentials for a different already-configured account."""
mock_entry1 = MockConfigEntry( mock_entry1 = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,

View file

@ -1,5 +1,4 @@
"""Test smarttub setup process.""" """Test smarttub setup process."""
import asyncio import asyncio
from unittest.mock import patch from unittest.mock import patch
@ -8,10 +7,13 @@ from smarttub import LoginFailed
from homeassistant.components import smarttub from homeassistant.components import smarttub
from homeassistant.components.smarttub.const import DOMAIN from homeassistant.components.smarttub.const import DOMAIN
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
async def test_setup_with_no_config(setup_component, hass, smarttub_api): async def test_setup_with_no_config(
setup_component, hass: HomeAssistant, smarttub_api
) -> None:
"""Test that we do not discover anything.""" """Test that we do not discover anything."""
# No flows started # No flows started
@ -20,7 +22,9 @@ async def test_setup_with_no_config(setup_component, hass, smarttub_api):
smarttub_api.login.assert_not_called() smarttub_api.login.assert_not_called()
async def test_setup_entry_not_ready(setup_component, hass, config_entry, smarttub_api): async def test_setup_entry_not_ready(
setup_component, hass: HomeAssistant, config_entry, smarttub_api
) -> None:
"""Test setup when the entry is not ready.""" """Test setup when the entry is not ready."""
smarttub_api.login.side_effect = asyncio.TimeoutError smarttub_api.login.side_effect = asyncio.TimeoutError
@ -29,7 +33,9 @@ async def test_setup_entry_not_ready(setup_component, hass, config_entry, smartt
assert config_entry.state is ConfigEntryState.SETUP_RETRY assert config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_setup_auth_failed(setup_component, hass, config_entry, smarttub_api): async def test_setup_auth_failed(
setup_component, hass: HomeAssistant, config_entry, smarttub_api
) -> None:
"""Test setup when the credentials are invalid.""" """Test setup when the credentials are invalid."""
smarttub_api.login.side_effect = LoginFailed smarttub_api.login.side_effect = LoginFailed
@ -49,13 +55,15 @@ async def test_setup_auth_failed(setup_component, hass, config_entry, smarttub_a
) )
async def test_config_passed_to_config_entry(hass, config_entry, config_data): async def test_config_passed_to_config_entry(
hass: HomeAssistant, config_entry, config_data
) -> None:
"""Test that configured options are loaded via config entry.""" """Test that configured options are loaded via config entry."""
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
assert await async_setup_component(hass, smarttub.DOMAIN, config_data) assert await async_setup_component(hass, smarttub.DOMAIN, config_data)
async def test_unload_entry(hass, config_entry): async def test_unload_entry(hass: HomeAssistant, config_entry) -> None:
"""Test being able to unload an entry.""" """Test being able to unload an entry."""
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)

View file

@ -1,8 +1,9 @@
"""Test the SmartTub light platform.""" """Test the SmartTub light platform."""
import pytest import pytest
from smarttub import SpaLight from smarttub import SpaLight
from homeassistant.core import HomeAssistant
# the light in light_zone should have initial state light_state. we will call # the light in light_zone should have initial state light_state. we will call
# service_name with service_params, and expect the resultant call to # service_name with service_params, and expect the resultant call to
@ -18,13 +19,13 @@ from smarttub import SpaLight
async def test_light( async def test_light(
spa, spa,
setup_entry, setup_entry,
hass, hass: HomeAssistant,
light_zone, light_zone,
light_state, light_state,
service_name, service_name,
service_params, service_params,
set_mode_args, set_mode_args,
): ) -> None:
"""Test light entity.""" """Test light entity."""
entity_id = f"light.{spa.brand}_{spa.model}_light_{light_zone}" entity_id = f"light.{spa.brand}_{spa.model}_light_{light_zone}"

View file

@ -1,8 +1,9 @@
"""Test the SmartTub sensor platform.""" """Test the SmartTub sensor platform."""
import pytest import pytest
import smarttub import smarttub
from homeassistant.core import HomeAssistant
@pytest.mark.parametrize( @pytest.mark.parametrize(
("entity_suffix", "expected_state"), ("entity_suffix", "expected_state"),
@ -15,7 +16,9 @@ import smarttub
("cleanup_cycle", "inactive"), ("cleanup_cycle", "inactive"),
], ],
) )
async def test_sensor(spa, setup_entry, hass, entity_suffix, expected_state): async def test_sensor(
spa, setup_entry, hass: HomeAssistant, entity_suffix, expected_state
) -> None:
"""Test simple sensors.""" """Test simple sensors."""
entity_id = f"sensor.{spa.brand}_{spa.model}_{entity_suffix}" entity_id = f"sensor.{spa.brand}_{spa.model}_{entity_suffix}"
@ -24,7 +27,9 @@ async def test_sensor(spa, setup_entry, hass, entity_suffix, expected_state):
assert state.state == expected_state assert state.state == expected_state
async def test_primary_filtration(spa, spa_state, setup_entry, hass): async def test_primary_filtration(
spa, spa_state, setup_entry, hass: HomeAssistant
) -> None:
"""Test the primary filtration cycle sensor.""" """Test the primary filtration cycle sensor."""
entity_id = f"sensor.{spa.brand}_{spa.model}_primary_filtration_cycle" entity_id = f"sensor.{spa.brand}_{spa.model}_primary_filtration_cycle"
@ -45,7 +50,9 @@ async def test_primary_filtration(spa, spa_state, setup_entry, hass):
spa_state.primary_filtration.set.assert_called_with(duration=8, start_hour=1) spa_state.primary_filtration.set.assert_called_with(duration=8, start_hour=1)
async def test_secondary_filtration(spa, spa_state, setup_entry, hass): async def test_secondary_filtration(
spa, spa_state, setup_entry, hass: HomeAssistant
) -> None:
"""Test the secondary filtration cycle sensor.""" """Test the secondary filtration cycle sensor."""
entity_id = f"sensor.{spa.brand}_{spa.model}_secondary_filtration_cycle" entity_id = f"sensor.{spa.brand}_{spa.model}_secondary_filtration_cycle"

View file

@ -1,8 +1,8 @@
"""Test the SmartTub switch platform.""" """Test the SmartTub switch platform."""
import pytest import pytest
from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
@pytest.mark.parametrize( @pytest.mark.parametrize(
@ -13,7 +13,9 @@ from homeassistant.const import STATE_OFF, STATE_ON
("P2", "jet_p2", "on"), ("P2", "jet_p2", "on"),
], ],
) )
async def test_pumps(spa, setup_entry, hass, pump_id, pump_state, entity_suffix): async def test_pumps(
spa, setup_entry, hass: HomeAssistant, pump_id, pump_state, entity_suffix
) -> None:
"""Test pump entities.""" """Test pump entities."""
status = await spa.get_status_full() status = await spa.get_status_full()

View file

@ -131,7 +131,9 @@ EMAIL_DATA = [
"Tests when image type cannot be detected or is of wrong type.", "Tests when image type cannot be detected or is of wrong type.",
], ],
) )
def test_send_message(message_data, data, content_type, hass, message): def test_send_message(
message_data, data, content_type, hass: HomeAssistant, message
) -> None:
"""Verify if we can send messages of all types correctly.""" """Verify if we can send messages of all types correctly."""
sample_email = "<mock@mock>" sample_email = "<mock@mock>"
with patch("email.utils.make_msgid", return_value=sample_email): with patch("email.utils.make_msgid", return_value=sample_email):
@ -139,7 +141,7 @@ def test_send_message(message_data, data, content_type, hass, message):
assert content_type in result assert content_type in result
def test_send_text_message(hass, message): def test_send_text_message(hass: HomeAssistant, message) -> None:
"""Verify if we can send simple text message.""" """Verify if we can send simple text message."""
expected = ( expected = (
'^Content-Type: text/plain; charset="us-ascii"\n' '^Content-Type: text/plain; charset="us-ascii"\n'
@ -172,7 +174,7 @@ def test_send_text_message(hass, message):
"Verify email recipient can be overwritten by target arg.", "Verify email recipient can be overwritten by target arg.",
], ],
) )
def test_send_target_message(target, hass, message): def test_send_target_message(target, hass: HomeAssistant, message) -> None:
"""Verify if we can send email to correct recipient.""" """Verify if we can send email to correct recipient."""
sample_email = "<mock@mock>" sample_email = "<mock@mock>"
message_data = "Test msg" message_data = "Test msg"

View file

@ -11,9 +11,10 @@ from homeassistant.core import HomeAssistant
from homeassistant.helpers.intent import ServiceIntentHandler, async_register from homeassistant.helpers.intent import ServiceIntentHandler, async_register
from tests.common import async_fire_mqtt_message, async_mock_intent, async_mock_service from tests.common import async_fire_mqtt_message, async_mock_intent, async_mock_service
from tests.typing import MqttMockHAClient
async def test_snips_config(hass, mqtt_mock): async def test_snips_config(hass: HomeAssistant, mqtt_mock: MqttMockHAClient) -> None:
"""Test Snips Config.""" """Test Snips Config."""
result = await async_setup_component( result = await async_setup_component(
hass, hass,
@ -48,7 +49,9 @@ async def test_snips_no_mqtt(
assert "MQTT integration is not available" in caplog.text assert "MQTT integration is not available" in caplog.text
async def test_snips_bad_config(hass, mqtt_mock): async def test_snips_bad_config(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test Snips bad config.""" """Test Snips bad config."""
result = await async_setup_component( result = await async_setup_component(
hass, hass,
@ -64,7 +67,9 @@ async def test_snips_bad_config(hass, mqtt_mock):
assert not result assert not result
async def test_snips_config_feedback_on(hass, mqtt_mock): async def test_snips_config_feedback_on(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test Snips Config.""" """Test Snips Config."""
result = await async_setup_component( result = await async_setup_component(
hass, "snips", {"snips": {"feedback_sounds": True}} hass, "snips", {"snips": {"feedback_sounds": True}}
@ -81,7 +86,9 @@ async def test_snips_config_feedback_on(hass, mqtt_mock):
assert mqtt_mock.async_publish.call_args_list[1][0][3] assert mqtt_mock.async_publish.call_args_list[1][0][3]
async def test_snips_config_feedback_off(hass, mqtt_mock): async def test_snips_config_feedback_off(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test Snips Config.""" """Test Snips Config."""
result = await async_setup_component( result = await async_setup_component(
hass, "snips", {"snips": {"feedback_sounds": False}} hass, "snips", {"snips": {"feedback_sounds": False}}
@ -98,7 +105,9 @@ async def test_snips_config_feedback_off(hass, mqtt_mock):
assert not mqtt_mock.async_publish.call_args_list[1][0][3] assert not mqtt_mock.async_publish.call_args_list[1][0][3]
async def test_snips_config_no_feedback(hass, mqtt_mock): async def test_snips_config_no_feedback(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test Snips Config.""" """Test Snips Config."""
calls = async_mock_service(hass, "snips", "say") calls = async_mock_service(hass, "snips", "say")
result = await async_setup_component(hass, "snips", {"snips": {}}) result = await async_setup_component(hass, "snips", {"snips": {}})
@ -107,7 +116,7 @@ async def test_snips_config_no_feedback(hass, mqtt_mock):
assert len(calls) == 0 assert len(calls) == 0
async def test_snips_intent(hass, mqtt_mock): async def test_snips_intent(hass: HomeAssistant, mqtt_mock: MqttMockHAClient) -> None:
"""Test intent via Snips.""" """Test intent via Snips."""
result = await async_setup_component(hass, "snips", {"snips": {}}) result = await async_setup_component(hass, "snips", {"snips": {}})
assert result assert result
@ -152,7 +161,9 @@ async def test_snips_intent(hass, mqtt_mock):
assert intent.text_input == "turn the lights green" assert intent.text_input == "turn the lights green"
async def test_snips_service_intent(hass, mqtt_mock): async def test_snips_service_intent(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test ServiceIntentHandler via Snips.""" """Test ServiceIntentHandler via Snips."""
hass.states.async_set("light.kitchen", "off") hass.states.async_set("light.kitchen", "off")
calls = async_mock_service(hass, "light", "turn_on") calls = async_mock_service(hass, "light", "turn_on")
@ -194,7 +205,9 @@ async def test_snips_service_intent(hass, mqtt_mock):
assert "site_id" not in calls[0].data assert "site_id" not in calls[0].data
async def test_snips_intent_with_duration(hass, mqtt_mock): async def test_snips_intent_with_duration(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test intent with Snips duration.""" """Test intent with Snips duration."""
result = await async_setup_component(hass, "snips", {"snips": {}}) result = await async_setup_component(hass, "snips", {"snips": {}})
assert result assert result
@ -247,7 +260,9 @@ async def test_snips_intent_with_duration(hass, mqtt_mock):
} }
async def test_intent_speech_response(hass, mqtt_mock): async def test_intent_speech_response(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test intent speech response via Snips.""" """Test intent speech response via Snips."""
result = await async_setup_component(hass, "snips", {"snips": {}}) result = await async_setup_component(hass, "snips", {"snips": {}})
assert result assert result
@ -285,7 +300,9 @@ async def test_intent_speech_response(hass, mqtt_mock):
assert topic == "hermes/dialogueManager/endSession" assert topic == "hermes/dialogueManager/endSession"
async def test_unknown_intent(hass, caplog, mqtt_mock): async def test_unknown_intent(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, mqtt_mock: MqttMockHAClient
) -> None:
"""Test unknown intent.""" """Test unknown intent."""
caplog.set_level(logging.WARNING) caplog.set_level(logging.WARNING)
result = await async_setup_component(hass, "snips", {"snips": {}}) result = await async_setup_component(hass, "snips", {"snips": {}})
@ -306,7 +323,9 @@ async def test_unknown_intent(hass, caplog, mqtt_mock):
assert "Received unknown intent unknownIntent" in caplog.text assert "Received unknown intent unknownIntent" in caplog.text
async def test_snips_intent_user(hass, mqtt_mock): async def test_snips_intent_user(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test intentName format user_XXX__intentName.""" """Test intentName format user_XXX__intentName."""
result = await async_setup_component(hass, "snips", {"snips": {}}) result = await async_setup_component(hass, "snips", {"snips": {}})
assert result assert result
@ -330,7 +349,9 @@ async def test_snips_intent_user(hass, mqtt_mock):
assert intent.intent_type == "Lights" assert intent.intent_type == "Lights"
async def test_snips_intent_username(hass, mqtt_mock): async def test_snips_intent_username(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test intentName format username:intentName.""" """Test intentName format username:intentName."""
result = await async_setup_component(hass, "snips", {"snips": {}}) result = await async_setup_component(hass, "snips", {"snips": {}})
assert result assert result
@ -354,7 +375,9 @@ async def test_snips_intent_username(hass, mqtt_mock):
assert intent.intent_type == "Lights" assert intent.intent_type == "Lights"
async def test_snips_low_probability(hass, caplog, mqtt_mock): async def test_snips_low_probability(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, mqtt_mock: MqttMockHAClient
) -> None:
"""Test intent via Snips.""" """Test intent via Snips."""
caplog.set_level(logging.WARNING) caplog.set_level(logging.WARNING)
result = await async_setup_component( result = await async_setup_component(
@ -378,7 +401,9 @@ async def test_snips_low_probability(hass, caplog, mqtt_mock):
assert "Intent below probaility threshold 0.49 < 0.5" in caplog.text assert "Intent below probaility threshold 0.49 < 0.5" in caplog.text
async def test_intent_special_slots(hass, mqtt_mock): async def test_intent_special_slots(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test intent special slot values via Snips.""" """Test intent special slot values via Snips."""
calls = async_mock_service(hass, "light", "turn_on") calls = async_mock_service(hass, "light", "turn_on")
result = await async_setup_component(hass, "snips", {"snips": {}}) result = await async_setup_component(hass, "snips", {"snips": {}})

View file

@ -23,7 +23,7 @@ from . import (
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
async def test_async_step_bluetooth_valid_device(hass: HomeAssistant): async def test_async_step_bluetooth_valid_device(hass: HomeAssistant) -> None:
"""Test discovery via bluetooth with a valid device.""" """Test discovery via bluetooth with a valid device."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,
@ -35,7 +35,7 @@ async def test_async_step_bluetooth_valid_device(hass: HomeAssistant):
await _test_setup_entry(hass, result["flow_id"]) await _test_setup_entry(hass, result["flow_id"])
async def test_async_step_bluetooth_waits_to_pair(hass: HomeAssistant): async def test_async_step_bluetooth_waits_to_pair(hass: HomeAssistant) -> None:
"""Test discovery via bluetooth with a device that's not in pairing mode, but enters pairing mode to complete setup.""" """Test discovery via bluetooth with a device that's not in pairing mode, but enters pairing mode to complete setup."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
@ -50,7 +50,7 @@ async def test_async_step_bluetooth_waits_to_pair(hass: HomeAssistant):
await _test_pairs(hass, result["flow_id"]) await _test_pairs(hass, result["flow_id"])
async def test_async_step_bluetooth_retries_pairing(hass: HomeAssistant): async def test_async_step_bluetooth_retries_pairing(hass: HomeAssistant) -> None:
"""Test discovery via bluetooth with a device that's not in pairing mode, times out waiting, but eventually complete setup.""" """Test discovery via bluetooth with a device that's not in pairing mode, times out waiting, but eventually complete setup."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
@ -66,7 +66,7 @@ async def test_async_step_bluetooth_retries_pairing(hass: HomeAssistant):
await _test_pairs(hass, retry_id) await _test_pairs(hass, retry_id)
async def test_async_step_bluetooth_not_snooz(hass: HomeAssistant): async def test_async_step_bluetooth_not_snooz(hass: HomeAssistant) -> None:
"""Test discovery via bluetooth not Snooz.""" """Test discovery via bluetooth not Snooz."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,
@ -77,7 +77,7 @@ async def test_async_step_bluetooth_not_snooz(hass: HomeAssistant):
assert result["reason"] == "not_supported" assert result["reason"] == "not_supported"
async def test_async_step_user_no_devices_found(hass: HomeAssistant): async def test_async_step_user_no_devices_found(hass: HomeAssistant) -> None:
"""Test setup from service info cache with no devices found.""" """Test setup from service info cache with no devices found."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,
@ -87,7 +87,7 @@ async def test_async_step_user_no_devices_found(hass: HomeAssistant):
assert result["reason"] == "no_devices_found" assert result["reason"] == "no_devices_found"
async def test_async_step_user_with_found_devices(hass: HomeAssistant): async def test_async_step_user_with_found_devices(hass: HomeAssistant) -> None:
"""Test setup from service info cache with devices found.""" """Test setup from service info cache with devices found."""
with patch( with patch(
"homeassistant.components.snooz.config_flow.async_discovered_service_info", "homeassistant.components.snooz.config_flow.async_discovered_service_info",
@ -107,7 +107,9 @@ async def test_async_step_user_with_found_devices(hass: HomeAssistant):
) )
async def test_async_step_user_with_found_devices_waits_to_pair(hass: HomeAssistant): async def test_async_step_user_with_found_devices_waits_to_pair(
hass: HomeAssistant,
) -> None:
"""Test setup from service info cache with devices found that require pairing mode.""" """Test setup from service info cache with devices found that require pairing mode."""
with patch( with patch(
"homeassistant.components.snooz.config_flow.async_discovered_service_info", "homeassistant.components.snooz.config_flow.async_discovered_service_info",
@ -123,7 +125,9 @@ async def test_async_step_user_with_found_devices_waits_to_pair(hass: HomeAssist
await _test_pairs(hass, result["flow_id"], {CONF_NAME: TEST_SNOOZ_DISPLAY_NAME}) await _test_pairs(hass, result["flow_id"], {CONF_NAME: TEST_SNOOZ_DISPLAY_NAME})
async def test_async_step_user_with_found_devices_retries_pairing(hass: HomeAssistant): async def test_async_step_user_with_found_devices_retries_pairing(
hass: HomeAssistant,
) -> None:
"""Test setup from service info cache with devices found that require pairing mode, times out, then completes.""" """Test setup from service info cache with devices found that require pairing mode, times out, then completes."""
with patch( with patch(
"homeassistant.components.snooz.config_flow.async_discovered_service_info", "homeassistant.components.snooz.config_flow.async_discovered_service_info",
@ -142,7 +146,7 @@ async def test_async_step_user_with_found_devices_retries_pairing(hass: HomeAssi
await _test_pairs(hass, retry_id, user_input) await _test_pairs(hass, retry_id, user_input)
async def test_async_step_user_device_added_between_steps(hass: HomeAssistant): async def test_async_step_user_device_added_between_steps(hass: HomeAssistant) -> None:
"""Test the device gets added via another flow between steps.""" """Test the device gets added via another flow between steps."""
with patch( with patch(
"homeassistant.components.snooz.config_flow.async_discovered_service_info", "homeassistant.components.snooz.config_flow.async_discovered_service_info",
@ -171,7 +175,9 @@ async def test_async_step_user_device_added_between_steps(hass: HomeAssistant):
assert result2["reason"] == "already_configured" assert result2["reason"] == "already_configured"
async def test_async_step_user_with_found_devices_already_setup(hass: HomeAssistant): async def test_async_step_user_with_found_devices_already_setup(
hass: HomeAssistant,
) -> None:
"""Test setup from service info cache with devices found.""" """Test setup from service info cache with devices found."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,
@ -192,7 +198,7 @@ async def test_async_step_user_with_found_devices_already_setup(hass: HomeAssist
assert result["reason"] == "no_devices_found" assert result["reason"] == "no_devices_found"
async def test_async_step_bluetooth_devices_already_setup(hass: HomeAssistant): async def test_async_step_bluetooth_devices_already_setup(hass: HomeAssistant) -> None:
"""Test we can't start a flow if there is already a config entry.""" """Test we can't start a flow if there is already a config entry."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,
@ -210,7 +216,7 @@ async def test_async_step_bluetooth_devices_already_setup(hass: HomeAssistant):
assert result["reason"] == "already_configured" assert result["reason"] == "already_configured"
async def test_async_step_bluetooth_already_in_progress(hass: HomeAssistant): async def test_async_step_bluetooth_already_in_progress(hass: HomeAssistant) -> None:
"""Test we can't start a flow for the same device twice.""" """Test we can't start a flow for the same device twice."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,
@ -229,7 +235,9 @@ async def test_async_step_bluetooth_already_in_progress(hass: HomeAssistant):
assert result["reason"] == "already_in_progress" assert result["reason"] == "already_in_progress"
async def test_async_step_user_takes_precedence_over_discovery(hass: HomeAssistant): async def test_async_step_user_takes_precedence_over_discovery(
hass: HomeAssistant,
) -> None:
"""Test manual setup takes precedence over discovery.""" """Test manual setup takes precedence over discovery."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,

View file

@ -32,7 +32,7 @@ from homeassistant.helpers import entity_registry
from . import SnoozFixture, create_mock_snooz, create_mock_snooz_config_entry from . import SnoozFixture, create_mock_snooz, create_mock_snooz_config_entry
async def test_turn_on(hass: HomeAssistant, snooz_fan_entity_id: str): async def test_turn_on(hass: HomeAssistant, snooz_fan_entity_id: str) -> None:
"""Test turning on the device.""" """Test turning on the device."""
await hass.services.async_call( await hass.services.async_call(
fan.DOMAIN, fan.DOMAIN,
@ -46,7 +46,7 @@ async def test_turn_on(hass: HomeAssistant, snooz_fan_entity_id: str):
assert ATTR_ASSUMED_STATE not in state.attributes assert ATTR_ASSUMED_STATE not in state.attributes
async def test_transition_on(hass: HomeAssistant, snooz_fan_entity_id: str): async def test_transition_on(hass: HomeAssistant, snooz_fan_entity_id: str) -> None:
"""Test transitioning on the device.""" """Test transitioning on the device."""
await hass.services.async_call( await hass.services.async_call(
DOMAIN, DOMAIN,
@ -63,7 +63,7 @@ async def test_transition_on(hass: HomeAssistant, snooz_fan_entity_id: str):
@pytest.mark.parametrize("percentage", [1, 22, 50, 99, 100]) @pytest.mark.parametrize("percentage", [1, 22, 50, 99, 100])
async def test_turn_on_with_percentage( async def test_turn_on_with_percentage(
hass: HomeAssistant, snooz_fan_entity_id: str, percentage: int hass: HomeAssistant, snooz_fan_entity_id: str, percentage: int
): ) -> None:
"""Test turning on the device with a percentage.""" """Test turning on the device with a percentage."""
await hass.services.async_call( await hass.services.async_call(
fan.DOMAIN, fan.DOMAIN,
@ -81,7 +81,7 @@ async def test_turn_on_with_percentage(
@pytest.mark.parametrize("percentage", [1, 22, 50, 99, 100]) @pytest.mark.parametrize("percentage", [1, 22, 50, 99, 100])
async def test_set_percentage( async def test_set_percentage(
hass: HomeAssistant, snooz_fan_entity_id: str, percentage: int hass: HomeAssistant, snooz_fan_entity_id: str, percentage: int
): ) -> None:
"""Test setting the fan percentage.""" """Test setting the fan percentage."""
await hass.services.async_call( await hass.services.async_call(
fan.DOMAIN, fan.DOMAIN,
@ -97,7 +97,7 @@ async def test_set_percentage(
async def test_set_0_percentage_turns_off( async def test_set_0_percentage_turns_off(
hass: HomeAssistant, snooz_fan_entity_id: str hass: HomeAssistant, snooz_fan_entity_id: str
): ) -> None:
"""Test turning off the device by setting the percentage/volume to 0.""" """Test turning off the device by setting the percentage/volume to 0."""
await hass.services.async_call( await hass.services.async_call(
fan.DOMAIN, fan.DOMAIN,
@ -120,7 +120,7 @@ async def test_set_0_percentage_turns_off(
assert ATTR_ASSUMED_STATE not in state.attributes assert ATTR_ASSUMED_STATE not in state.attributes
async def test_turn_off(hass: HomeAssistant, snooz_fan_entity_id: str): async def test_turn_off(hass: HomeAssistant, snooz_fan_entity_id: str) -> None:
"""Test turning off the device.""" """Test turning off the device."""
await hass.services.async_call( await hass.services.async_call(
fan.DOMAIN, fan.DOMAIN,
@ -134,7 +134,7 @@ async def test_turn_off(hass: HomeAssistant, snooz_fan_entity_id: str):
assert ATTR_ASSUMED_STATE not in state.attributes assert ATTR_ASSUMED_STATE not in state.attributes
async def test_transition_off(hass: HomeAssistant, snooz_fan_entity_id: str): async def test_transition_off(hass: HomeAssistant, snooz_fan_entity_id: str) -> None:
"""Test transitioning off the device.""" """Test transitioning off the device."""
await hass.services.async_call( await hass.services.async_call(
DOMAIN, DOMAIN,
@ -150,7 +150,7 @@ async def test_transition_off(hass: HomeAssistant, snooz_fan_entity_id: str):
async def test_push_events( async def test_push_events(
hass: HomeAssistant, mock_connected_snooz: SnoozFixture, snooz_fan_entity_id: str hass: HomeAssistant, mock_connected_snooz: SnoozFixture, snooz_fan_entity_id: str
): ) -> None:
"""Test state update events from snooz device.""" """Test state update events from snooz device."""
mock_connected_snooz.device.trigger_state(SnoozDeviceState(False, 64)) mock_connected_snooz.device.trigger_state(SnoozDeviceState(False, 64))
@ -172,7 +172,7 @@ async def test_push_events(
assert state.attributes[ATTR_ASSUMED_STATE] is True assert state.attributes[ATTR_ASSUMED_STATE] is True
async def test_restore_state(hass: HomeAssistant): async def test_restore_state(hass: HomeAssistant) -> None:
"""Tests restoring entity state.""" """Tests restoring entity state."""
device = await create_mock_snooz(connected=False, initial_state=UnknownSnoozState) device = await create_mock_snooz(connected=False, initial_state=UnknownSnoozState)
@ -203,7 +203,7 @@ async def test_restore_state(hass: HomeAssistant):
assert state.attributes[ATTR_ASSUMED_STATE] is True assert state.attributes[ATTR_ASSUMED_STATE] is True
async def test_restore_unknown_state(hass: HomeAssistant): async def test_restore_unknown_state(hass: HomeAssistant) -> None:
"""Tests restoring entity state that was unknown.""" """Tests restoring entity state that was unknown."""
device = await create_mock_snooz(connected=False, initial_state=UnknownSnoozState) device = await create_mock_snooz(connected=False, initial_state=UnknownSnoozState)
@ -226,7 +226,7 @@ async def test_restore_unknown_state(hass: HomeAssistant):
async def test_command_results( async def test_command_results(
hass: HomeAssistant, mock_connected_snooz: SnoozFixture, snooz_fan_entity_id: str hass: HomeAssistant, mock_connected_snooz: SnoozFixture, snooz_fan_entity_id: str
): ) -> None:
"""Test device command results.""" """Test device command results."""
mock_execute = Mock(spec=mock_connected_snooz.device.async_execute_command) mock_execute = Mock(spec=mock_connected_snooz.device.async_execute_command)

View file

@ -8,7 +8,7 @@ from . import SnoozFixture
async def test_removing_entry_cleans_up_connections( async def test_removing_entry_cleans_up_connections(
hass: HomeAssistant, mock_connected_snooz: SnoozFixture hass: HomeAssistant, mock_connected_snooz: SnoozFixture
): ) -> None:
"""Tests setup and removal of a config entry, ensuring connections are cleaned up.""" """Tests setup and removal of a config entry, ensuring connections are cleaned up."""
await hass.config_entries.async_remove(mock_connected_snooz.entry.entry_id) await hass.config_entries.async_remove(mock_connected_snooz.entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -18,7 +18,7 @@ async def test_removing_entry_cleans_up_connections(
async def test_reloading_entry_cleans_up_connections( async def test_reloading_entry_cleans_up_connections(
hass: HomeAssistant, mock_connected_snooz: SnoozFixture hass: HomeAssistant, mock_connected_snooz: SnoozFixture
): ) -> None:
"""Test reloading an entry disconnects any existing connections.""" """Test reloading an entry disconnects any existing connections."""
await hass.config_entries.async_reload(mock_connected_snooz.entry.entry_id) await hass.config_entries.async_reload(mock_connected_snooz.entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -21,7 +21,7 @@ API_KEY = "a1b2c3d4e5f6g7h8"
@patch("homeassistant.components.solaredge.Solaredge") @patch("homeassistant.components.solaredge.Solaredge")
async def test_solaredgeoverviewdataservice_energy_values_validity( async def test_solaredgeoverviewdataservice_energy_values_validity(
mock_solaredge, hass: HomeAssistant mock_solaredge, hass: HomeAssistant
): ) -> None:
"""Test overview energy data validity.""" """Test overview energy data validity."""
mock_config_entry = MockConfigEntry( mock_config_entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,

View file

@ -59,7 +59,7 @@ def init_config_flow(hass):
return flow return flow
async def test_user(hass, test_connect): async def test_user(hass: HomeAssistant, test_connect) -> None:
"""Test user config.""" """Test user config."""
flow = init_config_flow(hass) flow = init_config_flow(hass)
@ -74,7 +74,7 @@ async def test_user(hass, test_connect):
assert result["data"][CONF_HOST] == HOST assert result["data"][CONF_HOST] == HOST
async def test_import(hass, test_connect): async def test_import(hass: HomeAssistant, test_connect) -> None:
"""Test import step.""" """Test import step."""
flow = init_config_flow(hass) flow = init_config_flow(hass)
@ -97,7 +97,7 @@ async def test_import(hass, test_connect):
assert result["data"][CONF_HOST] == HOST assert result["data"][CONF_HOST] == HOST
async def test_abort_if_already_setup(hass, test_connect): async def test_abort_if_already_setup(hass: HomeAssistant, test_connect) -> None:
"""Test we abort if the device is already setup.""" """Test we abort if the device is already setup."""
flow = init_config_flow(hass) flow = init_config_flow(hass)
MockConfigEntry( MockConfigEntry(

View file

@ -180,7 +180,7 @@ async def test_options_not_loaded(hass: HomeAssistant) -> None:
@pytest.mark.parametrize("reversed", [True, False]) @pytest.mark.parametrize("reversed", [True, False])
async def test_options_with_targets(hass, reversed): async def test_options_with_targets(hass: HomeAssistant, reversed) -> None:
"""Test we can configure reverse for a target.""" """Test we can configure reverse for a target."""
config_entry = MockConfigEntry( config_entry = MockConfigEntry(

View file

@ -191,7 +191,7 @@ async def test_options_flow(
hass: HomeAssistant, hass: HomeAssistant,
mock_setup_entry: None, mock_setup_entry: None,
init_integration: MockConfigEntry, init_integration: MockConfigEntry,
): ) -> None:
"""Test updating options.""" """Test updating options."""
entry = init_integration entry = init_integration

View file

@ -87,7 +87,7 @@ async def test_unload_config_entry(
assert mock_config_entry.entry_id not in hass.data[DOMAIN] assert mock_config_entry.entry_id not in hass.data[DOMAIN]
async def test_migrate_config_entry(hass: HomeAssistant): async def test_migrate_config_entry(hass: HomeAssistant) -> None:
"""Test successful migration of entry data.""" """Test successful migration of entry data."""
legacy_config = { legacy_config = {
CONF_API_KEY: "MOCK_API_KEY", CONF_API_KEY: "MOCK_API_KEY",

View file

@ -3,17 +3,18 @@ from __future__ import annotations
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
from homeassistant import config_entries, core from homeassistant import config_entries
from homeassistant.components import ssdp, zeroconf from homeassistant.components import ssdp, zeroconf
from homeassistant.components.media_player import DOMAIN as MP_DOMAIN from homeassistant.components.media_player import DOMAIN as MP_DOMAIN
from homeassistant.components.sonos.const import DATA_SONOS_DISCOVERY_MANAGER, DOMAIN from homeassistant.components.sonos.const import DATA_SONOS_DISCOVERY_MANAGER, DOMAIN
from homeassistant.const import CONF_HOSTS from homeassistant.const import CONF_HOSTS
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
async def test_user_form( async def test_user_form(
hass: core.HomeAssistant, zeroconf_payload: zeroconf.ZeroconfServiceInfo hass: HomeAssistant, zeroconf_payload: zeroconf.ZeroconfServiceInfo
): ) -> None:
"""Test we get the user initiated form.""" """Test we get the user initiated form."""
# Ensure config flow will fail if no devices discovered yet # Ensure config flow will fail if no devices discovered yet
@ -59,7 +60,7 @@ async def test_user_form(
assert len(mock_setup_entry.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
async def test_user_form_already_created(hass: core.HomeAssistant): async def test_user_form_already_created(hass: HomeAssistant) -> None:
"""Ensure we abort a flow if the entry is already created from config.""" """Ensure we abort a flow if the entry is already created from config."""
config = {DOMAIN: {MP_DOMAIN: {CONF_HOSTS: "192.168.4.2"}}} config = {DOMAIN: {MP_DOMAIN: {CONF_HOSTS: "192.168.4.2"}}}
with patch( with patch(
@ -77,8 +78,8 @@ async def test_user_form_already_created(hass: core.HomeAssistant):
async def test_zeroconf_form( async def test_zeroconf_form(
hass: core.HomeAssistant, zeroconf_payload: zeroconf.ZeroconfServiceInfo hass: HomeAssistant, zeroconf_payload: zeroconf.ZeroconfServiceInfo
): ) -> None:
"""Test we pass Zeroconf discoveries to the manager.""" """Test we pass Zeroconf discoveries to the manager."""
mock_manager = hass.data[DATA_SONOS_DISCOVERY_MANAGER] = MagicMock() mock_manager = hass.data[DATA_SONOS_DISCOVERY_MANAGER] = MagicMock()
@ -112,7 +113,7 @@ async def test_zeroconf_form(
assert len(mock_manager.mock_calls) == 2 assert len(mock_manager.mock_calls) == 2
async def test_ssdp_discovery(hass: core.HomeAssistant, soco): async def test_ssdp_discovery(hass: HomeAssistant, soco) -> None:
"""Test that SSDP discoveries create a config flow.""" """Test that SSDP discoveries create a config flow."""
await hass.config_entries.flow.async_init( await hass.config_entries.flow.async_init(
@ -153,7 +154,7 @@ async def test_ssdp_discovery(hass: core.HomeAssistant, soco):
assert len(mock_setup_entry.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
async def test_zeroconf_sonos_v1(hass: core.HomeAssistant): async def test_zeroconf_sonos_v1(hass: HomeAssistant) -> None:
"""Test we pass sonos devices to the discovery manager with v1 firmware devices.""" """Test we pass sonos devices to the discovery manager with v1 firmware devices."""
mock_manager = hass.data[DATA_SONOS_DISCOVERY_MANAGER] = MagicMock() mock_manager = hass.data[DATA_SONOS_DISCOVERY_MANAGER] = MagicMock()
@ -205,8 +206,8 @@ async def test_zeroconf_sonos_v1(hass: core.HomeAssistant):
async def test_zeroconf_form_not_sonos( async def test_zeroconf_form_not_sonos(
hass: core.HomeAssistant, zeroconf_payload: zeroconf.ZeroconfServiceInfo hass: HomeAssistant, zeroconf_payload: zeroconf.ZeroconfServiceInfo
): ) -> None:
"""Test we abort on non-sonos devices.""" """Test we abort on non-sonos devices."""
mock_manager = hass.data[DATA_SONOS_DISCOVERY_MANAGER] = MagicMock() mock_manager = hass.data[DATA_SONOS_DISCOVERY_MANAGER] = MagicMock()

View file

@ -1,14 +1,15 @@
"""Tests for the Sonos config flow.""" """Tests for the Sonos config flow."""
from unittest.mock import patch from unittest.mock import patch
from homeassistant import config_entries, core, data_entry_flow from homeassistant import config_entries, data_entry_flow
from homeassistant.components import sonos, zeroconf from homeassistant.components import sonos, zeroconf
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
async def test_creating_entry_sets_up_media_player( async def test_creating_entry_sets_up_media_player(
hass: core.HomeAssistant, zeroconf_payload: zeroconf.ZeroconfServiceInfo hass: HomeAssistant, zeroconf_payload: zeroconf.ZeroconfServiceInfo
): ) -> None:
"""Test setting up Sonos loads the media player.""" """Test setting up Sonos loads the media player."""
# Initiate a discovery to allow a user config flow # Initiate a discovery to allow a user config flow
@ -36,7 +37,7 @@ async def test_creating_entry_sets_up_media_player(
assert len(mock_setup.mock_calls) == 1 assert len(mock_setup.mock_calls) == 1
async def test_configuring_sonos_creates_entry(hass: core.HomeAssistant): async def test_configuring_sonos_creates_entry(hass: HomeAssistant) -> None:
"""Test that specifying config will create an entry.""" """Test that specifying config will create an entry."""
with patch( with patch(
"homeassistant.components.sonos.async_setup_entry", "homeassistant.components.sonos.async_setup_entry",
@ -52,7 +53,7 @@ async def test_configuring_sonos_creates_entry(hass: core.HomeAssistant):
assert len(mock_setup.mock_calls) == 1 assert len(mock_setup.mock_calls) == 1
async def test_not_configuring_sonos_not_creates_entry(hass: core.HomeAssistant): async def test_not_configuring_sonos_not_creates_entry(hass: HomeAssistant) -> None:
"""Test that no config will not create an entry.""" """Test that no config will not create an entry."""
with patch( with patch(
"homeassistant.components.sonos.async_setup_entry", "homeassistant.components.sonos.async_setup_entry",

View file

@ -1,9 +1,12 @@
"""Tests for the Sonos Media Player platform.""" """Tests for the Sonos Media Player platform."""
from homeassistant.const import STATE_IDLE from homeassistant.const import STATE_IDLE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr from homeassistant.helpers import device_registry as dr
async def test_device_registry(hass, async_autosetup_sonos, soco): async def test_device_registry(
hass: HomeAssistant, async_autosetup_sonos, soco
) -> None:
"""Test sonos device registered in the device registry.""" """Test sonos device registered in the device registry."""
device_registry = dr.async_get(hass) device_registry = dr.async_get(hass)
reg_device = device_registry.async_get_device( reg_device = device_registry.async_get_device(
@ -20,7 +23,9 @@ async def test_device_registry(hass, async_autosetup_sonos, soco):
assert reg_device.name == "Zone A" assert reg_device.name == "Zone A"
async def test_entity_basic(hass, async_autosetup_sonos, discover): async def test_entity_basic(
hass: HomeAssistant, async_autosetup_sonos, discover
) -> None:
"""Test basic state and attributes.""" """Test basic state and attributes."""
state = hass.states.get("media_player.zone_a") state = hass.states.get("media_player.zone_a")
assert state.state == STATE_IDLE assert state.state == STATE_IDLE

View file

@ -3,10 +3,13 @@ from unittest.mock import patch
from homeassistant.components.number import DOMAIN as NUMBER_DOMAIN, SERVICE_SET_VALUE from homeassistant.components.number import DOMAIN as NUMBER_DOMAIN, SERVICE_SET_VALUE
from homeassistant.const import ATTR_ENTITY_ID from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as ent_reg from homeassistant.helpers import entity_registry as ent_reg
async def test_number_entities(hass, async_autosetup_sonos, soco): async def test_number_entities(
hass: HomeAssistant, async_autosetup_sonos, soco
) -> None:
"""Test number entities.""" """Test number entities."""
entity_registry = ent_reg.async_get(hass) entity_registry = ent_reg.async_get(hass)

View file

@ -13,10 +13,11 @@ from homeassistant.components.media_player import (
) )
from homeassistant.components.plex import DOMAIN as PLEX_DOMAIN, PLEX_URI_SCHEME from homeassistant.components.plex import DOMAIN as PLEX_DOMAIN, PLEX_URI_SCHEME
from homeassistant.const import ATTR_ENTITY_ID from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
async def test_plex_play_media(hass, async_autosetup_sonos): async def test_plex_play_media(hass: HomeAssistant, async_autosetup_sonos) -> None:
"""Test playing media via the Plex integration.""" """Test playing media via the Plex integration."""
mock_plex_server = Mock() mock_plex_server = Mock()
mock_lookup = mock_plex_server.lookup_media mock_lookup = mock_plex_server.lookup_media

View file

@ -2,12 +2,14 @@
from datetime import timedelta from datetime import timedelta
from unittest.mock import PropertyMock, patch from unittest.mock import PropertyMock, patch
import pytest
from soco.exceptions import NotSupportedException from soco.exceptions import NotSupportedException
from homeassistant.components.sensor import SCAN_INTERVAL from homeassistant.components.sensor import SCAN_INTERVAL
from homeassistant.components.sonos.binary_sensor import ATTR_BATTERY_POWER_SOURCE from homeassistant.components.sonos.binary_sensor import ATTR_BATTERY_POWER_SOURCE
from homeassistant.config_entries import RELOAD_AFTER_UPDATE_DELAY from homeassistant.config_entries import RELOAD_AFTER_UPDATE_DELAY
from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as ent_reg from homeassistant.helpers import entity_registry as ent_reg
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
@ -16,7 +18,9 @@ from .conftest import SonosMockEvent
from tests.common import async_fire_time_changed from tests.common import async_fire_time_changed
async def test_entity_registry_unsupported(hass, async_setup_sonos, soco): async def test_entity_registry_unsupported(
hass: HomeAssistant, async_setup_sonos, soco
) -> None:
"""Test sonos device without battery registered in the device registry.""" """Test sonos device without battery registered in the device registry."""
soco.get_battery_info.side_effect = NotSupportedException soco.get_battery_info.side_effect = NotSupportedException
@ -29,7 +33,9 @@ async def test_entity_registry_unsupported(hass, async_setup_sonos, soco):
assert "binary_sensor.zone_a_power" not in entity_registry.entities assert "binary_sensor.zone_a_power" not in entity_registry.entities
async def test_entity_registry_supported(hass, async_autosetup_sonos, soco): async def test_entity_registry_supported(
hass: HomeAssistant, async_autosetup_sonos, soco
) -> None:
"""Test sonos device with battery registered in the device registry.""" """Test sonos device with battery registered in the device registry."""
entity_registry = ent_reg.async_get(hass) entity_registry = ent_reg.async_get(hass)
@ -38,7 +44,9 @@ async def test_entity_registry_supported(hass, async_autosetup_sonos, soco):
assert "binary_sensor.zone_a_power" in entity_registry.entities assert "binary_sensor.zone_a_power" in entity_registry.entities
async def test_battery_attributes(hass, async_autosetup_sonos, soco): async def test_battery_attributes(
hass: HomeAssistant, async_autosetup_sonos, soco
) -> None:
"""Test sonos device with battery state.""" """Test sonos device with battery state."""
entity_registry = ent_reg.async_get(hass) entity_registry = ent_reg.async_get(hass)
@ -55,7 +63,9 @@ async def test_battery_attributes(hass, async_autosetup_sonos, soco):
) )
async def test_battery_on_s1(hass, async_setup_sonos, soco, device_properties_event): async def test_battery_on_s1(
hass: HomeAssistant, async_setup_sonos, soco, device_properties_event
) -> None:
"""Test battery state updates on a Sonos S1 device.""" """Test battery state updates on a Sonos S1 device."""
soco.get_battery_info.return_value = {} soco.get_battery_info.return_value = {}
@ -84,8 +94,12 @@ async def test_battery_on_s1(hass, async_setup_sonos, soco, device_properties_ev
async def test_device_payload_without_battery( async def test_device_payload_without_battery(
hass, async_setup_sonos, soco, device_properties_event, caplog hass: HomeAssistant,
): async_setup_sonos,
soco,
device_properties_event,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test device properties event update without battery info.""" """Test device properties event update without battery info."""
soco.get_battery_info.return_value = None soco.get_battery_info.return_value = None
@ -104,8 +118,12 @@ async def test_device_payload_without_battery(
async def test_device_payload_without_battery_and_ignored_keys( async def test_device_payload_without_battery_and_ignored_keys(
hass, async_setup_sonos, soco, device_properties_event, caplog hass: HomeAssistant,
): async_setup_sonos,
soco,
device_properties_event,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test device properties event update without battery info and ignored keys.""" """Test device properties event update without battery info and ignored keys."""
soco.get_battery_info.return_value = None soco.get_battery_info.return_value = None
@ -124,8 +142,8 @@ async def test_device_payload_without_battery_and_ignored_keys(
async def test_audio_input_sensor( async def test_audio_input_sensor(
hass, async_autosetup_sonos, soco, tv_event, no_media_event hass: HomeAssistant, async_autosetup_sonos, soco, tv_event, no_media_event
): ) -> None:
"""Test audio input sensor.""" """Test audio input sensor."""
entity_registry = ent_reg.async_get(hass) entity_registry = ent_reg.async_get(hass)
@ -165,8 +183,8 @@ async def test_audio_input_sensor(
async def test_microphone_binary_sensor( async def test_microphone_binary_sensor(
hass, async_autosetup_sonos, soco, device_properties_event hass: HomeAssistant, async_autosetup_sonos, soco, device_properties_event
): ) -> None:
"""Test microphone binary sensor.""" """Test microphone binary sensor."""
entity_registry = ent_reg.async_get(hass) entity_registry = ent_reg.async_get(hass)
assert "binary_sensor.zone_a_microphone" in entity_registry.entities assert "binary_sensor.zone_a_microphone" in entity_registry.entities
@ -184,7 +202,9 @@ async def test_microphone_binary_sensor(
assert mic_binary_sensor_state.state == STATE_ON assert mic_binary_sensor_state.state == STATE_ON
async def test_favorites_sensor(hass, async_autosetup_sonos, soco, fire_zgs_event): async def test_favorites_sensor(
hass: HomeAssistant, async_autosetup_sonos, soco, fire_zgs_event
) -> None:
"""Test Sonos favorites sensor.""" """Test Sonos favorites sensor."""
entity_registry = ent_reg.async_get(hass) entity_registry = ent_reg.async_get(hass)
favorites = entity_registry.entities["sensor.sonos_favorites"] favorites = entity_registry.entities["sensor.sonos_favorites"]

View file

@ -5,10 +5,11 @@ import pytest
from homeassistant.components.media_player import DOMAIN as MP_DOMAIN, SERVICE_JOIN from homeassistant.components.media_player import DOMAIN as MP_DOMAIN, SERVICE_JOIN
from homeassistant.components.sonos.const import DATA_SONOS from homeassistant.components.sonos.const import DATA_SONOS
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
async def test_media_player_join(hass, async_autosetup_sonos): async def test_media_player_join(hass: HomeAssistant, async_autosetup_sonos) -> None:
"""Test join service.""" """Test join service."""
valid_entity_id = "media_player.zone_a" valid_entity_id = "media_player.zone_a"
mocked_entity_id = "media_player.mocked" mocked_entity_id = "media_player.mocked"

View file

@ -1,6 +1,8 @@
"""Tests for common SonosSpeaker behavior.""" """Tests for common SonosSpeaker behavior."""
from unittest.mock import patch from unittest.mock import patch
import pytest
from homeassistant.components.sonos.const import DATA_SONOS, SCAN_INTERVAL from homeassistant.components.sonos.const import DATA_SONOS, SCAN_INTERVAL
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
@ -9,8 +11,8 @@ from tests.common import async_fire_time_changed
async def test_fallback_to_polling( async def test_fallback_to_polling(
hass: HomeAssistant, async_autosetup_sonos, soco, caplog hass: HomeAssistant, async_autosetup_sonos, soco, caplog: pytest.LogCaptureFixture
): ) -> None:
"""Test that polling fallback works.""" """Test that polling fallback works."""
speaker = list(hass.data[DATA_SONOS].discovered.values())[0] speaker = list(hass.data[DATA_SONOS].discovered.values())[0]
assert speaker.soco is soco assert speaker.soco is soco
@ -31,7 +33,9 @@ async def test_fallback_to_polling(
assert "Activity on Zone A from SonosSpeaker.update_volume" in caplog.text assert "Activity on Zone A from SonosSpeaker.update_volume" in caplog.text
async def test_subscription_creation_fails(hass: HomeAssistant, async_setup_sonos): async def test_subscription_creation_fails(
hass: HomeAssistant, async_setup_sonos
) -> None:
"""Test that subscription creation failures are handled.""" """Test that subscription creation failures are handled."""
with patch( with patch(
"homeassistant.components.sonos.speaker.SonosSpeaker._subscribe", "homeassistant.components.sonos.speaker.SonosSpeaker._subscribe",

View file

@ -1,10 +1,11 @@
"""Tests for the Sonos statistics.""" """Tests for the Sonos statistics."""
from homeassistant.components.sonos.const import DATA_SONOS from homeassistant.components.sonos.const import DATA_SONOS
from homeassistant.core import HomeAssistant
async def test_statistics_duplicate( async def test_statistics_duplicate(
hass, async_autosetup_sonos, soco, device_properties_event hass: HomeAssistant, async_autosetup_sonos, soco, device_properties_event
): ) -> None:
"""Test Sonos statistics.""" """Test Sonos statistics."""
speaker = list(hass.data[DATA_SONOS].discovered.values())[0] speaker = list(hass.data[DATA_SONOS].discovered.values())[0]

View file

@ -14,6 +14,7 @@ from homeassistant.components.sonos.switch import (
) )
from homeassistant.config_entries import RELOAD_AFTER_UPDATE_DELAY from homeassistant.config_entries import RELOAD_AFTER_UPDATE_DELAY
from homeassistant.const import ATTR_TIME, STATE_OFF, STATE_ON from homeassistant.const import ATTR_TIME, STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as ent_reg from homeassistant.helpers import entity_registry as ent_reg
from homeassistant.util import dt from homeassistant.util import dt
@ -22,7 +23,7 @@ from .conftest import SonosMockEvent
from tests.common import async_fire_time_changed from tests.common import async_fire_time_changed
async def test_entity_registry(hass, async_autosetup_sonos): async def test_entity_registry(hass: HomeAssistant, async_autosetup_sonos) -> None:
"""Test sonos device with alarm registered in the device registry.""" """Test sonos device with alarm registered in the device registry."""
entity_registry = ent_reg.async_get(hass) entity_registry = ent_reg.async_get(hass)
@ -37,7 +38,9 @@ async def test_entity_registry(hass, async_autosetup_sonos):
assert "switch.zone_a_touch_controls" in entity_registry.entities assert "switch.zone_a_touch_controls" in entity_registry.entities
async def test_switch_attributes(hass, async_autosetup_sonos, soco, fire_zgs_event): async def test_switch_attributes(
hass: HomeAssistant, async_autosetup_sonos, soco, fire_zgs_event
) -> None:
"""Test for correct Sonos switch states.""" """Test for correct Sonos switch states."""
entity_registry = ent_reg.async_get(hass) entity_registry = ent_reg.async_get(hass)
@ -126,8 +129,13 @@ async def test_switch_attributes(hass, async_autosetup_sonos, soco, fire_zgs_eve
async def test_alarm_create_delete( async def test_alarm_create_delete(
hass, async_setup_sonos, soco, alarm_clock, alarm_clock_extended, alarm_event hass: HomeAssistant,
): async_setup_sonos,
soco,
alarm_clock,
alarm_clock_extended,
alarm_event,
) -> None:
"""Test for correct creation and deletion of alarms during runtime.""" """Test for correct creation and deletion of alarms during runtime."""
entity_registry = ent_reg.async_get(hass) entity_registry = ent_reg.async_get(hass)