Add type hints to integration tests (part 1) (#87777)

This commit is contained in:
epenet 2023-02-09 16:09:13 +01:00 committed by GitHub
parent 2b3e6a4ca8
commit 07a1a0efa9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
51 changed files with 905 additions and 471 deletions

View file

@ -8,6 +8,7 @@ from homeassistant import data_entry_flow
from homeassistant.components.acmeda.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_HOST
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
@ -39,7 +40,7 @@ async def async_generator(items):
yield item
async def test_show_form_no_hubs(hass, mock_hub_discover):
async def test_show_form_no_hubs(hass: HomeAssistant, mock_hub_discover) -> None:
"""Test that flow aborts if no hubs are discovered."""
mock_hub_discover.return_value = async_generator([])
@ -54,7 +55,9 @@ async def test_show_form_no_hubs(hass, mock_hub_discover):
assert len(mock_hub_discover.mock_calls) == 1
async def test_show_form_one_hub(hass, mock_hub_discover, mock_hub_run):
async def test_show_form_one_hub(
hass: HomeAssistant, mock_hub_discover, mock_hub_run
) -> None:
"""Test that a config is created when one hub discovered."""
dummy_hub_1 = aiopulse.Hub(DUMMY_HOST1)
@ -76,7 +79,7 @@ async def test_show_form_one_hub(hass, mock_hub_discover, mock_hub_run):
assert len(mock_hub_discover.mock_calls) == 1
async def test_show_form_two_hubs(hass, mock_hub_discover):
async def test_show_form_two_hubs(hass: HomeAssistant, mock_hub_discover) -> None:
"""Test that the form is served when more than one hub discovered."""
dummy_hub_1 = aiopulse.Hub(DUMMY_HOST1)
@ -98,7 +101,9 @@ async def test_show_form_two_hubs(hass, mock_hub_discover):
assert len(mock_hub_discover.mock_calls) == 1
async def test_create_second_entry(hass, mock_hub_run, mock_hub_discover):
async def test_create_second_entry(
hass: HomeAssistant, mock_hub_run, mock_hub_discover
) -> None:
"""Test that a config is created when a second hub is discovered."""
dummy_hub_1 = aiopulse.Hub(DUMMY_HOST1)
@ -124,7 +129,7 @@ async def test_create_second_entry(hass, mock_hub_run, mock_hub_discover):
}
async def test_already_configured(hass, mock_hub_discover):
async def test_already_configured(hass: HomeAssistant, mock_hub_discover) -> None:
"""Test that flow aborts when all hubs are configured."""
dummy_hub_1 = aiopulse.Hub(DUMMY_HOST1)

View file

@ -27,7 +27,7 @@ def _patch_init_agent(mocked_agent):
async def test_setup_config_and_unload(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
):
) -> None:
"""Test setup and unload."""
entry = await init_integration(hass, aioclient_mock)
assert entry.state == ConfigEntryState.LOADED
@ -41,7 +41,7 @@ async def test_setup_config_and_unload(
assert not hass.data.get(DOMAIN)
async def test_async_setup_entry_not_ready(hass: HomeAssistant):
async def test_async_setup_entry_not_ready(hass: HomeAssistant) -> None:
"""Test that it throws ConfigEntryNotReady when exception occurs during setup."""
entry = create_entry(hass)
with patch(

View file

@ -2,14 +2,21 @@
import json
from homeassistant.components.diagnostics import REDACTED
from homeassistant.core import HomeAssistant
from . import init_integration
from tests.common import load_fixture
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import ClientSessionGenerator
async def test_entry_diagnostics(hass, aioclient_mock, hass_client):
async def test_entry_diagnostics(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
hass_client: ClientSessionGenerator,
) -> None:
"""Test config entry diagnostics."""
entry = await init_integration(hass, aioclient_mock)

View file

@ -1,4 +1,5 @@
"""Test init of Airly integration."""
from typing import Any
from unittest.mock import patch
import pytest
@ -9,7 +10,7 @@ from homeassistant.components.airly.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.util.dt import utcnow
from . import API_POINT_URL, init_integration
@ -198,8 +199,11 @@ async def test_unload_entry(
@pytest.mark.parametrize("old_identifier", ((DOMAIN, 123, 456), (DOMAIN, "123", "456")))
async def test_migrate_device_entry(
hass, aioclient_mock, old_identifier, device_registry
):
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
old_identifier: tuple[str, Any, Any],
device_registry: dr.DeviceRegistry,
) -> None:
"""Test device_info identifiers migration."""
config_entry = MockConfigEntry(
domain=DOMAIN,

View file

@ -6,9 +6,10 @@ import pytest
from homeassistant import config_entries, data_entry_flow
from homeassistant.components.airnow.const import DOMAIN
from homeassistant.core import HomeAssistant
async def test_form(hass, config, setup_airnow):
async def test_form(hass: HomeAssistant, config, setup_airnow) -> None:
"""Test we get the form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -22,7 +23,7 @@ async def test_form(hass, config, setup_airnow):
@pytest.mark.parametrize("mock_api_get", [AsyncMock(side_effect=InvalidKeyError)])
async def test_form_invalid_auth(hass, config, setup_airnow):
async def test_form_invalid_auth(hass: HomeAssistant, config, setup_airnow) -> None:
"""Test we handle invalid auth."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -33,7 +34,7 @@ async def test_form_invalid_auth(hass, config, setup_airnow):
@pytest.mark.parametrize("data", [{}])
async def test_form_invalid_location(hass, config, setup_airnow):
async def test_form_invalid_location(hass: HomeAssistant, config, setup_airnow) -> None:
"""Test we handle invalid location."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -44,7 +45,7 @@ async def test_form_invalid_location(hass, config, setup_airnow):
@pytest.mark.parametrize("mock_api_get", [AsyncMock(side_effect=AirNowError)])
async def test_form_cannot_connect(hass, config, setup_airnow):
async def test_form_cannot_connect(hass: HomeAssistant, config, setup_airnow) -> None:
"""Test we handle cannot connect error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -55,7 +56,7 @@ async def test_form_cannot_connect(hass, config, setup_airnow):
@pytest.mark.parametrize("mock_api_get", [AsyncMock(side_effect=RuntimeError)])
async def test_form_unexpected(hass, config, setup_airnow):
async def test_form_unexpected(hass: HomeAssistant, config, setup_airnow) -> None:
"""Test we handle an unexpected error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -65,7 +66,7 @@ async def test_form_unexpected(hass, config, setup_airnow):
assert result2["errors"] == {"base": "unknown"}
async def test_entry_already_exists(hass, config, config_entry):
async def test_entry_already_exists(hass: HomeAssistant, config, config_entry) -> None:
"""Test that the form aborts if the Lat/Lng is already configured."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}

View file

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

View file

@ -22,7 +22,7 @@ from . import (
from tests.common import MockConfigEntry
async def test_bluetooth_discovery(hass: HomeAssistant):
async def test_bluetooth_discovery(hass: HomeAssistant) -> None:
"""Test discovery via bluetooth with a valid device."""
with patch_async_ble_device_from_address(WAVE_SERVICE_INFO), patch_airthings_ble(
AirthingsDevice(name="Airthings Wave+", identifier="123456")
@ -47,7 +47,7 @@ async def test_bluetooth_discovery(hass: HomeAssistant):
assert result["result"].unique_id == "cc:cc:cc:cc:cc:cc"
async def test_bluetooth_discovery_no_BLEDevice(hass: HomeAssistant):
async def test_bluetooth_discovery_no_BLEDevice(hass: HomeAssistant) -> None:
"""Test discovery via bluetooth but there's no BLEDevice."""
with patch_async_ble_device_from_address(None):
result = await hass.config_entries.flow.async_init(
@ -61,7 +61,7 @@ async def test_bluetooth_discovery_no_BLEDevice(hass: HomeAssistant):
async def test_bluetooth_discovery_airthings_ble_update_failed(
hass: HomeAssistant,
):
) -> None:
"""Test discovery via bluetooth but there's an exception from airthings-ble."""
for loop in [(Exception(), "unknown"), (BleakError(), "cannot_connect")]:
exc, reason = loop
@ -78,7 +78,7 @@ async def test_bluetooth_discovery_airthings_ble_update_failed(
assert result["reason"] == reason
async def test_bluetooth_discovery_already_setup(hass: HomeAssistant):
async def test_bluetooth_discovery_already_setup(hass: HomeAssistant) -> None:
"""Test discovery via bluetooth with a valid device when already setup."""
entry = MockConfigEntry(
domain=DOMAIN,
@ -94,7 +94,7 @@ async def test_bluetooth_discovery_already_setup(hass: HomeAssistant):
assert result["reason"] == "already_configured"
async def test_user_setup(hass: HomeAssistant):
async def test_user_setup(hass: HomeAssistant) -> None:
"""Test the user initiated form."""
with patch(
"homeassistant.components.airthings_ble.config_flow.async_discovered_service_info",
@ -129,7 +129,7 @@ async def test_user_setup(hass: HomeAssistant):
assert result["result"].unique_id == "cc:cc:cc:cc:cc:cc"
async def test_user_setup_no_device(hass: HomeAssistant):
async def test_user_setup_no_device(hass: HomeAssistant) -> None:
"""Test the user initiated form without any device detected."""
with patch(
"homeassistant.components.airthings_ble.config_flow.async_discovered_service_info",
@ -142,7 +142,7 @@ async def test_user_setup_no_device(hass: HomeAssistant):
assert result["reason"] == "no_devices_found"
async def test_user_setup_existing_and_unknown_device(hass: HomeAssistant):
async def test_user_setup_existing_and_unknown_device(hass: HomeAssistant) -> None:
"""Test the user initiated form with existing devices and unknown ones."""
entry = MockConfigEntry(
domain=DOMAIN,
@ -160,7 +160,7 @@ async def test_user_setup_existing_and_unknown_device(hass: HomeAssistant):
assert result["reason"] == "no_devices_found"
async def test_user_setup_unknown_error(hass: HomeAssistant):
async def test_user_setup_unknown_error(hass: HomeAssistant) -> None:
"""Test the user initiated form with an unknown error."""
with patch(
"homeassistant.components.airthings_ble.config_flow.async_discovered_service_info",
@ -176,7 +176,7 @@ async def test_user_setup_unknown_error(hass: HomeAssistant):
assert result["reason"] == "unknown"
async def test_user_setup_unable_to_connect(hass: HomeAssistant):
async def test_user_setup_unable_to_connect(hass: HomeAssistant) -> None:
"""Test the user initiated form with a device that's failing connection."""
with patch(
"homeassistant.components.airthings_ble.config_flow.async_discovered_service_info",

View file

@ -20,6 +20,7 @@ from homeassistant.components.airvisual import (
)
from homeassistant.config_entries import SOURCE_REAUTH, SOURCE_USER
from homeassistant.const import CONF_API_KEY, CONF_SHOW_ON_MAP
from homeassistant.core import HomeAssistant
from .conftest import (
COORDS_CONFIG,
@ -62,7 +63,7 @@ from .conftest import (
],
)
async def test_create_entry(
hass,
hass: HomeAssistant,
cloud_api,
config,
entry_title,
@ -72,7 +73,7 @@ async def test_create_entry(
mock_pyairvisual,
patched_method,
response,
):
) -> None:
"""Test creating a config entry."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
@ -103,7 +104,7 @@ async def test_create_entry(
assert result["data"] == {**config, CONF_INTEGRATION_TYPE: integration_type}
async def test_duplicate_error(hass, config, setup_config_entry):
async def test_duplicate_error(hass: HomeAssistant, config, setup_config_entry) -> None:
"""Test that errors are shown when duplicate entries are added."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
@ -126,7 +127,9 @@ async def test_duplicate_error(hass, config, setup_config_entry):
assert result["reason"] == "already_configured"
async def test_options_flow(hass, config_entry, setup_config_entry):
async def test_options_flow(
hass: HomeAssistant, config_entry, setup_config_entry
) -> None:
"""Test config flow options."""
result = await hass.config_entries.options.async_init(config_entry.entry_id)
assert result["type"] == data_entry_flow.FlowResultType.FORM
@ -139,7 +142,9 @@ async def test_options_flow(hass, config_entry, setup_config_entry):
assert config_entry.options == {CONF_SHOW_ON_MAP: False}
async def test_step_reauth(hass, config_entry, setup_config_entry):
async def test_step_reauth(
hass: HomeAssistant, config_entry, setup_config_entry
) -> None:
"""Test that the reauth step works."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_REAUTH}, data=config_entry.data

View file

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

View file

@ -20,6 +20,7 @@ from homeassistant.const import (
CONF_PASSWORD,
CONF_STATE,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, issue_registry as ir
from .conftest import (
@ -39,7 +40,7 @@ from .conftest import (
from tests.common import MockConfigEntry
async def test_migration_1_2(hass, mock_pyairvisual):
async def test_migration_1_2(hass: HomeAssistant, mock_pyairvisual) -> None:
"""Test migrating from version 1 to 2."""
entry = MockConfigEntry(
domain=DOMAIN,
@ -98,7 +99,7 @@ async def test_migration_1_2(hass, mock_pyairvisual):
}
async def test_migration_2_3(hass, mock_pyairvisual):
async def test_migration_2_3(hass: HomeAssistant, mock_pyairvisual) -> None:
"""Test migrating from version 2 to 3."""
entry = MockConfigEntry(
domain=DOMAIN,

View file

@ -12,6 +12,7 @@ from homeassistant import data_entry_flow
from homeassistant.components.airvisual_pro.const import DOMAIN
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_REAUTH, SOURCE_USER
from homeassistant.const import CONF_IP_ADDRESS, CONF_PASSWORD
from homeassistant.core import HomeAssistant
@pytest.mark.parametrize(
@ -24,8 +25,8 @@ from homeassistant.const import CONF_IP_ADDRESS, CONF_PASSWORD
],
)
async def test_create_entry(
hass, config, connect_errors, connect_mock, pro, setup_airvisual_pro
):
hass: HomeAssistant, config, connect_errors, connect_mock, pro, setup_airvisual_pro
) -> None:
"""Test creating an entry."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
@ -52,7 +53,9 @@ async def test_create_entry(
}
async def test_duplicate_error(hass, config, config_entry, setup_airvisual_pro):
async def test_duplicate_error(
hass: HomeAssistant, config, config_entry, setup_airvisual_pro
) -> None:
"""Test that errors are shown when duplicates are added."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
@ -67,7 +70,7 @@ async def test_duplicate_error(hass, config, config_entry, setup_airvisual_pro):
assert result["reason"] == "already_configured"
async def test_step_import(hass, config, setup_airvisual_pro):
async def test_step_import(hass: HomeAssistant, config, setup_airvisual_pro) -> None:
"""Test that the user step works."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=config
@ -90,8 +93,14 @@ async def test_step_import(hass, config, setup_airvisual_pro):
],
)
async def test_reauth(
hass, config, config_entry, connect_errors, connect_mock, pro, setup_airvisual_pro
):
hass: HomeAssistant,
config,
config_entry,
connect_errors,
connect_mock,
pro,
setup_airvisual_pro,
) -> None:
"""Test re-auth (including errors)."""
result = await hass.config_entries.flow.async_init(
DOMAIN,

View file

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

View file

@ -145,7 +145,7 @@ async def test_form_duplicated_id(hass: HomeAssistant) -> None:
assert result["reason"] == "already_configured"
async def test_connection_error(hass: HomeAssistant):
async def test_connection_error(hass: HomeAssistant) -> None:
"""Test connection to host error."""
with patch(
@ -221,7 +221,7 @@ async def test_dhcp_flow_error(hass: HomeAssistant) -> None:
assert result["reason"] == "cannot_connect"
async def test_dhcp_connection_error(hass: HomeAssistant):
async def test_dhcp_connection_error(hass: HomeAssistant) -> None:
"""Test DHCP connection to host error."""
with patch(

View file

@ -98,7 +98,7 @@ async def test_form_connection_timeout(
async def test_form_already_configured(
hass: HomeAssistant, mock_aladdinconnect_api: MagicMock
):
) -> None:
"""Test we handle already configured error."""
mock_entry = MockConfigEntry(
domain=DOMAIN,

View file

@ -202,7 +202,7 @@ async def test_yaml_import(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
mock_aladdinconnect_api: MagicMock,
):
) -> None:
"""Test setup YAML import."""
assert COVER_DOMAIN not in hass.config.components

View file

@ -91,7 +91,7 @@ async def test_setup_component_no_error(hass: HomeAssistant) -> None:
async def test_entry_password_fail(
hass: HomeAssistant, mock_aladdinconnect_api: MagicMock
):
) -> None:
"""Test password fail during entry."""
entry = MockConfigEntry(
domain=DOMAIN,

View file

@ -1,7 +1,10 @@
"""The tests for Alarm control panel device actions."""
import pytest
from homeassistant.components.alarm_control_panel import DOMAIN, const
from homeassistant.components.alarm_control_panel import (
DOMAIN,
AlarmControlPanelEntityFeature,
)
import homeassistant.components.automation as automation
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.const import (
@ -14,9 +17,9 @@ from homeassistant.const import (
STATE_ALARM_TRIGGERED,
STATE_UNKNOWN,
)
from homeassistant.helpers import device_registry as dr
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.entity import EntityCategory
from homeassistant.helpers.entity_registry import RegistryEntryHider
from homeassistant.setup import async_setup_component
from tests.common import (
@ -34,60 +37,60 @@ from tests.components.blueprint.conftest import stub_blueprint_populate # noqa:
(False, 0, 0, ["disarm"]),
(
False,
const.AlarmControlPanelEntityFeature.ARM_AWAY,
AlarmControlPanelEntityFeature.ARM_AWAY,
0,
["disarm", "arm_away"],
),
(
False,
const.AlarmControlPanelEntityFeature.ARM_HOME,
AlarmControlPanelEntityFeature.ARM_HOME,
0,
["disarm", "arm_home"],
),
(
False,
const.AlarmControlPanelEntityFeature.ARM_NIGHT,
AlarmControlPanelEntityFeature.ARM_NIGHT,
0,
["disarm", "arm_night"],
),
(False, const.AlarmControlPanelEntityFeature.TRIGGER, 0, ["disarm", "trigger"]),
(False, AlarmControlPanelEntityFeature.TRIGGER, 0, ["disarm", "trigger"]),
(True, 0, 0, ["disarm"]),
(
True,
0,
const.AlarmControlPanelEntityFeature.ARM_AWAY,
AlarmControlPanelEntityFeature.ARM_AWAY,
["disarm", "arm_away"],
),
(
True,
0,
const.AlarmControlPanelEntityFeature.ARM_HOME,
AlarmControlPanelEntityFeature.ARM_HOME,
["disarm", "arm_home"],
),
(
True,
0,
const.AlarmControlPanelEntityFeature.ARM_NIGHT,
AlarmControlPanelEntityFeature.ARM_NIGHT,
["disarm", "arm_night"],
),
(
True,
0,
const.AlarmControlPanelEntityFeature.ARM_VACATION,
AlarmControlPanelEntityFeature.ARM_VACATION,
["disarm", "arm_vacation"],
),
(True, 0, const.AlarmControlPanelEntityFeature.TRIGGER, ["disarm", "trigger"]),
(True, 0, AlarmControlPanelEntityFeature.TRIGGER, ["disarm", "trigger"]),
],
)
async def test_get_actions(
hass,
device_registry,
entity_registry,
set_state,
features_reg,
features_state,
expected_action_types,
):
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
set_state: bool,
features_reg: AlarmControlPanelEntityFeature,
features_state: AlarmControlPanelEntityFeature,
expected_action_types: list[str],
) -> None:
"""Test we get the expected actions from a alarm_control_panel."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
@ -126,19 +129,19 @@ async def test_get_actions(
@pytest.mark.parametrize(
"hidden_by,entity_category",
(
(RegistryEntryHider.INTEGRATION, None),
(RegistryEntryHider.USER, None),
(er.RegistryEntryHider.INTEGRATION, None),
(er.RegistryEntryHider.USER, None),
(None, EntityCategory.CONFIG),
(None, EntityCategory.DIAGNOSTIC),
),
)
async def test_get_actions_hidden_auxiliary(
hass,
device_registry,
entity_registry,
hidden_by,
entity_category,
):
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
hidden_by: er.RegistryEntryHider | None,
entity_category: EntityCategory | None,
) -> None:
"""Test we get the expected actions from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
@ -153,7 +156,7 @@ async def test_get_actions_hidden_auxiliary(
device_id=device_entry.id,
entity_category=entity_category,
hidden_by=hidden_by,
supported_features=const.AlarmControlPanelEntityFeature.ARM_AWAY,
supported_features=AlarmControlPanelEntityFeature.ARM_AWAY,
)
expected_actions = []
expected_actions += [
@ -172,7 +175,11 @@ async def test_get_actions_hidden_auxiliary(
assert_lists_same(actions, expected_actions)
async def test_get_actions_arm_night_only(hass, device_registry, entity_registry):
async def test_get_actions_arm_night_only(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected actions from a alarm_control_panel."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
@ -209,8 +216,11 @@ async def test_get_actions_arm_night_only(hass, device_registry, entity_registry
async def test_get_action_capabilities(
hass, device_registry, entity_registry, enable_custom_integrations
):
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
enable_custom_integrations: None,
) -> None:
"""Test we get the expected capabilities from a sensor trigger."""
platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init()
@ -253,8 +263,11 @@ async def test_get_action_capabilities(
async def test_get_action_capabilities_arm_code(
hass, device_registry, entity_registry, enable_custom_integrations
):
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
enable_custom_integrations: None,
) -> None:
"""Test we get the expected capabilities from a sensor trigger."""
platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init()
@ -304,7 +317,7 @@ async def test_get_action_capabilities_arm_code(
assert capabilities == expected_capabilities[action["type"]]
async def test_action(hass, enable_custom_integrations):
async def test_action(hass: HomeAssistant, enable_custom_integrations: None) -> None:
"""Test for turn_on and turn_off actions."""
platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init()

View file

@ -1,7 +1,10 @@
"""The tests for Alarm control panel device conditions."""
import pytest
from homeassistant.components.alarm_control_panel import DOMAIN, const
from homeassistant.components.alarm_control_panel import (
DOMAIN,
AlarmControlPanelEntityFeature,
)
import homeassistant.components.automation as automation
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.const import (
@ -13,9 +16,9 @@ from homeassistant.const import (
STATE_ALARM_DISARMED,
STATE_ALARM_TRIGGERED,
)
from homeassistant.helpers import device_registry as dr
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.entity import EntityCategory
from homeassistant.helpers.entity_registry import RegistryEntryHider
from homeassistant.setup import async_setup_component
from tests.common import (
@ -28,7 +31,7 @@ from tests.components.blueprint.conftest import stub_blueprint_populate # noqa:
@pytest.fixture
def calls(hass):
def calls(hass: HomeAssistant) -> list[ServiceCall]:
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation")
@ -37,48 +40,48 @@ def calls(hass):
"set_state,features_reg,features_state,expected_condition_types",
[
(False, 0, 0, []),
(False, const.AlarmControlPanelEntityFeature.ARM_AWAY, 0, ["is_armed_away"]),
(False, const.AlarmControlPanelEntityFeature.ARM_HOME, 0, ["is_armed_home"]),
(False, const.AlarmControlPanelEntityFeature.ARM_NIGHT, 0, ["is_armed_night"]),
(False, AlarmControlPanelEntityFeature.ARM_AWAY, 0, ["is_armed_away"]),
(False, AlarmControlPanelEntityFeature.ARM_HOME, 0, ["is_armed_home"]),
(False, AlarmControlPanelEntityFeature.ARM_NIGHT, 0, ["is_armed_night"]),
(
False,
const.AlarmControlPanelEntityFeature.ARM_VACATION,
AlarmControlPanelEntityFeature.ARM_VACATION,
0,
["is_armed_vacation"],
),
(
False,
const.AlarmControlPanelEntityFeature.ARM_CUSTOM_BYPASS,
AlarmControlPanelEntityFeature.ARM_CUSTOM_BYPASS,
0,
["is_armed_custom_bypass"],
),
(True, 0, 0, []),
(True, 0, const.AlarmControlPanelEntityFeature.ARM_AWAY, ["is_armed_away"]),
(True, 0, const.AlarmControlPanelEntityFeature.ARM_HOME, ["is_armed_home"]),
(True, 0, const.AlarmControlPanelEntityFeature.ARM_NIGHT, ["is_armed_night"]),
(True, 0, AlarmControlPanelEntityFeature.ARM_AWAY, ["is_armed_away"]),
(True, 0, AlarmControlPanelEntityFeature.ARM_HOME, ["is_armed_home"]),
(True, 0, AlarmControlPanelEntityFeature.ARM_NIGHT, ["is_armed_night"]),
(
True,
0,
const.AlarmControlPanelEntityFeature.ARM_VACATION,
AlarmControlPanelEntityFeature.ARM_VACATION,
["is_armed_vacation"],
),
(
True,
0,
const.AlarmControlPanelEntityFeature.ARM_CUSTOM_BYPASS,
AlarmControlPanelEntityFeature.ARM_CUSTOM_BYPASS,
["is_armed_custom_bypass"],
),
],
)
async def test_get_conditions(
hass,
device_registry,
entity_registry,
set_state,
features_reg,
features_state,
expected_condition_types,
):
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
set_state: bool,
features_reg: AlarmControlPanelEntityFeature,
features_state: AlarmControlPanelEntityFeature,
expected_condition_types: list[str],
) -> None:
"""Test we get the expected conditions from a alarm_control_panel."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
@ -132,19 +135,19 @@ async def test_get_conditions(
@pytest.mark.parametrize(
"hidden_by,entity_category",
(
(RegistryEntryHider.INTEGRATION, None),
(RegistryEntryHider.USER, None),
(er.RegistryEntryHider.INTEGRATION, None),
(er.RegistryEntryHider.USER, None),
(None, EntityCategory.CONFIG),
(None, EntityCategory.DIAGNOSTIC),
),
)
async def test_get_conditions_hidden_auxiliary(
hass,
device_registry,
entity_registry,
hidden_by,
entity_category,
):
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
hidden_by: er.RegistryEntryHider | None,
entity_category: EntityCategory | None,
) -> None:
"""Test we get the expected conditions from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
@ -177,7 +180,7 @@ async def test_get_conditions_hidden_auxiliary(
assert_lists_same(conditions, expected_conditions)
async def test_if_state(hass, calls):
async def test_if_state(hass: HomeAssistant, calls: list[ServiceCall]) -> None:
"""Test for all conditions."""
assert await async_setup_component(
hass,

View file

@ -3,7 +3,10 @@ from datetime import timedelta
import pytest
from homeassistant.components.alarm_control_panel import DOMAIN
from homeassistant.components.alarm_control_panel import (
DOMAIN,
AlarmControlPanelEntityFeature,
)
import homeassistant.components.automation as automation
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.const import (
@ -15,9 +18,9 @@ from homeassistant.const import (
STATE_ALARM_PENDING,
STATE_ALARM_TRIGGERED,
)
from homeassistant.helpers import device_registry as dr
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.entity import EntityCategory
from homeassistant.helpers.entity_registry import RegistryEntryHider
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
@ -33,7 +36,7 @@ from tests.components.blueprint.conftest import stub_blueprint_populate # noqa:
@pytest.fixture
def calls(hass):
def calls(hass: HomeAssistant) -> list[ServiceCall]:
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation")
@ -74,14 +77,14 @@ def calls(hass):
],
)
async def test_get_triggers(
hass,
device_registry,
entity_registry,
set_state,
features_reg,
features_state,
expected_trigger_types,
):
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
set_state: bool,
features_reg: AlarmControlPanelEntityFeature,
features_state: AlarmControlPanelEntityFeature,
expected_trigger_types: list[str],
) -> None:
"""Test we get the expected triggers from an alarm_control_panel."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
@ -124,19 +127,19 @@ async def test_get_triggers(
@pytest.mark.parametrize(
"hidden_by,entity_category",
(
(RegistryEntryHider.INTEGRATION, None),
(RegistryEntryHider.USER, None),
(er.RegistryEntryHider.INTEGRATION, None),
(er.RegistryEntryHider.USER, None),
(None, EntityCategory.CONFIG),
(None, EntityCategory.DIAGNOSTIC),
),
)
async def test_get_triggers_hidden_auxiliary(
hass,
device_registry,
entity_registry,
hidden_by,
entity_category,
):
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
hidden_by: er.RegistryEntryHider | None,
entity_category: EntityCategory | None,
) -> None:
"""Test we get the expected triggers from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
@ -169,7 +172,11 @@ async def test_get_triggers_hidden_auxiliary(
assert_lists_same(triggers, expected_triggers)
async def test_get_trigger_capabilities(hass, device_registry, entity_registry):
async def test_get_trigger_capabilities(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected capabilities from an alarm_control_panel."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
@ -199,7 +206,9 @@ async def test_get_trigger_capabilities(hass, device_registry, entity_registry):
}
async def test_if_fires_on_state_change(hass, calls):
async def test_if_fires_on_state_change(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test for turn_on and turn_off triggers firing."""
hass.states.async_set("alarm_control_panel.entity", STATE_ALARM_PENDING)
@ -405,7 +414,9 @@ async def test_if_fires_on_state_change(hass, calls):
)
async def test_if_fires_on_state_change_with_for(hass, calls):
async def test_if_fires_on_state_change_with_for(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test for triggers firing with delay."""
entity_id = f"{DOMAIN}.entity"
hass.states.async_set(entity_id, STATE_ALARM_DISARMED)

View file

@ -55,7 +55,7 @@ from tests.common import MockConfigEntry
),
],
)
async def test_setups(hass: HomeAssistant, protocol, connection, title):
async def test_setups(hass: HomeAssistant, protocol, connection, title) -> None:
"""Test flow for setting up the available AlarmDecoder protocols."""
result = await hass.config_entries.flow.async_init(
@ -93,7 +93,7 @@ async def test_setups(hass: HomeAssistant, protocol, connection, title):
assert len(mock_setup_entry.mock_calls) == 1
async def test_setup_connection_error(hass: HomeAssistant):
async def test_setup_connection_error(hass: HomeAssistant) -> None:
"""Test flow for setup with a connection error."""
port = 1001
@ -137,7 +137,7 @@ async def test_setup_connection_error(hass: HomeAssistant):
assert result["errors"] == {"base": "unknown"}
async def test_options_arm_flow(hass: HomeAssistant):
async def test_options_arm_flow(hass: HomeAssistant) -> None:
"""Test arm options flow."""
user_input = {
CONF_ALT_NIGHT_MODE: True,
@ -178,7 +178,7 @@ async def test_options_arm_flow(hass: HomeAssistant):
}
async def test_options_zone_flow(hass: HomeAssistant):
async def test_options_zone_flow(hass: HomeAssistant) -> None:
"""Test options flow for adding/deleting zones."""
zone_number = "2"
zone_settings = {
@ -257,7 +257,7 @@ async def test_options_zone_flow(hass: HomeAssistant):
}
async def test_options_zone_flow_validation(hass: HomeAssistant):
async def test_options_zone_flow_validation(hass: HomeAssistant) -> None:
"""Test input validation for zone options flow."""
zone_number = "2"
zone_settings = {
@ -412,7 +412,7 @@ async def test_options_zone_flow_validation(hass: HomeAssistant):
),
],
)
async def test_one_device_allowed(hass, protocol, connection):
async def test_one_device_allowed(hass: HomeAssistant, protocol, connection) -> None:
"""Test that only one AlarmDecoder device is allowed."""
flow = config_flow.AlarmDecoderFlowHandler()
flow.hass = hass

View file

@ -85,7 +85,7 @@ async def test_setup(hass: HomeAssistant) -> None:
assert hass.states.get(ENTITY_ID).state == STATE_IDLE
async def test_fire(hass, mock_notifier):
async def test_fire(hass: HomeAssistant, mock_notifier: list[ServiceCall]) -> None:
"""Test the alert firing."""
assert await async_setup_component(hass, DOMAIN, TEST_CONFIG)
hass.states.async_set("sensor.test", STATE_ON)
@ -93,7 +93,7 @@ async def test_fire(hass, mock_notifier):
assert hass.states.get(ENTITY_ID).state == STATE_ON
async def test_silence(hass, mock_notifier):
async def test_silence(hass: HomeAssistant, mock_notifier: list[ServiceCall]) -> None:
"""Test silencing the alert."""
assert await async_setup_component(hass, DOMAIN, TEST_CONFIG)
hass.states.async_set("sensor.test", STATE_ON)
@ -116,7 +116,7 @@ async def test_silence(hass, mock_notifier):
assert hass.states.get(ENTITY_ID).state == STATE_ON
async def test_reset(hass, mock_notifier):
async def test_reset(hass: HomeAssistant, mock_notifier: list[ServiceCall]) -> None:
"""Test resetting the alert."""
assert await async_setup_component(hass, DOMAIN, TEST_CONFIG)
hass.states.async_set("sensor.test", STATE_ON)
@ -140,7 +140,7 @@ async def test_reset(hass, mock_notifier):
assert hass.states.get(ENTITY_ID).state == STATE_ON
async def test_toggle(hass, mock_notifier):
async def test_toggle(hass: HomeAssistant, mock_notifier: list[ServiceCall]) -> None:
"""Test toggling alert."""
assert await async_setup_component(hass, DOMAIN, TEST_CONFIG)
hass.states.async_set("sensor.test", STATE_ON)
@ -228,7 +228,9 @@ async def test_no_notifiers(
assert len(mock_notifier) == 0
async def test_sending_non_templated_notification(hass, mock_notifier):
async def test_sending_non_templated_notification(
hass: HomeAssistant, mock_notifier: list[ServiceCall]
) -> None:
"""Test notifications."""
assert await async_setup_component(hass, DOMAIN, TEST_CONFIG)
@ -239,7 +241,9 @@ async def test_sending_non_templated_notification(hass, mock_notifier):
assert last_event.data[notify.ATTR_MESSAGE] == NAME
async def test_sending_templated_notification(hass, mock_notifier):
async def test_sending_templated_notification(
hass: HomeAssistant, mock_notifier: list[ServiceCall]
) -> None:
"""Test templated notification."""
config = deepcopy(TEST_CONFIG)
config[DOMAIN][NAME][CONF_ALERT_MESSAGE] = TEMPLATE
@ -252,7 +256,9 @@ async def test_sending_templated_notification(hass, mock_notifier):
assert last_event.data[notify.ATTR_MESSAGE] == TEST_ENTITY
async def test_sending_templated_done_notification(hass, mock_notifier):
async def test_sending_templated_done_notification(
hass: HomeAssistant, mock_notifier: list[ServiceCall]
) -> None:
"""Test templated notification."""
config = deepcopy(TEST_CONFIG)
config[DOMAIN][NAME][CONF_DONE_MESSAGE] = TEMPLATE
@ -267,7 +273,9 @@ async def test_sending_templated_done_notification(hass, mock_notifier):
assert last_event.data[notify.ATTR_MESSAGE] == TEST_ENTITY
async def test_sending_titled_notification(hass, mock_notifier):
async def test_sending_titled_notification(
hass: HomeAssistant, mock_notifier: list[ServiceCall]
) -> None:
"""Test notifications."""
config = deepcopy(TEST_CONFIG)
config[DOMAIN][NAME][CONF_TITLE] = TITLE
@ -280,7 +288,9 @@ async def test_sending_titled_notification(hass, mock_notifier):
assert last_event.data[notify.ATTR_TITLE] == TEST_TITLE
async def test_sending_data_notification(hass, mock_notifier):
async def test_sending_data_notification(
hass: HomeAssistant, mock_notifier: list[ServiceCall]
) -> None:
"""Test notifications."""
config = deepcopy(TEST_CONFIG)
config[DOMAIN][NAME][CONF_DATA] = TEST_DATA

View file

@ -1,4 +1,5 @@
"""Test Alexa capabilities."""
from typing import Any
from unittest.mock import patch
import pytest
@ -34,7 +35,7 @@ from tests.common import async_mock_service
@pytest.mark.parametrize("adjust", ["-5", "5", "-80"])
async def test_api_adjust_brightness(hass, adjust):
async def test_api_adjust_brightness(hass: HomeAssistant, adjust: str) -> None:
"""Test api adjust brightness process."""
request = get_new_request(
"Alexa.BrightnessController", "AdjustBrightness", "light#test"
@ -119,7 +120,9 @@ async def test_api_set_color_temperature(hass: HomeAssistant) -> None:
@pytest.mark.parametrize("result,initial", [(383, "333"), (500, "500")])
async def test_api_decrease_color_temp(hass, result, initial):
async def test_api_decrease_color_temp(
hass: HomeAssistant, result: int, initial: str
) -> None:
"""Test api decrease color temp process."""
request = get_new_request(
"Alexa.ColorTemperatureController", "DecreaseColorTemperature", "light#test"
@ -147,7 +150,9 @@ async def test_api_decrease_color_temp(hass, result, initial):
@pytest.mark.parametrize("result,initial", [(283, "333"), (142, "142")])
async def test_api_increase_color_temp(hass, result, initial):
async def test_api_increase_color_temp(
hass: HomeAssistant, result: int, initial: str
) -> None:
"""Test api increase color temp process."""
request = get_new_request(
"Alexa.ColorTemperatureController", "IncreaseColorTemperature", "light#test"
@ -183,7 +188,13 @@ async def test_api_increase_color_temp(hass, result, initial):
("media_player", "BAD DEVICE", ["satellite_tv", "game console"], None),
],
)
async def test_api_select_input(hass, domain, payload, source_list, idx):
async def test_api_select_input(
hass: HomeAssistant,
domain: str,
payload: str,
source_list: list[Any],
idx: int | None,
) -> None:
"""Test api set input process."""
hass.states.async_set(
"media_player.test",
@ -249,7 +260,9 @@ async def test_report_lock_state(hass: HomeAssistant) -> None:
@pytest.mark.parametrize(
"supported_color_modes", [["brightness"], ["hs"], ["color_temp"]]
)
async def test_report_dimmable_light_state(hass, supported_color_modes):
async def test_report_dimmable_light_state(
hass: HomeAssistant, supported_color_modes: list[str]
) -> None:
"""Test BrightnessController reports brightness correctly."""
hass.states.async_set(
"light.test_on",
@ -277,7 +290,9 @@ async def test_report_dimmable_light_state(hass, supported_color_modes):
@pytest.mark.parametrize("supported_color_modes", [["hs"], ["rgb"], ["xy"]])
async def test_report_colored_light_state(hass, supported_color_modes):
async def test_report_colored_light_state(
hass: HomeAssistant, supported_color_modes: list[str]
) -> None:
"""Test ColorController reports color correctly."""
hass.states.async_set(
"light.test_on",
@ -934,7 +949,7 @@ async def test_report_image_processing(hass: HomeAssistant) -> None:
@pytest.mark.parametrize("domain", ["button", "input_button"])
async def test_report_button_pressed(hass, domain):
async def test_report_button_pressed(hass: HomeAssistant, domain: str) -> None:
"""Test button presses report human presence detection events.
For use to trigger routines.
@ -952,7 +967,9 @@ async def test_report_button_pressed(hass, domain):
@pytest.mark.parametrize("domain", ["switch", "input_boolean"])
async def test_toggle_entities_report_contact_events(hass, domain):
async def test_toggle_entities_report_contact_events(
hass: HomeAssistant, domain: str
) -> None:
"""Test toggles and switches report contact sensor events to trigger routines."""
hass.states.async_set(
f"{domain}.test_toggle", "on", {"friendly_name": "Test toggle"}

View file

@ -72,7 +72,7 @@ def _flash_briefing_req(client, briefing_id, password="pass%2Fabc"):
return client.get(f"/api/alexa/flash_briefings/{briefing_id}?password={password}")
async def test_flash_briefing_invalid_id(alexa_client):
async def test_flash_briefing_invalid_id(alexa_client) -> None:
"""Test an invalid Flash Briefing ID."""
req = await _flash_briefing_req(alexa_client, 10000)
assert req.status == HTTPStatus.NOT_FOUND
@ -80,7 +80,7 @@ async def test_flash_briefing_invalid_id(alexa_client):
assert text == ""
async def test_flash_briefing_no_password(alexa_client):
async def test_flash_briefing_no_password(alexa_client) -> None:
"""Test for no Flash Briefing password."""
req = await _flash_briefing_req(alexa_client, "weather", password=None)
assert req.status == HTTPStatus.UNAUTHORIZED
@ -88,7 +88,7 @@ async def test_flash_briefing_no_password(alexa_client):
assert text == ""
async def test_flash_briefing_invalid_password(alexa_client):
async def test_flash_briefing_invalid_password(alexa_client) -> None:
"""Test an invalid Flash Briefing password."""
req = await _flash_briefing_req(alexa_client, "weather", password="wrongpass")
assert req.status == HTTPStatus.UNAUTHORIZED
@ -96,7 +96,7 @@ async def test_flash_briefing_invalid_password(alexa_client):
assert text == ""
async def test_flash_briefing_request_for_password(alexa_client):
async def test_flash_briefing_request_for_password(alexa_client) -> None:
"""Test for "password" Flash Briefing."""
req = await _flash_briefing_req(alexa_client, "password")
assert req.status == HTTPStatus.NOT_FOUND
@ -104,7 +104,7 @@ async def test_flash_briefing_request_for_password(alexa_client):
assert text == ""
async def test_flash_briefing_date_from_str(alexa_client):
async def test_flash_briefing_date_from_str(alexa_client) -> None:
"""Test the response has a valid date parsed from string."""
req = await _flash_briefing_req(alexa_client, "weather")
assert req.status == HTTPStatus.OK
@ -117,7 +117,7 @@ async def test_flash_briefing_date_from_str(alexa_client):
)
async def test_flash_briefing_valid(alexa_client):
async def test_flash_briefing_valid(alexa_client) -> None:
"""Test the response is valid."""
data = [
{

View file

@ -1,5 +1,4 @@
"""The tests for the Alexa component."""
from http import HTTPStatus
import json
@ -8,7 +7,7 @@ import pytest
from homeassistant.components import alexa
from homeassistant.components.alexa import intent
from homeassistant.const import CONTENT_TYPE_JSON
from homeassistant.core import callback
from homeassistant.core import HomeAssistant, callback
from homeassistant.setup import async_setup_component
SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000"
@ -131,7 +130,7 @@ def _intent_req(client, data=None):
)
async def test_intent_launch_request(alexa_client):
async def test_intent_launch_request(alexa_client) -> None:
"""Test the launch of a request."""
data = {
"version": "1.0",
@ -156,7 +155,7 @@ async def test_intent_launch_request(alexa_client):
assert data.get("response", {}).get("shouldEndSession")
async def test_intent_launch_request_with_session_open(alexa_client):
async def test_intent_launch_request_with_session_open(alexa_client) -> None:
"""Test the launch of a request."""
data = {
"version": "1.0",
@ -185,7 +184,7 @@ async def test_intent_launch_request_with_session_open(alexa_client):
assert not data.get("response", {}).get("shouldEndSession")
async def test_intent_launch_request_not_configured(alexa_client):
async def test_intent_launch_request_not_configured(alexa_client) -> None:
"""Test the launch of a request."""
data = {
"version": "1.0",
@ -213,7 +212,7 @@ async def test_intent_launch_request_not_configured(alexa_client):
assert text == "This intent is not yet configured within Home Assistant."
async def test_intent_request_with_slots(alexa_client):
async def test_intent_request_with_slots(alexa_client) -> None:
"""Test a request with slots."""
data = {
"version": "1.0",
@ -247,7 +246,7 @@ async def test_intent_request_with_slots(alexa_client):
assert text == "You told us your sign is virgo."
async def test_intent_request_with_slots_and_synonym_resolution(alexa_client):
async def test_intent_request_with_slots_and_synonym_resolution(alexa_client) -> None:
"""Test a request with slots and a name synonym."""
data = {
"version": "1.0",
@ -300,7 +299,9 @@ async def test_intent_request_with_slots_and_synonym_resolution(alexa_client):
assert text == "You told us your sign is Virgo."
async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client):
async def test_intent_request_with_slots_and_multi_synonym_resolution(
alexa_client,
) -> None:
"""Test a request with slots and multiple name synonyms."""
data = {
"version": "1.0",
@ -353,7 +354,7 @@ async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_clie
assert text == "You told us your sign is V zodiac."
async def test_intent_request_with_slots_but_no_value(alexa_client):
async def test_intent_request_with_slots_but_no_value(alexa_client) -> None:
"""Test a request with slots but no value."""
data = {
"version": "1.0",
@ -387,7 +388,7 @@ async def test_intent_request_with_slots_but_no_value(alexa_client):
assert text == "You told us your sign is ."
async def test_intent_request_without_slots(hass, alexa_client):
async def test_intent_request_without_slots(hass: HomeAssistant, alexa_client) -> None:
"""Test a request without slots."""
data = {
"version": "1.0",
@ -428,7 +429,7 @@ async def test_intent_request_without_slots(hass, alexa_client):
assert text == "You are both home, you silly"
async def test_intent_request_calling_service(alexa_client):
async def test_intent_request_calling_service(alexa_client) -> None:
"""Test a request for calling a service."""
data = {
"version": "1.0",
@ -466,7 +467,7 @@ async def test_intent_request_calling_service(alexa_client):
assert data["response"]["outputSpeech"]["text"] == "Service called for virgo"
async def test_intent_session_ended_request(alexa_client):
async def test_intent_session_ended_request(alexa_client) -> None:
"""Test the request for ending the session."""
data = {
"version": "1.0",
@ -500,7 +501,7 @@ async def test_intent_session_ended_request(alexa_client):
)
async def test_intent_from_built_in_intent_library(alexa_client):
async def test_intent_from_built_in_intent_library(alexa_client) -> None:
"""Test intents from the Built-in Intent Library."""
data = {
"request": {

View file

@ -11,7 +11,7 @@ from homeassistant.components.media_player import MediaPlayerEntityFeature
import homeassistant.components.vacuum as vacuum
from homeassistant.config import async_process_ha_core_config
from homeassistant.const import STATE_UNKNOWN, UnitOfTemperature
from homeassistant.core import Context, HomeAssistant
from homeassistant.core import Context, Event, HomeAssistant
from homeassistant.helpers import entityfilter
from homeassistant.setup import async_setup_component
from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM
@ -32,13 +32,13 @@ from tests.common import async_capture_events, async_mock_service
@pytest.fixture
def events(hass):
def events(hass: HomeAssistant) -> list[Event]:
"""Fixture that catches alexa events."""
return async_capture_events(hass, smart_home.EVENT_ALEXA_SMART_HOME)
@pytest.fixture
async def mock_camera(hass):
async def mock_camera(hass: HomeAssistant) -> None:
"""Initialize a demo camera platform."""
assert await async_setup_component(
hass, "camera", {camera.DOMAIN: {"platform": "demo"}}
@ -47,7 +47,7 @@ async def mock_camera(hass):
@pytest.fixture
async def mock_stream(hass):
async def mock_stream(hass: HomeAssistant) -> None:
"""Initialize a demo camera platform with streaming."""
assert await async_setup_component(hass, "stream", {"stream": {}})
await hass.async_block_till_done()
@ -159,7 +159,7 @@ def assert_endpoint_capabilities(endpoint, *interfaces):
@freeze_time("2022-04-19 07:53:05")
async def test_switch(hass, events):
async def test_switch(hass: HomeAssistant, events: list[Event]) -> None:
"""Test switch discovery."""
device = ("switch.test", "on", {"friendly_name": "Test switch"})
appliance = await discovery_test(device, hass)
@ -191,7 +191,7 @@ async def test_switch(hass, events):
assert {"name": "detectionState"} in properties["supported"]
async def test_outlet(hass, events):
async def test_outlet(hass: HomeAssistant, events: list[Event]) -> None:
"""Test switch with device class outlet discovery."""
device = (
"switch.test",
@ -274,7 +274,9 @@ async def test_dimmable_light(hass: HomeAssistant) -> None:
"supported_color_modes",
[["color_temp", "hs"], ["color_temp", "rgb"], ["color_temp", "xy"]],
)
async def test_color_light(hass, supported_color_modes):
async def test_color_light(
hass: HomeAssistant, supported_color_modes: list[str]
) -> None:
"""Test color light discovery."""
device = (
"light.test_3",
@ -2614,7 +2616,7 @@ async def test_entity_config(hass: HomeAssistant) -> None:
assert scene["description"] == "Config description via Home Assistant (Scene)"
async def test_logging_request(hass, events):
async def test_logging_request(hass: HomeAssistant, events: list[Event]) -> None:
"""Test that we log requests."""
context = Context()
request = get_new_request("Alexa.Discovery", "Discover")
@ -2636,7 +2638,9 @@ async def test_logging_request(hass, events):
assert event.context == context
async def test_logging_request_with_entity(hass, events):
async def test_logging_request_with_entity(
hass: HomeAssistant, events: list[Event]
) -> None:
"""Test that we log requests."""
context = Context()
request = get_new_request("Alexa.PowerController", "TurnOn", "switch#xy")
@ -3348,7 +3352,7 @@ async def test_cover_semantics_position_and_tilt(hass: HomeAssistant) -> None:
@pytest.mark.parametrize("domain", ["input_number", "number"])
async def test_input_number(hass, domain: str):
async def test_input_number(hass: HomeAssistant, domain: str) -> None:
"""Test input_number and number discovery."""
device = (
f"{domain}.test_slider",
@ -3434,7 +3438,7 @@ async def test_input_number(hass, domain: str):
@pytest.mark.parametrize("domain", ["input_number", "number"])
async def test_input_number_float(hass, domain: str):
async def test_input_number_float(hass: HomeAssistant, domain: str) -> None:
"""Test input_number and number discovery."""
device = (
f"{domain}.test_slider_float",
@ -4065,7 +4069,7 @@ async def test_vacuum_discovery_no_turn_on_or_off(hass: HomeAssistant) -> None:
)
async def test_camera_discovery(hass, mock_stream):
async def test_camera_discovery(hass: HomeAssistant, mock_stream: None) -> None:
"""Test camera discovery."""
device = (
"camera.test",
@ -4125,7 +4129,9 @@ async def test_camera_discovery_without_stream(hass: HomeAssistant) -> None:
("https://correctschemaandport.org", 3),
],
)
async def test_camera_hass_urls(hass, mock_stream, url, result):
async def test_camera_hass_urls(
hass: HomeAssistant, mock_stream: None, url: str, result: int
) -> None:
"""Test camera discovery with unsupported urls."""
device = (
"camera.test",
@ -4138,7 +4144,9 @@ async def test_camera_hass_urls(hass, mock_stream, url, result):
assert len(appliance["capabilities"]) == result
async def test_initialize_camera_stream(hass, mock_camera, mock_stream):
async def test_initialize_camera_stream(
hass: HomeAssistant, mock_camera: None, mock_stream: None
) -> None:
"""Test InitializeCameraStreams handler."""
request = get_new_request(
"Alexa.CameraStreamController", "InitializeCameraStreams", "camera#demo_camera"
@ -4180,7 +4188,7 @@ async def test_initialize_camera_stream(hass, mock_camera, mock_stream):
"domain",
["button", "input_button"],
)
async def test_button(hass, domain):
async def test_button(hass: HomeAssistant, domain: str) -> None:
"""Test button discovery."""
device = (
f"{domain}.ring_doorbell",

View file

@ -52,7 +52,11 @@ async def test_report_state(
assert call_json["event"]["endpoint"]["endpointId"] == "binary_sensor#test_contact"
async def test_report_state_fail(hass, aioclient_mock, caplog):
async def test_report_state_fail(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test proactive state retries once."""
aioclient_mock.post(
TEST_URL,
@ -94,7 +98,11 @@ async def test_report_state_fail(hass, aioclient_mock, caplog):
) in caplog.text
async def test_report_state_timeout(hass, aioclient_mock, caplog):
async def test_report_state_timeout(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test proactive state retries once."""
aioclient_mock.post(
TEST_URL,
@ -191,8 +199,8 @@ async def test_report_state_unsets_authorized_on_error(
@pytest.mark.parametrize("exc", [errors.NoTokenAvailable, errors.RequireRelink])
async def test_report_state_unsets_authorized_on_access_token_error(
hass, aioclient_mock, exc
):
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, exc: Exception
) -> None:
"""Test proactive state unsets authorized on error."""
aioclient_mock.post(TEST_URL, text="", status=202)
@ -383,7 +391,14 @@ async def test_report_state_humidifier(
),
],
)
async def test_report_state_number(hass, aioclient_mock, domain, value, unit, label):
async def test_report_state_number(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
domain: str,
value: float,
unit: str | None,
label: AlexaGlobalCatalog,
) -> None:
"""Test proactive state reports with number or input_number instance."""
aioclient_mock.post(TEST_URL, text="", status=202)
state = {
@ -603,7 +618,11 @@ async def test_doorbell_event_from_unknown(
assert call_json["event"]["endpoint"]["endpointId"] == "binary_sensor#test_doorbell"
async def test_doorbell_event_fail(hass, aioclient_mock, caplog):
async def test_doorbell_event_fail(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test proactive state retries once."""
aioclient_mock.post(
TEST_URL,
@ -646,7 +665,11 @@ async def test_doorbell_event_fail(hass, aioclient_mock, caplog):
) in caplog.text
async def test_doorbell_event_timeout(hass, aioclient_mock, caplog):
async def test_doorbell_event_timeout(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test proactive state retries once."""
aioclient_mock.post(
TEST_URL,

View file

@ -8,6 +8,7 @@ from homeassistant import data_entry_flow
from homeassistant.components.ambient_station import CONF_APP_KEY, DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_API_KEY
from homeassistant.core import HomeAssistant
@pytest.mark.parametrize(
@ -18,8 +19,8 @@ from homeassistant.const import CONF_API_KEY
],
)
async def test_create_entry(
hass, api, config, devices_response, errors, mock_aioambient
):
hass: HomeAssistant, api, config, devices_response, errors, mock_aioambient
) -> None:
"""Test creating an entry."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
@ -47,7 +48,9 @@ async def test_create_entry(
}
async def test_duplicate_error(hass, config, config_entry, setup_config_entry):
async def test_duplicate_error(
hass: HomeAssistant, config, config_entry, setup_config_entry
) -> None:
"""Test that errors are shown when duplicates are added."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=config

View file

@ -1,13 +1,19 @@
"""Test Ambient PWS diagnostics."""
from homeassistant.components.ambient_station import DOMAIN
from homeassistant.components.diagnostics import REDACTED
from homeassistant.core import HomeAssistant
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, data_station, setup_config_entry
):
hass: HomeAssistant,
config_entry,
hass_client: ClientSessionGenerator,
data_station,
setup_config_entry,
) -> None:
"""Test config entry diagnostics."""
ambient = hass.data[DOMAIN][config_entry.entry_id]
ambient.stations = data_station

View file

@ -26,7 +26,11 @@ MOCK_VERSION_DEV = "1970.1.0.dev0"
MOCK_VERSION_NIGHTLY = "1970.1.0.dev19700101"
async def test_no_send(hass, caplog, aioclient_mock):
async def test_no_send(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test send when no preferences are defined."""
analytics = Analytics(hass)
with patch(
@ -75,7 +79,11 @@ async def test_load_with_supervisor_without_diagnostics(hass: HomeAssistant) ->
assert not analytics.preferences[ATTR_DIAGNOSTICS]
async def test_failed_to_send(hass, caplog, aioclient_mock):
async def test_failed_to_send(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test failed to send payload."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=400)
analytics = Analytics(hass)
@ -90,7 +98,11 @@ async def test_failed_to_send(hass, caplog, aioclient_mock):
)
async def test_failed_to_send_raises(hass, caplog, aioclient_mock):
async def test_failed_to_send_raises(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test raises when failed to send payload."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, exc=aiohttp.ClientError())
analytics = Analytics(hass)
@ -102,7 +114,11 @@ async def test_failed_to_send_raises(hass, caplog, aioclient_mock):
assert "Error sending analytics" in caplog.text
async def test_send_base(hass, caplog, aioclient_mock):
async def test_send_base(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test send base preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
analytics = Analytics(hass)
@ -123,7 +139,11 @@ async def test_send_base(hass, caplog, aioclient_mock):
assert "'integrations':" not in caplog.text
async def test_send_base_with_supervisor(hass, caplog, aioclient_mock):
async def test_send_base_with_supervisor(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test send base preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
@ -170,7 +190,11 @@ async def test_send_base_with_supervisor(hass, caplog, aioclient_mock):
assert "'integrations':" not in caplog.text
async def test_send_usage(hass, caplog, aioclient_mock):
async def test_send_usage(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test send usage preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
analytics = Analytics(hass)
@ -189,7 +213,11 @@ async def test_send_usage(hass, caplog, aioclient_mock):
assert "'certificate': False" in caplog.text
async def test_send_usage_with_supervisor(hass, caplog, aioclient_mock):
async def test_send_usage_with_supervisor(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test send usage with supervisor preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
analytics = Analytics(hass)
@ -242,7 +270,11 @@ async def test_send_usage_with_supervisor(hass, caplog, aioclient_mock):
assert "'addon_count':" not in caplog.text
async def test_send_statistics(hass, caplog, aioclient_mock):
async def test_send_statistics(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test send statistics preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
analytics = Analytics(hass)
@ -260,7 +292,11 @@ async def test_send_statistics(hass, caplog, aioclient_mock):
assert "'integrations':" not in caplog.text
async def test_send_statistics_one_integration_fails(hass, caplog, aioclient_mock):
async def test_send_statistics_one_integration_fails(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test send statistics preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
analytics = Analytics(hass)
@ -281,8 +317,10 @@ async def test_send_statistics_one_integration_fails(hass, caplog, aioclient_moc
async def test_send_statistics_async_get_integration_unknown_exception(
hass, caplog, aioclient_mock
):
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test send statistics preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
analytics = Analytics(hass)
@ -298,7 +336,11 @@ async def test_send_statistics_async_get_integration_unknown_exception(
await analytics.send_analytics()
async def test_send_statistics_with_supervisor(hass, caplog, aioclient_mock):
async def test_send_statistics_with_supervisor(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test send statistics preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
analytics = Analytics(hass)
@ -366,7 +408,11 @@ async def test_reusing_uuid(
assert analytics.uuid == "NOT_MOCK_UUID"
async def test_custom_integrations(hass, aioclient_mock, enable_custom_integrations):
async def test_custom_integrations(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
enable_custom_integrations: None,
) -> None:
"""Test sending custom integrations."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
analytics = Analytics(hass)
@ -398,7 +444,11 @@ async def test_dev_url(
assert str(payload[1]) == ANALYTICS_ENDPOINT_URL_DEV
async def test_dev_url_error(hass, aioclient_mock, caplog):
async def test_dev_url_error(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test sending payload to dev url that returns error."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL_DEV, status=400)
analytics = Analytics(hass)
@ -458,7 +508,9 @@ async def test_send_with_no_energy(
assert "energy" not in postdata
async def test_send_with_no_energy_config(recorder_mock, hass, aioclient_mock):
async def test_send_with_no_energy_config(
recorder_mock, hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test send base preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
analytics = Analytics(hass)
@ -480,7 +532,9 @@ async def test_send_with_no_energy_config(recorder_mock, hass, aioclient_mock):
assert not postdata["energy"]["configured"]
async def test_send_with_energy_config(recorder_mock, hass, aioclient_mock):
async def test_send_with_energy_config(
recorder_mock, hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test send base preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
analytics = Analytics(hass)
@ -502,7 +556,11 @@ async def test_send_with_energy_config(recorder_mock, hass, aioclient_mock):
assert postdata["energy"]["configured"]
async def test_send_usage_with_certificate(hass, caplog, aioclient_mock):
async def test_send_usage_with_certificate(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test send usage preferences with certificate."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
analytics = Analytics(hass)

View file

@ -5,6 +5,9 @@ from homeassistant.components.analytics.const import ANALYTICS_ENDPOINT_URL, DOM
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import WebSocketGenerator
MOCK_VERSION = "1970.1.0"
@ -16,7 +19,11 @@ async def test_setup(hass: HomeAssistant) -> None:
assert DOMAIN in hass.data
async def test_websocket(hass, hass_ws_client, aioclient_mock):
async def test_websocket(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test WebSocket commands."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})

View file

@ -1,4 +1,5 @@
"""Tests for the AndroidTV config flow."""
from typing import Any
from unittest.mock import patch
import pytest
@ -92,7 +93,12 @@ class MockConfigDevice:
(CONFIG_ADB_SERVER, ETH_MAC, WIFI_MAC),
],
)
async def test_user(hass, config, eth_mac, wifi_mac):
async def test_user(
hass: HomeAssistant,
config: dict[str, Any],
eth_mac: str | None,
wifi_mac: str | None,
) -> None:
"""Test user config."""
flow_result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER, "show_advanced_options": True}
@ -206,7 +212,12 @@ async def test_error_invalid_key(hass: HomeAssistant) -> None:
(CONFIG_PYTHON_ADB, None, INVALID_MAC),
],
)
async def test_invalid_mac(hass, config, eth_mac, wifi_mac):
async def test_invalid_mac(
hass: HomeAssistant,
config: dict[str, Any],
eth_mac: str | None,
wifi_mac: str | None,
) -> None:
"""Test for invalid mac address."""
with patch(
CONNECT_METHOD,

View file

@ -1,5 +1,6 @@
"""The tests for the androidtv platform."""
import logging
from typing import Any
from unittest.mock import Mock, patch
from adb_shell.exceptions import TcpTimeoutException as AdbShellTimeoutException
@ -219,7 +220,9 @@ def _setup(config):
CONFIG_FIRETV_ADB_SERVER,
],
)
async def test_reconnect(hass, caplog, config):
async def test_reconnect(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, config: dict[str, Any]
) -> None:
"""Test that the error and reconnection attempts are logged correctly.
"Handles device/service unavailable. Log a warning once when
@ -278,7 +281,9 @@ async def test_reconnect(hass, caplog, config):
CONFIG_FIRETV_ADB_SERVER,
],
)
async def test_adb_shell_returns_none(hass, config):
async def test_adb_shell_returns_none(
hass: HomeAssistant, config: dict[str, Any]
) -> None:
"""Test the case that the ADB shell command returns `None`.
The state should be `None` and the device should be unavailable.
@ -330,7 +335,7 @@ async def test_setup_with_adbkey(hass: HomeAssistant) -> None:
CONFIG_FIRETV_DEFAULT,
],
)
async def test_sources(hass, config):
async def test_sources(hass: HomeAssistant, config: dict[str, Any]) -> None:
"""Test that sources (i.e., apps) are handled correctly for Android TV and Fire TV devices."""
conf_apps = {
"com.app.test1": "TEST 1",
@ -396,7 +401,9 @@ async def test_sources(hass, config):
(CONFIG_FIRETV_DEFAULT, ["TEST 1"]),
],
)
async def test_exclude_sources(hass, config, expected_sources):
async def test_exclude_sources(
hass: HomeAssistant, config: dict[str, Any], expected_sources: list[str]
) -> None:
"""Test that sources (i.e., apps) are handled correctly when the `exclude_unnamed_apps` config parameter is provided."""
conf_apps = {
"com.app.test1": "TEST 1",
@ -487,7 +494,9 @@ async def _test_select_source(
("!com.app.test3", "com.app.test3", patchers.PATCH_STOP_APP),
],
)
async def test_select_source_androidtv(hass, source, expected_arg, method_patch):
async def test_select_source_androidtv(
hass: HomeAssistant, source, expected_arg, method_patch
) -> None:
"""Test that an app can be launched for AndroidTV."""
conf_apps = {
"com.app.test1": "TEST 1",
@ -529,7 +538,9 @@ async def test_androidtv_select_source_overridden_app_name(hass: HomeAssistant)
("!com.app.test3", "com.app.test3", patchers.PATCH_STOP_APP),
],
)
async def test_select_source_firetv(hass, source, expected_arg, method_patch):
async def test_select_source_firetv(
hass: HomeAssistant, source, expected_arg, method_patch
) -> None:
"""Test that an app can be launched for FireTV."""
conf_apps = {
"com.app.test1": "TEST 1",
@ -549,7 +560,9 @@ async def test_select_source_firetv(hass, source, expected_arg, method_patch):
(CONFIG_FIRETV_DEFAULT, True),
],
)
async def test_setup_fail(hass, config, connect):
async def test_setup_fail(
hass: HomeAssistant, config: dict[str, Any], connect: bool
) -> None:
"""Test that the entity is not created when the ADB connection is not established."""
patch_key, entity_id, config_entry = _setup(config)
config_entry.add_to_hass(hass)

View file

@ -10,6 +10,7 @@ import pytest
import homeassistant.components.apache_kafka as apache_kafka
from homeassistant.const import STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
APACHE_KAFKA_PATH = "homeassistant.components.apache_kafka"
@ -54,7 +55,9 @@ def mock_client_stop():
yield stop
async def test_minimal_config(hass, mock_client):
async def test_minimal_config(
hass: HomeAssistant, mock_client: MockKafkaClient
) -> None:
"""Test the minimal config and defaults of component."""
config = {apache_kafka.DOMAIN: MIN_CONFIG}
assert await async_setup_component(hass, apache_kafka.DOMAIN, config)
@ -62,7 +65,7 @@ async def test_minimal_config(hass, mock_client):
assert mock_client.start.called_once
async def test_full_config(hass, mock_client):
async def test_full_config(hass: HomeAssistant, mock_client: MockKafkaClient) -> None:
"""Test the full config of component."""
config = {
apache_kafka.DOMAIN: {
@ -105,7 +108,7 @@ async def _run_filter_tests(hass, tests, mock_client):
mock_client.send_and_wait.assert_not_called()
async def test_allowlist(hass, mock_client):
async def test_allowlist(hass: HomeAssistant, mock_client: MockKafkaClient) -> None:
"""Test an allowlist only config."""
await _setup(
hass,
@ -128,7 +131,7 @@ async def test_allowlist(hass, mock_client):
await _run_filter_tests(hass, tests, mock_client)
async def test_denylist(hass, mock_client):
async def test_denylist(hass: HomeAssistant, mock_client: MockKafkaClient) -> None:
"""Test a denylist only config."""
await _setup(
hass,
@ -151,7 +154,9 @@ async def test_denylist(hass, mock_client):
await _run_filter_tests(hass, tests, mock_client)
async def test_filtered_allowlist(hass, mock_client):
async def test_filtered_allowlist(
hass: HomeAssistant, mock_client: MockKafkaClient
) -> None:
"""Test an allowlist config with a filtering denylist."""
await _setup(
hass,
@ -175,7 +180,9 @@ async def test_filtered_allowlist(hass, mock_client):
await _run_filter_tests(hass, tests, mock_client)
async def test_filtered_denylist(hass, mock_client):
async def test_filtered_denylist(
hass: HomeAssistant, mock_client: MockKafkaClient
) -> None:
"""Test a denylist config with a filtering allowlist."""
await _setup(
hass,

View file

@ -1,29 +1,38 @@
"""The tests for the Home Assistant API component."""
from http import HTTPStatus
import json
from unittest.mock import patch
from aiohttp import web
from aiohttp.test_utils import TestClient
import pytest
import voluptuous as vol
from homeassistant import const
from homeassistant.auth.providers.legacy_api_password import (
LegacyApiPasswordAuthProvider,
)
from homeassistant.bootstrap import DATA_LOGGING
import homeassistant.core as ha
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from tests.common import async_mock_service
from tests.common import MockUser, async_mock_service
from tests.typing import ClientSessionGenerator
@pytest.fixture
def mock_api_client(hass, hass_client):
def mock_api_client(
hass: HomeAssistant, hass_client: ClientSessionGenerator
) -> TestClient:
"""Start the Home Assistant HTTP component and return admin API client."""
hass.loop.run_until_complete(async_setup_component(hass, "api", {}))
return hass.loop.run_until_complete(hass_client())
async def test_api_list_state_entities(hass, mock_api_client):
async def test_api_list_state_entities(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if the debug interface allows us to list state entities."""
hass.states.async_set("test.entity", "hello")
resp = await mock_api_client.get(const.URL_API_STATES)
@ -35,7 +44,7 @@ async def test_api_list_state_entities(hass, mock_api_client):
assert remote_data == local_data
async def test_api_get_state(hass, mock_api_client):
async def test_api_get_state(hass: HomeAssistant, mock_api_client: TestClient) -> None:
"""Test if the debug interface allows us to get a state."""
hass.states.async_set("hello.world", "nice", {"attr": 1})
resp = await mock_api_client.get("/api/states/hello.world")
@ -51,13 +60,17 @@ async def test_api_get_state(hass, mock_api_client):
assert data.attributes == state.attributes
async def test_api_get_non_existing_state(hass, mock_api_client):
async def test_api_get_non_existing_state(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if the debug interface allows us to get a state."""
resp = await mock_api_client.get("/api/states/does_not_exist")
assert resp.status == HTTPStatus.NOT_FOUND
async def test_api_state_change(hass, mock_api_client):
async def test_api_state_change(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if we can change the state of an entity that exists."""
hass.states.async_set("test.test", "not_to_be_set")
@ -69,7 +82,9 @@ async def test_api_state_change(hass, mock_api_client):
# pylint: disable=invalid-name
async def test_api_state_change_of_non_existing_entity(hass, mock_api_client):
async def test_api_state_change_of_non_existing_entity(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if changing a state of a non existing entity is possible."""
new_state = "debug_state_change"
@ -83,7 +98,9 @@ async def test_api_state_change_of_non_existing_entity(hass, mock_api_client):
# pylint: disable=invalid-name
async def test_api_state_change_with_bad_data(hass, mock_api_client):
async def test_api_state_change_with_bad_data(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if API sends appropriate error if we omit state."""
resp = await mock_api_client.post(
"/api/states/test_entity.that_does_not_exist", json={}
@ -93,7 +110,9 @@ async def test_api_state_change_with_bad_data(hass, mock_api_client):
# pylint: disable=invalid-name
async def test_api_state_change_to_zero_value(hass, mock_api_client):
async def test_api_state_change_to_zero_value(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if changing a state to a zero value is possible."""
resp = await mock_api_client.post(
"/api/states/test_entity.with_zero_state", json={"state": 0}
@ -109,7 +128,9 @@ async def test_api_state_change_to_zero_value(hass, mock_api_client):
# pylint: disable=invalid-name
async def test_api_state_change_push(hass, mock_api_client):
async def test_api_state_change_push(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if we can push a change the state of an entity."""
hass.states.async_set("test.test", "not_to_be_set")
@ -134,7 +155,9 @@ async def test_api_state_change_push(hass, mock_api_client):
# pylint: disable=invalid-name
async def test_api_fire_event_with_no_data(hass, mock_api_client):
async def test_api_fire_event_with_no_data(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if the API allows us to fire an event."""
test_value = []
@ -152,7 +175,9 @@ async def test_api_fire_event_with_no_data(hass, mock_api_client):
# pylint: disable=invalid-name
async def test_api_fire_event_with_data(hass, mock_api_client):
async def test_api_fire_event_with_data(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if the API allows us to fire an event."""
test_value = []
@ -175,7 +200,9 @@ async def test_api_fire_event_with_data(hass, mock_api_client):
# pylint: disable=invalid-name
async def test_api_fire_event_with_invalid_json(hass, mock_api_client):
async def test_api_fire_event_with_invalid_json(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if the API allows us to fire an event."""
test_value = []
@ -206,7 +233,7 @@ async def test_api_fire_event_with_invalid_json(hass, mock_api_client):
assert len(test_value) == 0
async def test_api_get_config(hass, mock_api_client):
async def test_api_get_config(hass: HomeAssistant, mock_api_client: TestClient) -> None:
"""Test the return of the configuration."""
resp = await mock_api_client.get(const.URL_API_CONFIG)
result = await resp.json()
@ -222,14 +249,18 @@ async def test_api_get_config(hass, mock_api_client):
assert hass.config.as_dict() == result
async def test_api_get_components(hass, mock_api_client):
async def test_api_get_components(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test the return of the components."""
resp = await mock_api_client.get(const.URL_API_COMPONENTS)
result = await resp.json()
assert set(result) == hass.config.components
async def test_api_get_event_listeners(hass, mock_api_client):
async def test_api_get_event_listeners(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if we can get the list of events being listened for."""
resp = await mock_api_client.get(const.URL_API_EVENTS)
data = await resp.json()
@ -242,7 +273,9 @@ async def test_api_get_event_listeners(hass, mock_api_client):
assert len(local) == 0
async def test_api_get_services(hass, mock_api_client):
async def test_api_get_services(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if we can get a dict describing current services."""
resp = await mock_api_client.get(const.URL_API_SERVICES)
data = await resp.json()
@ -254,7 +287,9 @@ async def test_api_get_services(hass, mock_api_client):
assert serv_domain["services"] == local
async def test_api_call_service_no_data(hass, mock_api_client):
async def test_api_call_service_no_data(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if the API allows us to call a service."""
test_value = []
@ -270,7 +305,9 @@ async def test_api_call_service_no_data(hass, mock_api_client):
assert len(test_value) == 1
async def test_api_call_service_with_data(hass, mock_api_client):
async def test_api_call_service_with_data(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if the API allows us to call a service."""
@ha.callback
@ -299,7 +336,7 @@ async def test_api_call_service_with_data(hass, mock_api_client):
assert state["attributes"] == {"data": 1}
async def test_api_template(hass, mock_api_client):
async def test_api_template(hass: HomeAssistant, mock_api_client: TestClient) -> None:
"""Test the template API."""
hass.states.async_set("sensor.temperature", 10)
@ -313,7 +350,9 @@ async def test_api_template(hass, mock_api_client):
assert body == "10"
async def test_api_template_error(hass, mock_api_client):
async def test_api_template_error(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test the template API."""
hass.states.async_set("sensor.temperature", 10)
@ -324,7 +363,7 @@ async def test_api_template_error(hass, mock_api_client):
assert resp.status == HTTPStatus.BAD_REQUEST
async def test_stream(hass, mock_api_client):
async def test_stream(hass: HomeAssistant, mock_api_client: TestClient) -> None:
"""Test the stream."""
listen_count = _listen_count(hass)
@ -339,7 +378,9 @@ async def test_stream(hass, mock_api_client):
assert data["event_type"] == "test_event"
async def test_stream_with_restricted(hass, mock_api_client):
async def test_stream_with_restricted(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test the stream with restrictions."""
listen_count = _listen_count(hass)
@ -379,14 +420,17 @@ async def _stream_next_event(stream):
return json.loads(conv)
def _listen_count(hass):
def _listen_count(hass: HomeAssistant) -> int:
"""Return number of event listeners."""
return sum(hass.bus.async_listeners().values())
async def test_api_error_log(
hass, hass_client_no_auth, hass_access_token, hass_admin_user
):
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
hass_access_token: str,
hass_admin_user: MockUser,
) -> None:
"""Test if we can fetch the error log."""
hass.data[DATA_LOGGING] = "/some/path"
await async_setup_component(hass, "api", {})
@ -418,7 +462,9 @@ async def test_api_error_log(
assert resp.status == HTTPStatus.UNAUTHORIZED
async def test_api_fire_event_context(hass, mock_api_client, hass_access_token):
async def test_api_fire_event_context(
hass: HomeAssistant, mock_api_client: TestClient, hass_access_token: str
) -> None:
"""Test if the API sets right context if we fire an event."""
test_value = []
@ -441,7 +487,9 @@ async def test_api_fire_event_context(hass, mock_api_client, hass_access_token):
assert test_value[0].context.user_id == refresh_token.user.id
async def test_api_call_service_context(hass, mock_api_client, hass_access_token):
async def test_api_call_service_context(
hass: HomeAssistant, mock_api_client: TestClient, hass_access_token: str
) -> None:
"""Test if the API sets right context if we call a service."""
calls = async_mock_service(hass, "test_domain", "test_service")
@ -457,7 +505,9 @@ async def test_api_call_service_context(hass, mock_api_client, hass_access_token
assert calls[0].context.user_id == refresh_token.user.id
async def test_api_set_state_context(hass, mock_api_client, hass_access_token):
async def test_api_set_state_context(
hass: HomeAssistant, mock_api_client: TestClient, hass_access_token: str
) -> None:
"""Test if the API sets right context if we set state."""
await mock_api_client.post(
"/api/states/light.kitchen",
@ -471,14 +521,18 @@ async def test_api_set_state_context(hass, mock_api_client, hass_access_token):
assert state.context.user_id == refresh_token.user.id
async def test_event_stream_requires_admin(hass, mock_api_client, hass_admin_user):
async def test_event_stream_requires_admin(
hass: HomeAssistant, mock_api_client: TestClient, hass_admin_user: MockUser
) -> None:
"""Test user needs to be admin to access event stream."""
hass_admin_user.groups = []
resp = await mock_api_client.get("/api/stream")
assert resp.status == HTTPStatus.UNAUTHORIZED
async def test_states_view_filters(hass, mock_api_client, hass_admin_user):
async def test_states_view_filters(
hass: HomeAssistant, mock_api_client: TestClient, hass_admin_user: MockUser
) -> None:
"""Test filtering only visible states."""
hass_admin_user.mock_policy({"entities": {"entity_ids": {"test.entity": True}}})
hass.states.async_set("test.entity", "hello")
@ -490,35 +544,45 @@ async def test_states_view_filters(hass, mock_api_client, hass_admin_user):
assert json[0]["entity_id"] == "test.entity"
async def test_get_entity_state_read_perm(hass, mock_api_client, hass_admin_user):
async def test_get_entity_state_read_perm(
hass: HomeAssistant, mock_api_client: TestClient, hass_admin_user: MockUser
) -> None:
"""Test getting a state requires read permission."""
hass_admin_user.mock_policy({})
resp = await mock_api_client.get("/api/states/light.test")
assert resp.status == HTTPStatus.UNAUTHORIZED
async def test_post_entity_state_admin(hass, mock_api_client, hass_admin_user):
async def test_post_entity_state_admin(
hass: HomeAssistant, mock_api_client: TestClient, hass_admin_user: MockUser
) -> None:
"""Test updating state requires admin."""
hass_admin_user.groups = []
resp = await mock_api_client.post("/api/states/light.test")
assert resp.status == HTTPStatus.UNAUTHORIZED
async def test_delete_entity_state_admin(hass, mock_api_client, hass_admin_user):
async def test_delete_entity_state_admin(
hass: HomeAssistant, mock_api_client: TestClient, hass_admin_user: MockUser
) -> None:
"""Test deleting entity requires admin."""
hass_admin_user.groups = []
resp = await mock_api_client.delete("/api/states/light.test")
assert resp.status == HTTPStatus.UNAUTHORIZED
async def test_post_event_admin(hass, mock_api_client, hass_admin_user):
async def test_post_event_admin(
hass: HomeAssistant, mock_api_client: TestClient, hass_admin_user: MockUser
) -> None:
"""Test sending event requires admin."""
hass_admin_user.groups = []
resp = await mock_api_client.post("/api/events/state_changed")
assert resp.status == HTTPStatus.UNAUTHORIZED
async def test_rendering_template_admin(hass, mock_api_client, hass_admin_user):
async def test_rendering_template_admin(
hass: HomeAssistant, mock_api_client: TestClient, hass_admin_user: MockUser
) -> None:
"""Test rendering a template requires admin."""
hass_admin_user.groups = []
resp = await mock_api_client.post(const.URL_API_TEMPLATE)
@ -526,8 +590,11 @@ async def test_rendering_template_admin(hass, mock_api_client, hass_admin_user):
async def test_rendering_template_legacy_user(
hass, mock_api_client, aiohttp_client, legacy_auth
):
hass: HomeAssistant,
mock_api_client: TestClient,
aiohttp_client: ClientSessionGenerator,
legacy_auth: LegacyApiPasswordAuthProvider,
) -> None:
"""Test rendering a template with legacy API password."""
hass.states.async_set("sensor.temperature", 10)
client = await aiohttp_client(hass.http.app)
@ -538,13 +605,17 @@ async def test_rendering_template_legacy_user(
assert resp.status == HTTPStatus.UNAUTHORIZED
async def test_api_call_service_not_found(hass, mock_api_client):
async def test_api_call_service_not_found(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if the API fails 400 if unknown service."""
resp = await mock_api_client.post("/api/services/test_domain/test_service")
assert resp.status == HTTPStatus.BAD_REQUEST
async def test_api_call_service_bad_data(hass, mock_api_client):
async def test_api_call_service_bad_data(
hass: HomeAssistant, mock_api_client: TestClient
) -> None:
"""Test if the API fails 400 if unknown service."""
test_value = []

View file

@ -66,7 +66,7 @@ def mock_setup_entry():
# User Flows
async def test_user_input_device_not_found(hass, mrp_device):
async def test_user_input_device_not_found(hass: HomeAssistant, mrp_device) -> None:
"""Test when user specifies a non-existing device."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -83,7 +83,7 @@ async def test_user_input_device_not_found(hass, mrp_device):
assert result2["errors"] == {"base": "no_devices_found"}
async def test_user_input_unexpected_error(hass, mock_scan):
async def test_user_input_unexpected_error(hass: HomeAssistant, mock_scan) -> None:
"""Test that unexpected error yields an error message."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -99,7 +99,7 @@ async def test_user_input_unexpected_error(hass, mock_scan):
assert result2["errors"] == {"base": "unknown"}
async def test_user_adds_full_device(hass, full_device, pairing):
async def test_user_adds_full_device(hass: HomeAssistant, full_device, pairing) -> None:
"""Test adding device with all services."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -147,7 +147,9 @@ async def test_user_adds_full_device(hass, full_device, pairing):
}
async def test_user_adds_dmap_device(hass, dmap_device, dmap_pin, pairing):
async def test_user_adds_dmap_device(
hass: HomeAssistant, dmap_device, dmap_pin, pairing
) -> None:
"""Test adding device with only DMAP service."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -179,7 +181,9 @@ async def test_user_adds_dmap_device(hass, dmap_device, dmap_pin, pairing):
}
async def test_user_adds_dmap_device_failed(hass, dmap_device, dmap_pin, pairing):
async def test_user_adds_dmap_device_failed(
hass: HomeAssistant, dmap_device, dmap_pin, pairing
) -> None:
"""Test adding DMAP device where remote device did not attempt to pair."""
pairing.always_fail = True
@ -200,8 +204,8 @@ async def test_user_adds_dmap_device_failed(hass, dmap_device, dmap_pin, pairing
async def test_user_adds_device_with_ip_filter(
hass, dmap_device_with_credentials, mock_scan
):
hass: HomeAssistant, dmap_device_with_credentials, mock_scan
) -> None:
"""Test add device filtering by IP."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -219,7 +223,9 @@ async def test_user_adds_device_with_ip_filter(
@pytest.mark.parametrize("pairing_requirement", [(PairingRequirement.NotNeeded)])
async def test_user_pair_no_interaction(hass, dmap_with_requirement, pairing_mock):
async def test_user_pair_no_interaction(
hass: HomeAssistant, dmap_with_requirement, pairing_mock
) -> None:
"""Test pairing service without user interaction."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -242,7 +248,9 @@ async def test_user_pair_no_interaction(hass, dmap_with_requirement, pairing_moc
}
async def test_user_adds_device_by_ip_uses_unicast_scan(hass, mock_scan):
async def test_user_adds_device_by_ip_uses_unicast_scan(
hass: HomeAssistant, mock_scan
) -> None:
"""Test add device by IP-address, verify unicast scan is used."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -256,7 +264,7 @@ async def test_user_adds_device_by_ip_uses_unicast_scan(hass, mock_scan):
assert str(mock_scan.hosts[0]) == "127.0.0.1"
async def test_user_adds_existing_device(hass, mrp_device):
async def test_user_adds_existing_device(hass: HomeAssistant, mrp_device) -> None:
"""Test that it is not possible to add existing device."""
MockConfigEntry(domain="apple_tv", unique_id="mrpid").add_to_hass(hass)
@ -272,7 +280,9 @@ async def test_user_adds_existing_device(hass, mrp_device):
assert result2["errors"] == {"base": "already_configured"}
async def test_user_connection_failed(hass, mrp_device, pairing_mock):
async def test_user_connection_failed(
hass: HomeAssistant, mrp_device, pairing_mock
) -> None:
"""Test error message when connection to device fails."""
pairing_mock.begin.side_effect = exceptions.ConnectionFailedError
@ -298,7 +308,9 @@ async def test_user_connection_failed(hass, mrp_device, pairing_mock):
assert result2["reason"] == "setup_failed"
async def test_user_start_pair_error_failed(hass, mrp_device, pairing_mock):
async def test_user_start_pair_error_failed(
hass: HomeAssistant, mrp_device, pairing_mock
) -> None:
"""Test initiating pairing fails."""
pairing_mock.begin.side_effect = exceptions.PairingError
@ -320,8 +332,8 @@ async def test_user_start_pair_error_failed(hass, mrp_device, pairing_mock):
async def test_user_pair_service_with_password(
hass, airplay_device_with_password, pairing_mock
):
hass: HomeAssistant, airplay_device_with_password, pairing_mock
) -> None:
"""Test pairing with service requiring a password (not supported)."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -348,7 +360,9 @@ async def test_user_pair_service_with_password(
@pytest.mark.parametrize("pairing_requirement", [(PairingRequirement.Disabled)])
async def test_user_pair_disabled_service(hass, dmap_with_requirement, pairing_mock):
async def test_user_pair_disabled_service(
hass: HomeAssistant, dmap_with_requirement, pairing_mock
) -> None:
"""Test pairing with disabled service (is ignored with message)."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -375,7 +389,9 @@ async def test_user_pair_disabled_service(hass, dmap_with_requirement, pairing_m
@pytest.mark.parametrize("pairing_requirement", [(PairingRequirement.Unsupported)])
async def test_user_pair_ignore_unsupported(hass, dmap_with_requirement, pairing_mock):
async def test_user_pair_ignore_unsupported(
hass: HomeAssistant, dmap_with_requirement, pairing_mock
) -> None:
"""Test pairing with disabled service (is ignored silently)."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -394,7 +410,9 @@ async def test_user_pair_ignore_unsupported(hass, dmap_with_requirement, pairing
assert result["reason"] == "setup_failed"
async def test_user_pair_invalid_pin(hass, mrp_device, pairing_mock):
async def test_user_pair_invalid_pin(
hass: HomeAssistant, mrp_device, pairing_mock
) -> None:
"""Test pairing with invalid pin."""
pairing_mock.finish.side_effect = exceptions.PairingError
@ -420,7 +438,9 @@ async def test_user_pair_invalid_pin(hass, mrp_device, pairing_mock):
assert result2["errors"] == {"base": "invalid_auth"}
async def test_user_pair_unexpected_error(hass, mrp_device, pairing_mock):
async def test_user_pair_unexpected_error(
hass: HomeAssistant, mrp_device, pairing_mock
) -> None:
"""Test unexpected error when entering PIN code."""
pairing_mock.finish.side_effect = Exception
@ -446,7 +466,9 @@ async def test_user_pair_unexpected_error(hass, mrp_device, pairing_mock):
assert result2["errors"] == {"base": "unknown"}
async def test_user_pair_backoff_error(hass, mrp_device, pairing_mock):
async def test_user_pair_backoff_error(
hass: HomeAssistant, mrp_device, pairing_mock
) -> None:
"""Test that backoff error is displayed in case device requests it."""
pairing_mock.begin.side_effect = exceptions.BackOffError
@ -467,7 +489,9 @@ async def test_user_pair_backoff_error(hass, mrp_device, pairing_mock):
assert result2["reason"] == "backoff"
async def test_user_pair_begin_unexpected_error(hass, mrp_device, pairing_mock):
async def test_user_pair_begin_unexpected_error(
hass: HomeAssistant, mrp_device, pairing_mock
) -> None:
"""Test unexpected error during start of pairing."""
pairing_mock.begin.side_effect = Exception
@ -488,7 +512,9 @@ async def test_user_pair_begin_unexpected_error(hass, mrp_device, pairing_mock):
assert result2["reason"] == "unknown"
async def test_ignores_disabled_service(hass, airplay_with_disabled_mrp, pairing):
async def test_ignores_disabled_service(
hass: HomeAssistant, airplay_with_disabled_mrp, pairing
) -> None:
"""Test adding device with only DMAP service."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -545,7 +571,9 @@ async def test_zeroconf_unsupported_service_aborts(hass: HomeAssistant) -> None:
assert result["reason"] == "unknown"
async def test_zeroconf_add_mrp_device(hass, mrp_device, pairing):
async def test_zeroconf_add_mrp_device(
hass: HomeAssistant, mrp_device, pairing
) -> None:
"""Test add MRP device discovered by zeroconf."""
unrelated_result = await hass.config_entries.flow.async_init(
DOMAIN,
@ -600,7 +628,9 @@ async def test_zeroconf_add_mrp_device(hass, mrp_device, pairing):
}
async def test_zeroconf_add_dmap_device(hass, dmap_device, dmap_pin, pairing):
async def test_zeroconf_add_dmap_device(
hass: HomeAssistant, dmap_device, dmap_pin, pairing
) -> None:
"""Test add DMAP device discovered by zeroconf."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_ZEROCONF}, data=DMAP_SERVICE
@ -628,7 +658,7 @@ async def test_zeroconf_add_dmap_device(hass, dmap_device, dmap_pin, pairing):
}
async def test_zeroconf_ip_change(hass, mock_scan):
async def test_zeroconf_ip_change(hass: HomeAssistant, mock_scan) -> None:
"""Test that the config entry gets updated when the ip changes and reloads."""
entry = MockConfigEntry(
domain="apple_tv", unique_id="mrpid", data={CONF_ADDRESS: "127.0.0.2"}
@ -661,7 +691,9 @@ async def test_zeroconf_ip_change(hass, mock_scan):
assert unrelated_entry.data[CONF_ADDRESS] == "127.0.0.2"
async def test_zeroconf_ip_change_via_secondary_identifier(hass, mock_scan):
async def test_zeroconf_ip_change_via_secondary_identifier(
hass: HomeAssistant, mock_scan
) -> None:
"""Test that the config entry gets updated when the ip changes and reloads.
Instead of checking only the unique id, all the identifiers
@ -700,7 +732,7 @@ async def test_zeroconf_ip_change_via_secondary_identifier(hass, mock_scan):
assert unrelated_entry.data[CONF_ADDRESS] == "127.0.0.2"
async def test_zeroconf_add_existing_aborts(hass, dmap_device):
async def test_zeroconf_add_existing_aborts(hass: HomeAssistant, dmap_device) -> None:
"""Test start new zeroconf flow while existing flow is active aborts."""
await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_ZEROCONF}, data=DMAP_SERVICE
@ -713,7 +745,9 @@ async def test_zeroconf_add_existing_aborts(hass, dmap_device):
assert result["reason"] == "already_in_progress"
async def test_zeroconf_add_but_device_not_found(hass, mock_scan):
async def test_zeroconf_add_but_device_not_found(
hass: HomeAssistant, mock_scan
) -> None:
"""Test add device which is not found with another scan."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_ZEROCONF}, data=DMAP_SERVICE
@ -722,7 +756,7 @@ async def test_zeroconf_add_but_device_not_found(hass, mock_scan):
assert result["reason"] == "no_devices_found"
async def test_zeroconf_add_existing_device(hass, dmap_device):
async def test_zeroconf_add_existing_device(hass: HomeAssistant, dmap_device) -> None:
"""Test add already existing device from zeroconf."""
MockConfigEntry(domain="apple_tv", unique_id="dmapid").add_to_hass(hass)
@ -733,7 +767,7 @@ async def test_zeroconf_add_existing_device(hass, dmap_device):
assert result["reason"] == "already_configured"
async def test_zeroconf_unexpected_error(hass, mock_scan):
async def test_zeroconf_unexpected_error(hass: HomeAssistant, mock_scan) -> None:
"""Test unexpected error aborts in zeroconf."""
mock_scan.side_effect = Exception
@ -744,7 +778,9 @@ async def test_zeroconf_unexpected_error(hass, mock_scan):
assert result["reason"] == "unknown"
async def test_zeroconf_abort_if_other_in_progress(hass, mock_scan):
async def test_zeroconf_abort_if_other_in_progress(
hass: HomeAssistant, mock_scan
) -> None:
"""Test discovering unsupported zeroconf service."""
mock_scan.result = [
create_conf(IPv4Address("127.0.0.1"), "Device", airplay_service())
@ -791,8 +827,8 @@ async def test_zeroconf_abort_if_other_in_progress(hass, mock_scan):
async def test_zeroconf_missing_device_during_protocol_resolve(
hass, mock_scan, pairing, mock_zeroconf
):
hass: HomeAssistant, mock_scan, pairing, mock_zeroconf: None
) -> None:
"""Test discovery after service been added to existing flow with missing device."""
mock_scan.result = [
create_conf(IPv4Address("127.0.0.1"), "Device", airplay_service())
@ -849,8 +885,8 @@ async def test_zeroconf_missing_device_during_protocol_resolve(
async def test_zeroconf_additional_protocol_resolve_failure(
hass, mock_scan, pairing, mock_zeroconf
):
hass: HomeAssistant, mock_scan, pairing, mock_zeroconf: None
) -> None:
"""Test discovery with missing service."""
mock_scan.result = [
create_conf(IPv4Address("127.0.0.1"), "Device", airplay_service())
@ -909,8 +945,8 @@ async def test_zeroconf_additional_protocol_resolve_failure(
async def test_zeroconf_pair_additionally_found_protocols(
hass, mock_scan, pairing, mock_zeroconf
):
hass: HomeAssistant, mock_scan, pairing, mock_zeroconf: None
) -> None:
"""Test discovered protocols are merged to original flow."""
mock_scan.result = [
create_conf(IPv4Address("127.0.0.1"), "Device", airplay_service())
@ -1013,7 +1049,9 @@ async def test_zeroconf_pair_additionally_found_protocols(
# Re-configuration
async def test_reconfigure_update_credentials(hass, mrp_device, pairing):
async def test_reconfigure_update_credentials(
hass: HomeAssistant, mrp_device, pairing
) -> None:
"""Test that reconfigure flow updates config entry."""
config_entry = MockConfigEntry(
domain="apple_tv", unique_id="mrpid", data={"identifiers": ["mrpid"]}

View file

@ -1,5 +1,4 @@
"""Test the Developer Credentials integration."""
from __future__ import annotations
from collections.abc import Callable, Generator
@ -30,6 +29,7 @@ from homeassistant.helpers import config_entry_oauth2_flow
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, mock_platform
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import ClientSessionGenerator, WebSocketGenerator
CLIENT_ID = "some-client-id"
@ -223,13 +223,13 @@ async def ws_client(hass_ws_client: WebSocketGenerator) -> ClientFixture:
return create_client
async def test_websocket_list_empty(ws_client: ClientFixture):
async def test_websocket_list_empty(ws_client: ClientFixture) -> None:
"""Test websocket list command."""
client = await ws_client()
assert await client.cmd_result("list") == []
async def test_websocket_create(ws_client: ClientFixture):
async def test_websocket_create(ws_client: ClientFixture) -> None:
"""Test websocket create command."""
client = await ws_client()
result = await client.cmd_result(
@ -258,7 +258,7 @@ async def test_websocket_create(ws_client: ClientFixture):
]
async def test_websocket_create_invalid_domain(ws_client: ClientFixture):
async def test_websocket_create_invalid_domain(ws_client: ClientFixture) -> None:
"""Test websocket create command."""
client = await ws_client()
resp = await client.cmd(
@ -278,7 +278,7 @@ async def test_websocket_create_invalid_domain(ws_client: ClientFixture):
)
async def test_websocket_update_not_supported(ws_client: ClientFixture):
async def test_websocket_update_not_supported(ws_client: ClientFixture) -> None:
"""Test websocket update command in unsupported."""
client = await ws_client()
result = await client.cmd_result(
@ -303,7 +303,7 @@ async def test_websocket_update_not_supported(ws_client: ClientFixture):
assert resp["error"].get("message") == "Updates not supported"
async def test_websocket_delete(ws_client: ClientFixture):
async def test_websocket_delete(ws_client: ClientFixture) -> None:
"""Test websocket delete command."""
client = await ws_client()
@ -328,7 +328,7 @@ async def test_websocket_delete(ws_client: ClientFixture):
assert await client.cmd_result("list") == []
async def test_websocket_delete_item_not_found(ws_client: ClientFixture):
async def test_websocket_delete_item_not_found(ws_client: ClientFixture) -> None:
"""Test websocket delete command."""
client = await ws_client()
@ -347,7 +347,7 @@ async def test_websocket_import_config(
ws_client: ClientFixture,
config_credential: ClientCredential,
import_config_credential: Any,
):
) -> None:
"""Test websocket list command for an imported credential."""
client = await ws_client()
@ -374,7 +374,7 @@ async def test_import_duplicate_credentials(
ws_client: ClientFixture,
config_credential: ClientCredential,
import_config_credential: Any,
):
) -> None:
"""Exercise duplicate credentials are ignored."""
# Import the test credential again and verify it is not imported twice
@ -397,7 +397,7 @@ async def test_import_named_credential(
ws_client: ClientFixture,
config_credential: ClientCredential,
import_config_credential: Any,
):
) -> None:
"""Test websocket list command for an imported credential."""
client = await ws_client()
@ -427,7 +427,7 @@ async def test_config_flow_other_domain(
hass: HomeAssistant,
ws_client: ClientFixture,
authorization_server: AuthorizationServer,
):
) -> None:
"""Test config flow ignores credentials for another domain."""
await setup_application_credentials_integration(
hass,
@ -454,7 +454,7 @@ async def test_config_flow(
hass: HomeAssistant,
ws_client: ClientFixture,
oauth_fixture: OAuthFixture,
):
) -> None:
"""Test config flow with application credential registered."""
client = await ws_client()
@ -511,7 +511,7 @@ async def test_config_flow_multiple_entries(
hass: HomeAssistant,
ws_client: ClientFixture,
oauth_fixture: OAuthFixture,
):
) -> None:
"""Test config flow with multiple application credentials registered."""
client = await ws_client()
@ -554,7 +554,7 @@ async def test_config_flow_create_delete_credential(
hass: HomeAssistant,
ws_client: ClientFixture,
oauth_fixture: OAuthFixture,
):
) -> None:
"""Test adding and deleting a credential unregisters from the config flow."""
client = await ws_client()
@ -577,13 +577,13 @@ async def test_config_flow_create_delete_credential(
@pytest.mark.parametrize("config_credential", [DEVELOPER_CREDENTIAL])
async def test_config_flow_with_config_credential(
hass,
hass_client_no_auth,
aioclient_mock,
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
aioclient_mock: AiohttpClientMocker,
oauth_fixture,
config_credential,
import_config_credential,
):
) -> None:
"""Test config flow with application credential registered."""
result = await hass.config_entries.flow.async_init(
TEST_DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -596,7 +596,7 @@ async def test_config_flow_with_config_credential(
@pytest.mark.parametrize("mock_application_credentials_integration", [None])
async def test_import_without_setup(hass, config_credential):
async def test_import_without_setup(hass: HomeAssistant, config_credential) -> None:
"""Test import of credentials without setting up the integration."""
with pytest.raises(ValueError):
@ -613,7 +613,7 @@ async def test_import_without_setup(hass, config_credential):
@pytest.mark.parametrize("mock_application_credentials_integration", [None])
async def test_websocket_without_platform(
hass: HomeAssistant, ws_client: ClientFixture
):
) -> None:
"""Test an integration without the application credential platform."""
assert await async_setup_component(hass, "application_credentials", {})
hass.config.components.add(TEST_DOMAIN)
@ -642,7 +642,7 @@ async def test_websocket_without_platform(
@pytest.mark.parametrize("mock_application_credentials_integration", [None])
async def test_websocket_without_authorization_server(
hass: HomeAssistant, ws_client: ClientFixture
):
) -> None:
"""Test platform with incorrect implementation."""
assert await async_setup_component(hass, "application_credentials", {})
hass.config.components.add(TEST_DOMAIN)
@ -679,14 +679,14 @@ async def test_websocket_without_authorization_server(
@pytest.mark.parametrize("config_credential", [DEVELOPER_CREDENTIAL])
async def test_platform_with_auth_implementation(
hass,
hass_client_no_auth,
aioclient_mock,
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
aioclient_mock: AiohttpClientMocker,
oauth_fixture,
config_credential,
import_config_credential,
authorization_server,
):
) -> None:
"""Test config flow with custom OAuth2 implementation."""
assert await async_setup_component(hass, "application_credentials", {})
@ -717,7 +717,7 @@ async def test_platform_with_auth_implementation(
assert result["data"].get("auth_implementation") == TEST_DOMAIN
async def test_websocket_integration_list(ws_client: ClientFixture):
async def test_websocket_integration_list(ws_client: ClientFixture) -> None:
"""Test websocket integration list command."""
client = await ws_client()
with patch(
@ -734,7 +734,7 @@ async def test_websocket_integration_list(ws_client: ClientFixture):
async def test_name(
hass: HomeAssistant, ws_client: ClientFixture, oauth_fixture: OAuthFixture
):
) -> None:
"""Test a credential with a name set."""
client = await ws_client()
result = await client.cmd_result(
@ -780,7 +780,7 @@ async def test_remove_config_entry_without_app_credentials(
hass: HomeAssistant,
ws_client: ClientFixture,
authorization_server: AuthorizationServer,
):
) -> None:
"""Test config entry removal for non-app credentials integration."""
hass.config.components.add("other_domain")
config_entry = MockConfigEntry(domain="other_domain")
@ -797,7 +797,7 @@ async def test_remove_config_entry_without_app_credentials(
assert "application_credential_id" not in result
async def test_websocket_create_strips_whitespace(ws_client: ClientFixture):
async def test_websocket_create_strips_whitespace(ws_client: ClientFixture) -> None:
"""Test websocket create command with whitespace in the credentials."""
client = await ws_client()
result = await client.cmd_result(

View file

@ -1,4 +1,5 @@
"""The tests for the apprise notification platform."""
from pathlib import Path
from unittest.mock import MagicMock, patch
from homeassistant.core import HomeAssistant
@ -39,7 +40,7 @@ async def test_apprise_config_load_fail02(hass: HomeAssistant) -> None:
assert not hass.services.has_service(BASE_COMPONENT, "test")
async def test_apprise_config_load_okay(hass, tmp_path):
async def test_apprise_config_load_okay(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test apprise configuration failures."""
# Test cases where our URL is invalid
@ -111,7 +112,9 @@ async def test_apprise_notification(hass: HomeAssistant) -> None:
)
async def test_apprise_notification_with_target(hass, tmp_path):
async def test_apprise_notification_with_target(
hass: HomeAssistant, tmp_path: Path
) -> None:
"""Test apprise notification with a target."""
# Test cases where our URL is invalid

View file

@ -117,7 +117,7 @@ async def test_async_step_user_takes_precedence_over_discovery(
assert not hass.config_entries.flow.async_progress(DOMAIN)
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."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
@ -127,7 +127,7 @@ async def test_async_step_user_no_devices_found(hass: HomeAssistant):
assert result["reason"] == "no_devices_found"
async def test_async_step_user_only_other_devices_found(hass: HomeAssistant):
async def test_async_step_user_only_other_devices_found(hass: HomeAssistant) -> None:
"""Test setup from service info cache with only other devices found."""
with patch(
"homeassistant.components.aranet.config_flow.async_discovered_service_info",
@ -141,7 +141,7 @@ async def test_async_step_user_only_other_devices_found(hass: HomeAssistant):
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."""
with patch(
"homeassistant.components.aranet.config_flow.async_discovered_service_info",
@ -164,7 +164,7 @@ async def test_async_step_user_with_found_devices(hass: HomeAssistant):
assert result2["result"].unique_id == "aa:bb:cc:dd:ee:ff"
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."""
with patch(
"homeassistant.components.aranet.config_flow.async_discovered_service_info",
@ -192,7 +192,9 @@ async def test_async_step_user_device_added_between_steps(hass: HomeAssistant):
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."""
entry = MockConfigEntry(
domain=DOMAIN,
@ -212,7 +214,7 @@ async def test_async_step_user_with_found_devices_already_setup(hass: HomeAssist
assert result["reason"] == "no_devices_found"
async def test_async_step_user_old_firmware(hass: HomeAssistant):
async def test_async_step_user_old_firmware(hass: HomeAssistant) -> None:
"""Test we can't set up a device with firmware too old to report measurements."""
with patch(
"homeassistant.components.aranet.config_flow.async_discovered_service_info",
@ -233,7 +235,7 @@ async def test_async_step_user_old_firmware(hass: HomeAssistant):
assert result2["reason"] == "outdated_version"
async def test_async_step_user_integrations_disabled(hass: HomeAssistant):
async def test_async_step_user_integrations_disabled(hass: HomeAssistant) -> None:
"""Test we can't set up a device the device's integration setting disabled."""
with patch(
"homeassistant.components.aranet.config_flow.async_discovered_service_info",

View file

@ -60,7 +60,7 @@ def dummy_client_fixture(hass):
yield client.return_value
async def test_ssdp(hass, dummy_client):
async def test_ssdp(hass: HomeAssistant, dummy_client) -> None:
"""Test a ssdp import flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
@ -92,7 +92,7 @@ async def test_ssdp_abort(hass: HomeAssistant) -> None:
assert result["reason"] == "already_configured"
async def test_ssdp_unable_to_connect(hass, dummy_client):
async def test_ssdp_unable_to_connect(hass: HomeAssistant, dummy_client) -> None:
"""Test a ssdp import flow."""
dummy_client.start.side_effect = AsyncMock(side_effect=ConnectionFailed)
@ -109,7 +109,7 @@ async def test_ssdp_unable_to_connect(hass, dummy_client):
assert result["reason"] == "cannot_connect"
async def test_ssdp_invalid_id(hass, dummy_client):
async def test_ssdp_invalid_id(hass: HomeAssistant, dummy_client) -> None:
"""Test a ssdp with invalid UDN."""
discover = replace(
MOCK_DISCOVER, upnp=MOCK_DISCOVER.upnp | {ssdp.ATTR_UPNP_UDN: "invalid"}

View file

@ -4,6 +4,8 @@ import pytest
from homeassistant.components.arcam_fmj.const import DOMAIN
import homeassistant.components.automation as automation
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.setup import async_setup_component
from tests.common import (
@ -20,7 +22,11 @@ def calls(hass):
return async_mock_service(hass, "test", "automation")
async def test_get_triggers(hass, device_registry, entity_registry):
async def test_get_triggers(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected triggers from a arcam_fmj."""
config_entry = MockConfigEntry(domain=DOMAIN, data={})
config_entry.add_to_hass(hass)
@ -55,7 +61,9 @@ async def test_get_triggers(hass, device_registry, entity_registry):
assert trigger in expected_triggers or trigger["domain"] == "media_player"
async def test_if_fires_on_turn_on_request(hass, calls, player_setup, state):
async def test_if_fires_on_turn_on_request(
hass: HomeAssistant, calls, player_setup, state
) -> None:
"""Test for turn_on and turn_off triggers firing."""
state.get_power.return_value = None

View file

@ -19,6 +19,7 @@ from homeassistant.const import (
ATTR_MODEL,
ATTR_NAME,
)
from homeassistant.core import HomeAssistant
from .conftest import MOCK_HOST, MOCK_UUID
@ -34,7 +35,7 @@ async def update(player, force_refresh=False):
return player.hass.states.get(player.entity_id)
async def test_properties(player, state):
async def test_properties(player, state) -> None:
"""Test standard properties."""
assert player.unique_id == f"{MOCK_UUID}-1"
assert player.device_info == {
@ -48,7 +49,7 @@ async def test_properties(player, state):
assert not player.should_poll
async def test_powered_off(hass, player, state):
async def test_powered_off(hass: HomeAssistant, player, state) -> None:
"""Test properties in powered off state."""
state.get_source.return_value = None
state.get_power.return_value = None
@ -58,7 +59,7 @@ async def test_powered_off(hass, player, state):
assert data.state == "off"
async def test_powered_on(player, state):
async def test_powered_on(player, state) -> None:
"""Test properties in powered on state."""
state.get_source.return_value = SourceCodes.PVR
state.get_power.return_value = True
@ -68,13 +69,13 @@ async def test_powered_on(player, state):
assert data.state == "on"
async def test_supported_features(player, state):
async def test_supported_features(player, state) -> None:
"""Test supported features."""
data = await update(player)
assert data.attributes["supported_features"] == 200588
async def test_turn_on(player, state):
async def test_turn_on(player, state) -> None:
"""Test turn on service."""
state.get_power.return_value = None
await player.async_turn_on()
@ -85,27 +86,27 @@ async def test_turn_on(player, state):
state.set_power.assert_called_with(True)
async def test_turn_off(player, state):
async def test_turn_off(player, state) -> None:
"""Test command to turn off."""
await player.async_turn_off()
state.set_power.assert_called_with(False)
@pytest.mark.parametrize("mute", [True, False])
async def test_mute_volume(player, state, mute):
async def test_mute_volume(player, state, mute) -> None:
"""Test mute functionality."""
await player.async_mute_volume(mute)
state.set_mute.assert_called_with(mute)
player.async_write_ha_state.assert_called_with()
async def test_name(player):
async def test_name(player) -> None:
"""Test name."""
data = await update(player)
assert data.attributes["friendly_name"] == "Zone 1"
async def test_update(player, state):
async def test_update(player, state) -> None:
"""Test update."""
await update(player, force_refresh=True)
state.update.assert_called_with()
@ -115,7 +116,9 @@ async def test_update(player, state):
"source, value",
[("PVR", SourceCodes.PVR), ("BD", SourceCodes.BD), ("INVALID", None)],
)
async def test_select_source(hass, player_setup, state, source, value):
async def test_select_source(
hass: HomeAssistant, player_setup, state, source, value
) -> None:
"""Test selection of source."""
await hass.services.async_call(
"media_player",
@ -130,7 +133,7 @@ async def test_select_source(hass, player_setup, state, source, value):
state.set_source.assert_not_called()
async def test_source_list(player, state):
async def test_source_list(player, state) -> None:
"""Test source list."""
state.get_source_list.return_value = [SourceCodes.BD]
data = await update(player)
@ -144,20 +147,20 @@ async def test_source_list(player, state):
"DOLBY_PL",
],
)
async def test_select_sound_mode(player, state, mode):
async def test_select_sound_mode(player, state, mode) -> None:
"""Test selection sound mode."""
await player.async_select_sound_mode(mode)
state.set_decode_mode.assert_called_with(mode)
async def test_volume_up(player, state):
async def test_volume_up(player, state) -> None:
"""Test mute functionality."""
await player.async_volume_up()
state.inc_volume.assert_called_with()
player.async_write_ha_state.assert_called_with()
async def test_volume_down(player, state):
async def test_volume_down(player, state) -> None:
"""Test mute functionality."""
await player.async_volume_down()
state.dec_volume.assert_called_with()
@ -172,7 +175,7 @@ async def test_volume_down(player, state):
(None, None),
],
)
async def test_sound_mode(player, state, mode, mode_enum):
async def test_sound_mode(player, state, mode, mode_enum) -> None:
"""Test selection sound mode."""
state.get_decode_mode.return_value = mode_enum
data = await update(player)
@ -187,14 +190,14 @@ async def test_sound_mode(player, state, mode, mode_enum):
(None, None),
],
)
async def test_sound_mode_list(player, state, modes, modes_enum):
async def test_sound_mode_list(player, state, modes, modes_enum) -> None:
"""Test sound mode list."""
state.get_decode_modes.return_value = modes_enum
data = await update(player)
assert data.attributes.get(ATTR_SOUND_MODE_LIST) == modes
async def test_is_volume_muted(player, state):
async def test_is_volume_muted(player, state) -> None:
"""Test muted."""
state.get_mute.return_value = True
assert player.is_volume_muted is True # pylint: disable=singleton-comparison
@ -204,7 +207,7 @@ async def test_is_volume_muted(player, state):
assert player.is_volume_muted is None
async def test_volume_level(player, state):
async def test_volume_level(player, state) -> None:
"""Test volume."""
state.get_volume.return_value = 0
assert isclose(player.volume_level, 0.0)
@ -217,7 +220,7 @@ async def test_volume_level(player, state):
@pytest.mark.parametrize("volume, call", [(0.0, 0), (0.5, 50), (1.0, 99)])
async def test_set_volume_level(player, state, volume, call):
async def test_set_volume_level(player, state, volume, call) -> None:
"""Test setting volume."""
await player.async_set_volume_level(volume)
state.set_volume.assert_called_with(call)
@ -232,7 +235,7 @@ async def test_set_volume_level(player, state, volume, call):
(None, None),
],
)
async def test_media_content_type(player, state, source, media_content_type):
async def test_media_content_type(player, state, source, media_content_type) -> None:
"""Test content type deduction."""
state.get_source.return_value = source
assert player.media_content_type == media_content_type
@ -248,7 +251,7 @@ async def test_media_content_type(player, state, source, media_content_type):
(SourceCodes.PVR, "dab", "rds", None),
],
)
async def test_media_channel(player, state, source, dab, rds, channel):
async def test_media_channel(player, state, source, dab, rds, channel) -> None:
"""Test media channel."""
state.get_dab_station.return_value = dab
state.get_rds_information.return_value = rds
@ -264,7 +267,7 @@ async def test_media_channel(player, state, source, dab, rds, channel):
(SourceCodes.DAB, None, None),
],
)
async def test_media_artist(player, state, source, dls, artist):
async def test_media_artist(player, state, source, dls, artist) -> None:
"""Test media artist."""
state.get_dls_pdt.return_value = dls
state.get_source.return_value = source
@ -279,7 +282,7 @@ async def test_media_artist(player, state, source, dls, artist):
(None, None, None),
],
)
async def test_media_title(player, state, source, channel, title):
async def test_media_title(player, state, source, channel, title) -> None:
"""Test media title."""
from homeassistant.components.arcam_fmj.media_player import ArcamFmj
@ -295,7 +298,7 @@ async def test_media_title(player, state, source, channel, title):
assert data.attributes["media_title"] == title
async def test_added_to_hass(player, state):
async def test_added_to_hass(player, state) -> None:
"""Test addition to hass."""
from homeassistant.components.arcam_fmj.const import (
SIGNAL_CLIENT_DATA,

View file

@ -77,7 +77,7 @@ def mock_controller_connect(mock_unique_id):
"unique_id",
[{}, {"label_mac": MAC_ADDR}],
)
async def test_user(hass, mock_unique_id, unique_id):
async def test_user(hass: HomeAssistant, mock_unique_id, unique_id) -> None:
"""Test user config."""
mock_unique_id.update(unique_id)
flow_result = await hass.config_entries.flow.async_init(
@ -108,7 +108,7 @@ async def test_user(hass, mock_unique_id, unique_id):
({CONF_SSH_KEY: SSH_KEY}, "pwd_and_ssh"),
],
)
async def test_error_wrong_password_ssh(hass, config, error):
async def test_error_wrong_password_ssh(hass: HomeAssistant, config, error) -> None:
"""Test we abort for wrong password and ssh file combination."""
config_data = CONFIG_DATA.copy()
config_data.update(config)
@ -175,7 +175,7 @@ async def test_abort_if_not_unique_id_setup(hass: HomeAssistant) -> None:
@pytest.mark.usefixtures("connect")
async def test_update_uniqueid_exist(hass, mock_unique_id):
async def test_update_uniqueid_exist(hass: HomeAssistant, mock_unique_id) -> None:
"""Test we update entry if uniqueid is already configured."""
mock_unique_id.update({"label_mac": MAC_ADDR})
existing_entry = MockConfigEntry(
@ -228,7 +228,7 @@ async def test_abort_invalid_unique_id(hass: HomeAssistant) -> None:
(None, "cannot_connect"),
],
)
async def test_on_connect_failed(hass, side_effect, error):
async def test_on_connect_failed(hass: HomeAssistant, side_effect, error) -> None:
"""Test when we have errors connecting the router."""
flow_result = await hass.config_entries.flow.async_init(
DOMAIN,

View file

@ -25,6 +25,7 @@ from homeassistant.const import (
STATE_NOT_HOME,
STATE_UNAVAILABLE,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.util import slugify
from homeassistant.util.dt import utcnow
@ -217,12 +218,12 @@ def _setup_entry(hass, config, sensors, unique_id=None):
[None, MAC_ADDR],
)
async def test_sensors(
hass,
hass: HomeAssistant,
connect,
mock_devices,
create_device_registry_devices,
entry_unique_id,
):
) -> None:
"""Test creating AsusWRT default sensors and tracker."""
config_entry, sensor_prefix = _setup_entry(
hass, CONFIG_DATA, SENSORS_DEFAULT, entry_unique_id
@ -291,9 +292,9 @@ async def test_sensors(
async def test_loadavg_sensors(
hass,
hass: HomeAssistant,
connect,
):
) -> None:
"""Test creating an AsusWRT load average sensors."""
config_entry, sensor_prefix = _setup_entry(hass, CONFIG_DATA, SENSORS_LOADAVG)
config_entry.add_to_hass(hass)
@ -311,10 +312,10 @@ async def test_loadavg_sensors(
async def test_temperature_sensors_fail(
hass,
hass: HomeAssistant,
connect,
mock_available_temps,
):
) -> None:
"""Test fail creating AsusWRT temperature sensors."""
config_entry, sensor_prefix = _setup_entry(hass, CONFIG_DATA, SENSORS_TEMP)
config_entry.add_to_hass(hass)
@ -333,9 +334,9 @@ async def test_temperature_sensors_fail(
async def test_temperature_sensors(
hass,
hass: HomeAssistant,
connect,
):
) -> None:
"""Test creating a AsusWRT temperature sensors."""
config_entry, sensor_prefix = _setup_entry(hass, CONFIG_DATA, SENSORS_TEMP)
config_entry.add_to_hass(hass)
@ -356,7 +357,7 @@ async def test_temperature_sensors(
"side_effect",
[OSError, None],
)
async def test_connect_fail(hass, side_effect):
async def test_connect_fail(hass: HomeAssistant, side_effect) -> None:
"""Test AsusWRT connect fail."""
# init config entry
@ -379,7 +380,7 @@ async def test_connect_fail(hass, side_effect):
assert config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_sensors_polling_fails(hass, connect_sens_fail):
async def test_sensors_polling_fails(hass: HomeAssistant, connect_sens_fail) -> None:
"""Test AsusWRT sensors are unavailable when polling fails."""
config_entry, sensor_prefix = _setup_entry(hass, CONFIG_DATA, SENSORS_ALL)
config_entry.add_to_hass(hass)
@ -398,7 +399,7 @@ async def test_sensors_polling_fails(hass, connect_sens_fail):
assert hass.states.get(f"{sensor_prefix}_devices_connected").state == "0"
async def test_options_reload(hass, connect):
async def test_options_reload(hass: HomeAssistant, connect) -> None:
"""Test AsusWRT integration is reload changing an options that require this."""
config_entry = MockConfigEntry(domain=DOMAIN, data=CONFIG_DATA, unique_id=MAC_ADDR)
config_entry.add_to_hass(hass)

View file

@ -10,7 +10,9 @@ from . import UID, USER_INPUT, init_integration, mock_connection
from tests.test_util.aiohttp import AiohttpClientMocker
async def test_show_form(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker):
async def test_show_form(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test that the form is served with no input."""
mock_connection(aioclient_mock)
result = await hass.config_entries.flow.async_init(
@ -44,7 +46,7 @@ async def test_adding_second_device(
async def test_connection_error(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
):
) -> None:
"""Test we show user form on Atag connection error."""
mock_connection(aioclient_mock, conn_error=True)
result = await hass.config_entries.flow.async_init(
@ -58,7 +60,9 @@ async def test_connection_error(
assert result["errors"] == {"base": "cannot_connect"}
async def test_unauthorized(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker):
async def test_unauthorized(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test we show correct form when Unauthorized error is raised."""
mock_connection(aioclient_mock, authorized=False)
result = await hass.config_entries.flow.async_init(

View file

@ -5,6 +5,7 @@ from unittest.mock import patch
import pytest
from homeassistant.components.auth import indieauth
from homeassistant.core import HomeAssistant
from tests.test_util.aiohttp import AiohttpClientMocker
@ -129,7 +130,7 @@ async def test_verify_redirect_uri() -> None:
)
async def test_find_link_tag(hass, mock_session):
async def test_find_link_tag(hass: HomeAssistant, mock_session) -> None:
"""Test finding link tag."""
mock_session.get(
"http://127.0.0.1:8000",
@ -150,7 +151,7 @@ async def test_find_link_tag(hass, mock_session):
assert redirect_uris == ["hass://oauth2_redirect", "http://127.0.0.1:8000/beer"]
async def test_find_link_tag_max_size(hass, mock_session):
async def test_find_link_tag_max_size(hass: HomeAssistant, mock_session) -> None:
"""Test finding link tag."""
text = "".join(
[
@ -169,7 +170,7 @@ async def test_find_link_tag_max_size(hass, mock_session):
"client_id",
["https://home-assistant.io/android", "https://home-assistant.io/iOS"],
)
async def test_verify_redirect_uri_android_ios(client_id):
async def test_verify_redirect_uri_android_ios(client_id) -> None:
"""Test that we verify redirect uri correctly for Android/iOS."""
with patch.object(indieauth, "fetch_redirect_uris", return_value=[]):
assert await indieauth.verify_redirect_uri(

View file

@ -15,7 +15,7 @@ from homeassistant.util.dt import utcnow
from . import async_setup_auth
from tests.common import CLIENT_ID, CLIENT_REDIRECT_URI, MockUser
from tests.typing import ClientSessionGenerator
from tests.typing import ClientSessionGenerator, WebSocketGenerator
@pytest.fixture
@ -166,7 +166,7 @@ async def test_auth_code_checks_local_only_user(
assert error["error"] == "access_denied"
def test_auth_code_store_expiration(mock_credential):
def test_auth_code_store_expiration(mock_credential) -> None:
"""Test that the auth code store will not return expired tokens."""
store, retrieve = auth._create_auth_code_store()
client_id = "bla"
@ -190,7 +190,7 @@ def test_auth_code_store_expiration(mock_credential):
assert retrieve(client_id, code) == mock_credential
def test_auth_code_store_requires_credentials(mock_credential):
def test_auth_code_store_requires_credentials(mock_credential) -> None:
"""Test we require credentials."""
store, _retrieve = auth._create_auth_code_store()
@ -200,7 +200,9 @@ def test_auth_code_store_requires_credentials(mock_credential):
store(None, mock_credential)
async def test_ws_current_user(hass, hass_ws_client, hass_access_token):
async def test_ws_current_user(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, hass_access_token: str
) -> None:
"""Test the current user command with Home Assistant creds."""
assert await async_setup_component(hass, "auth", {})
@ -354,8 +356,11 @@ async def test_refresh_token_checks_local_only_user(
async def test_refresh_token_provider_rejected(
hass, aiohttp_client, hass_admin_user, hass_admin_credential
):
hass: HomeAssistant,
aiohttp_client: ClientSessionGenerator,
hass_admin_user: MockUser,
hass_admin_credential: Credentials,
) -> None:
"""Test that we verify client ID."""
client = await async_setup_auth(hass, aiohttp_client)
refresh_token = await async_setup_user_refresh_token(hass)
@ -383,7 +388,9 @@ async def test_refresh_token_provider_rejected(
@pytest.mark.parametrize(
"url,base_data", [("/auth/token", {"action": "revoke"}), ("/auth/revoke", {})]
)
async def test_revoking_refresh_token(url, base_data, hass, aiohttp_client):
async def test_revoking_refresh_token(
url, base_data, hass: HomeAssistant, aiohttp_client: ClientSessionGenerator
) -> None:
"""Test that we can revoke refresh tokens."""
client = await async_setup_auth(hass, aiohttp_client)
refresh_token = await async_setup_user_refresh_token(hass)
@ -424,7 +431,9 @@ async def test_revoking_refresh_token(url, base_data, hass, aiohttp_client):
assert resp.status == HTTPStatus.BAD_REQUEST
async def test_ws_long_lived_access_token(hass, hass_ws_client, hass_access_token):
async def test_ws_long_lived_access_token(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, hass_access_token: str
) -> None:
"""Test generate long-lived access token."""
assert await async_setup_component(hass, "auth", {"http": {}})
@ -452,7 +461,9 @@ async def test_ws_long_lived_access_token(hass, hass_ws_client, hass_access_toke
assert refresh_token.client_icon is None
async def test_ws_refresh_tokens(hass, hass_ws_client, hass_access_token):
async def test_ws_refresh_tokens(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, hass_access_token: str
) -> None:
"""Test fetching refresh token metadata."""
assert await async_setup_component(hass, "auth", {"http": {}})
@ -478,8 +489,12 @@ async def test_ws_refresh_tokens(hass, hass_ws_client, hass_access_token):
async def test_ws_delete_refresh_token(
hass, hass_admin_user, hass_admin_credential, hass_ws_client, hass_access_token
):
hass: HomeAssistant,
hass_admin_user: MockUser,
hass_admin_credential: Credentials,
hass_ws_client: WebSocketGenerator,
hass_access_token: str,
) -> None:
"""Test deleting a refresh token."""
assert await async_setup_component(hass, "auth", {"http": {}})
@ -504,7 +519,9 @@ async def test_ws_delete_refresh_token(
assert refresh_token is None
async def test_ws_sign_path(hass, hass_ws_client, hass_access_token):
async def test_ws_sign_path(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, hass_access_token: str
) -> None:
"""Test signing a path."""
assert await async_setup_component(hass, "auth", {"http": {}})
ws_client = await hass_ws_client(hass, hass_access_token)

View file

@ -50,6 +50,7 @@ from homeassistant.util import yaml
import homeassistant.util.dt as dt_util
from tests.common import (
MockUser,
assert_setup_component,
async_capture_events,
async_fire_time_changed,
@ -67,7 +68,9 @@ def calls(hass):
return async_mock_service(hass, "test", "automation")
async def test_service_data_not_a_dict(hass, caplog, calls):
async def test_service_data_not_a_dict(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, calls
) -> None:
"""Test service data not dict."""
with assert_setup_component(1, automation.DOMAIN):
assert await async_setup_component(
@ -87,7 +90,7 @@ async def test_service_data_not_a_dict(hass, caplog, calls):
assert "Result is not a Dictionary" in caplog.text
async def test_service_data_single_template(hass, calls):
async def test_service_data_single_template(hass: HomeAssistant, calls) -> None:
"""Test service data not dict."""
with assert_setup_component(1, automation.DOMAIN):
assert await async_setup_component(
@ -110,7 +113,7 @@ async def test_service_data_single_template(hass, calls):
assert calls[0].data["foo"] == "bar"
async def test_service_specify_data(hass, calls):
async def test_service_specify_data(hass: HomeAssistant, calls) -> None:
"""Test service data."""
assert await async_setup_component(
hass,
@ -144,7 +147,7 @@ async def test_service_specify_data(hass, calls):
assert state.attributes.get("last_triggered") == time
async def test_service_specify_entity_id(hass, calls):
async def test_service_specify_entity_id(hass: HomeAssistant, calls) -> None:
"""Test service data."""
assert await async_setup_component(
hass,
@ -163,7 +166,7 @@ async def test_service_specify_entity_id(hass, calls):
assert ["hello.world"] == calls[0].data.get(ATTR_ENTITY_ID)
async def test_service_specify_entity_id_list(hass, calls):
async def test_service_specify_entity_id_list(hass: HomeAssistant, calls) -> None:
"""Test service data."""
assert await async_setup_component(
hass,
@ -185,7 +188,7 @@ async def test_service_specify_entity_id_list(hass, calls):
assert ["hello.world", "hello.world2"] == calls[0].data.get(ATTR_ENTITY_ID)
async def test_two_triggers(hass, calls):
async def test_two_triggers(hass: HomeAssistant, calls) -> None:
"""Test triggers."""
assert await async_setup_component(
hass,
@ -209,7 +212,9 @@ async def test_two_triggers(hass, calls):
assert len(calls) == 2
async def test_trigger_service_ignoring_condition(hass, caplog, calls):
async def test_trigger_service_ignoring_condition(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, calls
) -> None:
"""Test triggers."""
assert await async_setup_component(
hass,
@ -260,7 +265,7 @@ async def test_trigger_service_ignoring_condition(hass, caplog, calls):
assert len(calls) == 2
async def test_two_conditions_with_and(hass, calls):
async def test_two_conditions_with_and(hass: HomeAssistant, calls) -> None:
"""Test two and conditions."""
entity_id = "test.entity"
assert await async_setup_component(
@ -298,7 +303,7 @@ async def test_two_conditions_with_and(hass, calls):
assert len(calls) == 1
async def test_shorthand_conditions_template(hass, calls):
async def test_shorthand_conditions_template(hass: HomeAssistant, calls) -> None:
"""Test shorthand nation form in conditions."""
assert await async_setup_component(
hass,
@ -323,7 +328,7 @@ async def test_shorthand_conditions_template(hass, calls):
assert len(calls) == 1
async def test_automation_list_setting(hass, calls):
async def test_automation_list_setting(hass: HomeAssistant, calls) -> None:
"""Event is not a valid condition."""
assert await async_setup_component(
hass,
@ -351,7 +356,7 @@ async def test_automation_list_setting(hass, calls):
assert len(calls) == 2
async def test_automation_calling_two_actions(hass, calls):
async def test_automation_calling_two_actions(hass: HomeAssistant, calls) -> None:
"""Test if we can call two actions from automation async definition."""
assert await async_setup_component(
hass,
@ -375,7 +380,7 @@ async def test_automation_calling_two_actions(hass, calls):
assert calls[1].data["position"] == 1
async def test_shared_context(hass, calls):
async def test_shared_context(hass: HomeAssistant, calls) -> None:
"""Test that the shared context is passed down the chain."""
assert await async_setup_component(
hass,
@ -442,7 +447,7 @@ async def test_shared_context(hass, calls):
assert calls[0].context is second_trigger_context
async def test_services(hass, calls):
async def test_services(hass: HomeAssistant, calls) -> None:
"""Test the automation services for turning entities on/off."""
entity_id = "automation.hello"
@ -524,7 +529,9 @@ async def test_services(hass, calls):
assert automation.is_on(hass, entity_id)
async def test_reload_config_service(hass, calls, hass_admin_user, hass_read_only_user):
async def test_reload_config_service(
hass: HomeAssistant, calls, hass_admin_user: MockUser, hass_read_only_user: MockUser
) -> None:
"""Test the reload config service."""
assert await async_setup_component(
hass,
@ -602,7 +609,7 @@ async def test_reload_config_service(hass, calls, hass_admin_user, hass_read_onl
assert calls[1].data.get("event") == "test_event2"
async def test_reload_config_when_invalid_config(hass, calls):
async def test_reload_config_when_invalid_config(hass: HomeAssistant, calls) -> None:
"""Test the reload config service handling invalid config."""
with assert_setup_component(1, automation.DOMAIN):
assert await async_setup_component(
@ -641,7 +648,7 @@ async def test_reload_config_when_invalid_config(hass, calls):
assert len(calls) == 1
async def test_reload_config_handles_load_fails(hass, calls):
async def test_reload_config_handles_load_fails(hass: HomeAssistant, calls) -> None:
"""Test the reload config service."""
assert await async_setup_component(
hass,
@ -679,7 +686,7 @@ async def test_reload_config_handles_load_fails(hass, calls):
@pytest.mark.parametrize("service", ["turn_off_stop", "turn_off_no_stop", "reload"])
async def test_automation_stops(hass, calls, service):
async def test_automation_stops(hass: HomeAssistant, calls, service) -> None:
"""Test that turning off / reloading stops any running actions as appropriate."""
entity_id = "automation.hello"
test_entity = "test.entity"
@ -741,7 +748,9 @@ async def test_automation_stops(hass, calls, service):
@pytest.mark.parametrize("extra_config", ({}, {"id": "sun"}))
async def test_reload_unchanged_does_not_stop(hass, calls, extra_config):
async def test_reload_unchanged_does_not_stop(
hass: HomeAssistant, calls, extra_config
) -> None:
"""Test that reloading stops any running actions as appropriate."""
test_entity = "test.entity"
@ -785,7 +794,9 @@ async def test_reload_unchanged_does_not_stop(hass, calls, extra_config):
assert len(calls) == 1
async def test_reload_moved_automation_without_alias(hass, calls):
async def test_reload_moved_automation_without_alias(
hass: HomeAssistant, calls
) -> None:
"""Test that changing the order of automations without alias triggers reload."""
with patch(
"homeassistant.components.automation.AutomationEntity", wraps=AutomationEntity
@ -838,7 +849,9 @@ async def test_reload_moved_automation_without_alias(hass, calls):
assert len(calls) == 2
async def test_reload_identical_automations_without_id(hass, calls):
async def test_reload_identical_automations_without_id(
hass: HomeAssistant, calls
) -> None:
"""Test reloading of identical automations without id."""
with patch(
"homeassistant.components.automation.AutomationEntity", wraps=AutomationEntity
@ -1011,7 +1024,9 @@ async def test_reload_identical_automations_without_id(hass, calls):
},
),
)
async def test_reload_unchanged_automation(hass, calls, automation_config):
async def test_reload_unchanged_automation(
hass: HomeAssistant, calls, automation_config
) -> None:
"""Test an unmodified automation is not reloaded."""
with patch(
"homeassistant.components.automation.AutomationEntity", wraps=AutomationEntity
@ -1044,7 +1059,9 @@ async def test_reload_unchanged_automation(hass, calls, automation_config):
@pytest.mark.parametrize("extra_config", ({}, {"id": "sun"}))
async def test_reload_automation_when_blueprint_changes(hass, calls, extra_config):
async def test_reload_automation_when_blueprint_changes(
hass: HomeAssistant, calls, extra_config
) -> None:
"""Test an automation is updated at reload if the blueprint has changed."""
with patch(
"homeassistant.components.automation.AutomationEntity", wraps=AutomationEntity
@ -1382,8 +1399,12 @@ async def test_automation_not_trigger_on_bootstrap(hass: HomeAssistant) -> None:
),
)
async def test_automation_bad_config_validation(
hass: HomeAssistant, caplog, broken_config, problem, details
):
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
broken_config,
problem,
details,
) -> None:
"""Test bad automation configuration which can be detected during validation."""
assert await async_setup_component(
hass,
@ -1936,7 +1957,7 @@ async def test_automation_this_var_always(
assert "Error rendering variables" not in caplog.text
async def test_blueprint_automation(hass, calls):
async def test_blueprint_automation(hass: HomeAssistant, calls) -> None:
"""Test blueprint automation."""
assert await async_setup_component(
hass,
@ -1993,8 +2014,12 @@ async def test_blueprint_automation(hass, calls):
),
)
async def test_blueprint_automation_bad_config(
hass, caplog, blueprint_inputs, problem, details
):
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
blueprint_inputs,
problem,
details,
) -> None:
"""Test blueprint automation with bad inputs."""
assert await async_setup_component(
hass,
@ -2043,7 +2068,7 @@ async def test_blueprint_automation_fails_substitution(
) in caplog.text
async def test_trigger_service(hass, calls):
async def test_trigger_service(hass: HomeAssistant, calls) -> None:
"""Test the automation trigger service."""
assert await async_setup_component(
hass,
@ -2073,7 +2098,7 @@ async def test_trigger_service(hass, calls):
assert calls[0].context.parent_id is context.id
async def test_trigger_condition_implicit_id(hass, calls):
async def test_trigger_condition_implicit_id(hass: HomeAssistant, calls) -> None:
"""Test triggers."""
assert await async_setup_component(
hass,
@ -2123,7 +2148,7 @@ async def test_trigger_condition_implicit_id(hass, calls):
assert calls[-1].data.get("param") == "one"
async def test_trigger_condition_explicit_id(hass, calls):
async def test_trigger_condition_explicit_id(hass: HomeAssistant, calls) -> None:
"""Test triggers."""
assert await async_setup_component(
hass,
@ -2191,8 +2216,8 @@ async def test_recursive_automation_starting_script(
automation_runs,
script_mode,
script_warning_msg,
caplog,
):
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test starting automations does not interfere with script deadlock prevention."""
# Fail if additional script modes are added to
@ -2295,7 +2320,9 @@ async def test_recursive_automation_starting_script(
@pytest.mark.parametrize("automation_mode", SCRIPT_MODE_CHOICES)
async def test_recursive_automation(hass: HomeAssistant, automation_mode, caplog):
async def test_recursive_automation(
hass: HomeAssistant, automation_mode, caplog: pytest.LogCaptureFixture
) -> None:
"""Test automation triggering itself.
- Illegal recursion detection should not be triggered

View file

@ -14,7 +14,7 @@ from homeassistant.components.automation import (
from homeassistant.components.recorder.db_schema import StateAttributes, States
from homeassistant.components.recorder.util import session_scope
from homeassistant.const import ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME
from homeassistant.core import State
from homeassistant.core import HomeAssistant, State
from homeassistant.setup import async_setup_component
from tests.common import async_mock_service
@ -27,7 +27,7 @@ def calls(hass):
return async_mock_service(hass, "test", "automation")
async def test_exclude_attributes(recorder_mock, hass, calls):
async def test_exclude_attributes(recorder_mock, hass: HomeAssistant, calls) -> None:
"""Test automation registered attributes to be excluded."""
assert await async_setup_component(
hass,

View file

@ -22,7 +22,7 @@ from .const import (
from tests.common import MockConfigEntry
async def test_show_form(hass: HomeAssistant):
async def test_show_form(hass: HomeAssistant) -> None:
"""Test that the form is served with no input."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
@ -32,7 +32,7 @@ async def test_show_form(hass: HomeAssistant):
assert result["step_id"] == SOURCE_USER
async def test_invalid_access_token(hass: HomeAssistant):
async def test_invalid_access_token(hass: HomeAssistant) -> None:
"""Test that errors are shown when the access token is invalid."""
with patch("python_awair.AwairClient.query", side_effect=AuthError()):
@ -53,7 +53,7 @@ async def test_invalid_access_token(hass: HomeAssistant):
assert result["errors"] == {CONF_ACCESS_TOKEN: "invalid_access_token"}
async def test_unexpected_api_error(hass: HomeAssistant):
async def test_unexpected_api_error(hass: HomeAssistant) -> None:
"""Test that we abort on generic errors."""
with patch("python_awair.AwairClient.query", side_effect=AwairError()):
@ -75,7 +75,7 @@ async def test_unexpected_api_error(hass: HomeAssistant):
assert result["reason"] == "unknown"
async def test_duplicate_error(hass: HomeAssistant, user, cloud_devices):
async def test_duplicate_error(hass: HomeAssistant, user, cloud_devices) -> None:
"""Test that errors are shown when adding a duplicate config."""
with patch(
@ -104,7 +104,7 @@ async def test_duplicate_error(hass: HomeAssistant, user, cloud_devices):
assert result["reason"] == "already_configured_account"
async def test_no_devices_error(hass: HomeAssistant, user, no_devices):
async def test_no_devices_error(hass: HomeAssistant, user, no_devices) -> None:
"""Test that errors are shown when the API returns no devices."""
with patch("python_awair.AwairClient.query", side_effect=[user, no_devices]):
@ -195,7 +195,7 @@ async def test_reauth_error(hass: HomeAssistant) -> None:
assert result["reason"] == "unknown"
async def test_create_cloud_entry(hass: HomeAssistant, user, cloud_devices):
async def test_create_cloud_entry(hass: HomeAssistant, user, cloud_devices) -> None:
"""Test overall flow when using cloud api."""
with patch(
@ -225,7 +225,7 @@ async def test_create_cloud_entry(hass: HomeAssistant, user, cloud_devices):
assert result["result"].unique_id == CLOUD_UNIQUE_ID
async def test_create_local_entry(hass: HomeAssistant, local_devices):
async def test_create_local_entry(hass: HomeAssistant, local_devices) -> None:
"""Test overall flow when using local API."""
with patch("python_awair.AwairClient.query", side_effect=[local_devices]), patch(
@ -258,7 +258,9 @@ async def test_create_local_entry(hass: HomeAssistant, local_devices):
assert result["result"].unique_id == LOCAL_UNIQUE_ID
async def test_create_local_entry_from_discovery(hass: HomeAssistant, local_devices):
async def test_create_local_entry_from_discovery(
hass: HomeAssistant, local_devices
) -> None:
"""Test local API when device discovered after instructions shown."""
menu_step = await hass.config_entries.flow.async_init(
@ -299,7 +301,7 @@ async def test_create_local_entry_from_discovery(hass: HomeAssistant, local_devi
assert result["result"].unique_id == LOCAL_UNIQUE_ID
async def test_create_local_entry_awair_error(hass: HomeAssistant):
async def test_create_local_entry_awair_error(hass: HomeAssistant) -> None:
"""Test overall flow when using local API and device is returns error."""
with patch(
@ -331,7 +333,7 @@ async def test_create_local_entry_awair_error(hass: HomeAssistant):
assert result["step_id"] == "local_pick"
async def test_create_zeroconf_entry(hass: HomeAssistant, local_devices):
async def test_create_zeroconf_entry(hass: HomeAssistant, local_devices) -> None:
"""Test overall flow when using discovery."""
with patch("python_awair.AwairClient.query", side_effect=[local_devices]), patch(
@ -353,7 +355,7 @@ async def test_create_zeroconf_entry(hass: HomeAssistant, local_devices):
assert result["result"].unique_id == LOCAL_UNIQUE_ID
async def test_unsuccessful_create_zeroconf_entry(hass: HomeAssistant):
async def test_unsuccessful_create_zeroconf_entry(hass: HomeAssistant) -> None:
"""Test overall flow when using discovery and device is unreachable."""
with patch(

View file

@ -8,7 +8,9 @@ from . import setup_awair
from .const import LOCAL_CONFIG, LOCAL_UNIQUE_ID
async def test_local_awair_sensors(hass: HomeAssistant, local_devices, local_data):
async def test_local_awair_sensors(
hass: HomeAssistant, local_devices, local_data
) -> None:
"""Test expected sensors on a local Awair."""
fixtures = [local_devices, local_data]
entry = await setup_awair(hass, fixtures, LOCAL_UNIQUE_ID, LOCAL_CONFIG)

View file

@ -62,7 +62,9 @@ def assert_expected_properties(
assert state.attributes.get(attr) == value
async def test_awair_gen1_sensors(hass: HomeAssistant, user, cloud_devices, gen1_data):
async def test_awair_gen1_sensors(
hass: HomeAssistant, user, cloud_devices, gen1_data
) -> None:
"""Test expected sensors on a 1st gen Awair."""
fixtures = [user, cloud_devices, gen1_data]
@ -154,7 +156,9 @@ async def test_awair_gen1_sensors(hass: HomeAssistant, user, cloud_devices, gen1
assert hass.states.get("sensor.living_room_illuminance") is None
async def test_awair_gen2_sensors(hass: HomeAssistant, user, cloud_devices, gen2_data):
async def test_awair_gen2_sensors(
hass: HomeAssistant, user, cloud_devices, gen2_data
) -> None:
"""Test expected sensors on a 2nd gen Awair."""
fixtures = [user, cloud_devices, gen2_data]
@ -187,7 +191,9 @@ async def test_awair_gen2_sensors(hass: HomeAssistant, user, cloud_devices, gen2
assert hass.states.get("sensor.living_room_pm10") is None
async def test_local_awair_sensors(hass: HomeAssistant, local_devices, local_data):
async def test_local_awair_sensors(
hass: HomeAssistant, local_devices, local_data
) -> None:
"""Test expected sensors on a local Awair."""
fixtures = [local_devices, local_data]
@ -204,7 +210,9 @@ async def test_local_awair_sensors(hass: HomeAssistant, local_devices, local_dat
)
async def test_awair_mint_sensors(hass: HomeAssistant, user, cloud_devices, mint_data):
async def test_awair_mint_sensors(
hass: HomeAssistant, user, cloud_devices, mint_data
) -> None:
"""Test expected sensors on an Awair mint."""
fixtures = [user, cloud_devices, mint_data]
@ -245,7 +253,9 @@ async def test_awair_mint_sensors(hass: HomeAssistant, user, cloud_devices, mint
assert hass.states.get("sensor.living_room_carbon_dioxide") is None
async def test_awair_glow_sensors(hass: HomeAssistant, user, cloud_devices, glow_data):
async def test_awair_glow_sensors(
hass: HomeAssistant, user, cloud_devices, glow_data
) -> None:
"""Test expected sensors on an Awair glow."""
fixtures = [user, cloud_devices, glow_data]
@ -265,7 +275,9 @@ async def test_awair_glow_sensors(hass: HomeAssistant, user, cloud_devices, glow
assert hass.states.get("sensor.living_room_pm2_5") is None
async def test_awair_omni_sensors(hass: HomeAssistant, user, cloud_devices, omni_data):
async def test_awair_omni_sensors(
hass: HomeAssistant, user, cloud_devices, omni_data
) -> None:
"""Test expected sensors on an Awair omni."""
fixtures = [user, cloud_devices, omni_data]
@ -300,7 +312,9 @@ async def test_awair_omni_sensors(hass: HomeAssistant, user, cloud_devices, omni
)
async def test_awair_offline(hass: HomeAssistant, user, cloud_devices, awair_offline):
async def test_awair_offline(
hass: HomeAssistant, user, cloud_devices, awair_offline
) -> None:
"""Test expected behavior when an Awair is offline."""
fixtures = [user, cloud_devices, awair_offline]
@ -320,7 +334,7 @@ async def test_awair_offline(hass: HomeAssistant, user, cloud_devices, awair_off
async def test_awair_unavailable(
hass: HomeAssistant, user, cloud_devices, gen1_data, awair_offline
):
) -> None:
"""Test expected behavior when an Awair becomes offline later."""
fixtures = [user, cloud_devices, gen1_data]