diff --git a/tests/auth/mfa_modules/test_insecure_example.py b/tests/auth/mfa_modules/test_insecure_example.py index a182de6d01f..d22bfaa0719 100644 --- a/tests/auth/mfa_modules/test_insecure_example.py +++ b/tests/auth/mfa_modules/test_insecure_example.py @@ -2,11 +2,12 @@ from homeassistant import auth, data_entry_flow from homeassistant.auth.mfa_modules import auth_mfa_module_from_config from homeassistant.auth.models import Credentials +from homeassistant.core import HomeAssistant from tests.common import MockUser -async def test_validate(hass): +async def test_validate(hass: HomeAssistant) -> None: """Test validating pin.""" auth_module = await auth_mfa_module_from_config( hass, @@ -26,7 +27,7 @@ async def test_validate(hass): assert result is False -async def test_setup_user(hass): +async def test_setup_user(hass: HomeAssistant) -> None: """Test setup user.""" auth_module = await auth_mfa_module_from_config( hass, {"type": "insecure_example", "data": []} @@ -39,7 +40,7 @@ async def test_setup_user(hass): assert result is True -async def test_depose_user(hass): +async def test_depose_user(hass: HomeAssistant) -> None: """Test despose user.""" auth_module = await auth_mfa_module_from_config( hass, @@ -54,7 +55,7 @@ async def test_depose_user(hass): assert len(auth_module._data) == 0 -async def test_is_user_setup(hass): +async def test_is_user_setup(hass: HomeAssistant) -> None: """Test is user setup.""" auth_module = await auth_mfa_module_from_config( hass, @@ -67,7 +68,7 @@ async def test_is_user_setup(hass): assert await auth_module.async_is_user_setup("invalid-user") is False -async def test_login(hass): +async def test_login(hass: HomeAssistant) -> None: """Test login flow with auth module.""" hass.auth = await auth.auth_manager_from_config( hass, @@ -134,7 +135,7 @@ async def test_login(hass): assert result["data"].id == "mock-id" -async def test_setup_flow(hass): +async def test_setup_flow(hass: HomeAssistant) -> None: """Test validating pin.""" auth_module = await auth_mfa_module_from_config( hass, diff --git a/tests/auth/mfa_modules/test_notify.py b/tests/auth/mfa_modules/test_notify.py index e69f11155a5..d5b7e0bbc62 100644 --- a/tests/auth/mfa_modules/test_notify.py +++ b/tests/auth/mfa_modules/test_notify.py @@ -6,6 +6,7 @@ from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, models as auth_models from homeassistant.auth.mfa_modules import auth_mfa_module_from_config from homeassistant.components.notify import NOTIFY_SERVICE_SCHEMA +from homeassistant.core import HomeAssistant from tests.common import MockUser, async_mock_service @@ -13,7 +14,7 @@ MOCK_CODE = "123456" MOCK_CODE_2 = "654321" -async def test_validating_mfa(hass): +async def test_validating_mfa(hass: HomeAssistant) -> None: """Test validating mfa code.""" notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"}) await notify_auth_module.async_setup_user("test-user", {"notify_service": "dummy"}) @@ -22,7 +23,7 @@ async def test_validating_mfa(hass): assert await notify_auth_module.async_validate("test-user", {"code": MOCK_CODE}) -async def test_validating_mfa_invalid_code(hass): +async def test_validating_mfa_invalid_code(hass: HomeAssistant) -> None: """Test validating an invalid mfa code.""" notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"}) await notify_auth_module.async_setup_user("test-user", {"notify_service": "dummy"}) @@ -34,7 +35,7 @@ async def test_validating_mfa_invalid_code(hass): ) -async def test_validating_mfa_invalid_user(hass): +async def test_validating_mfa_invalid_user(hass: HomeAssistant) -> None: """Test validating an mfa code with invalid user.""" notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"}) await notify_auth_module.async_setup_user("test-user", {"notify_service": "dummy"}) @@ -45,7 +46,7 @@ async def test_validating_mfa_invalid_user(hass): ) -async def test_validating_mfa_counter(hass): +async def test_validating_mfa_counter(hass: HomeAssistant) -> None: """Test counter will move only after generate code.""" notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"}) await notify_auth_module.async_setup_user( @@ -81,7 +82,7 @@ async def test_validating_mfa_counter(hass): assert after_generate_count == notify_setting.counter -async def test_setup_depose_user(hass): +async def test_setup_depose_user(hass: HomeAssistant) -> None: """Test set up and despose user.""" notify_auth_module = await auth_mfa_module_from_config(hass, {"type": "notify"}) await notify_auth_module.async_setup_user("test-user", {}) @@ -96,7 +97,7 @@ async def test_setup_depose_user(hass): assert len(notify_auth_module._user_settings) == 1 -async def test_login_flow_validates_mfa(hass): +async def test_login_flow_validates_mfa(hass: HomeAssistant) -> None: """Test login flow with mfa enabled.""" hass.auth = await auth_manager_from_config( hass, @@ -232,7 +233,7 @@ async def test_login_flow_validates_mfa(hass): assert result["data"].id == "mock-id" -async def test_setup_user_notify_service(hass): +async def test_setup_user_notify_service(hass: HomeAssistant) -> None: """Test allow select notify service during mfa setup.""" notify_calls = async_mock_service(hass, "notify", "test1", NOTIFY_SERVICE_SCHEMA) async_mock_service(hass, "notify", "test2", NOTIFY_SERVICE_SCHEMA) @@ -286,7 +287,7 @@ async def test_setup_user_notify_service(hass): assert step["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY -async def test_include_exclude_config(hass): +async def test_include_exclude_config(hass: HomeAssistant) -> None: """Test allow include exclude config.""" async_mock_service(hass, "notify", "include1", NOTIFY_SERVICE_SCHEMA) async_mock_service(hass, "notify", "include2", NOTIFY_SERVICE_SCHEMA) @@ -320,7 +321,7 @@ async def test_include_exclude_config(hass): assert services == ["include1"] -async def test_setup_user_no_notify_service(hass): +async def test_setup_user_no_notify_service(hass: HomeAssistant) -> None: """Test setup flow abort if there is no available notify service.""" async_mock_service(hass, "notify", "test1", NOTIFY_SERVICE_SCHEMA) notify_auth_module = await auth_mfa_module_from_config( @@ -336,7 +337,7 @@ async def test_setup_user_no_notify_service(hass): assert step["reason"] == "no_available_service" -async def test_not_raise_exception_when_service_not_exist(hass): +async def test_not_raise_exception_when_service_not_exist(hass: HomeAssistant) -> None: """Test login flow will not raise exception when notify service error.""" hass.auth = await auth_manager_from_config( hass, @@ -382,7 +383,7 @@ async def test_not_raise_exception_when_service_not_exist(hass): await hass.async_block_till_done() -async def test_race_condition_in_data_loading(hass): +async def test_race_condition_in_data_loading(hass: HomeAssistant) -> None: """Test race condition in the data loading.""" counter = 0 diff --git a/tests/auth/mfa_modules/test_totp.py b/tests/auth/mfa_modules/test_totp.py index 53374e2d015..e5b1a930dd7 100644 --- a/tests/auth/mfa_modules/test_totp.py +++ b/tests/auth/mfa_modules/test_totp.py @@ -5,13 +5,14 @@ from unittest.mock import patch from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, models as auth_models from homeassistant.auth.mfa_modules import auth_mfa_module_from_config +from homeassistant.core import HomeAssistant from tests.common import MockUser MOCK_CODE = "123456" -async def test_validating_mfa(hass): +async def test_validating_mfa(hass: HomeAssistant) -> None: """Test validating mfa code.""" totp_auth_module = await auth_mfa_module_from_config(hass, {"type": "totp"}) await totp_auth_module.async_setup_user("test-user", {}) @@ -20,7 +21,7 @@ async def test_validating_mfa(hass): assert await totp_auth_module.async_validate("test-user", {"code": MOCK_CODE}) -async def test_validating_mfa_invalid_code(hass): +async def test_validating_mfa_invalid_code(hass: HomeAssistant) -> None: """Test validating an invalid mfa code.""" totp_auth_module = await auth_mfa_module_from_config(hass, {"type": "totp"}) await totp_auth_module.async_setup_user("test-user", {}) @@ -32,7 +33,7 @@ async def test_validating_mfa_invalid_code(hass): ) -async def test_validating_mfa_invalid_user(hass): +async def test_validating_mfa_invalid_user(hass: HomeAssistant) -> None: """Test validating an mfa code with invalid user.""" totp_auth_module = await auth_mfa_module_from_config(hass, {"type": "totp"}) await totp_auth_module.async_setup_user("test-user", {}) @@ -43,7 +44,7 @@ async def test_validating_mfa_invalid_user(hass): ) -async def test_setup_depose_user(hass): +async def test_setup_depose_user(hass: HomeAssistant) -> None: """Test despose user.""" totp_auth_module = await auth_mfa_module_from_config(hass, {"type": "totp"}) result = await totp_auth_module.async_setup_user("test-user", {}) @@ -62,7 +63,7 @@ async def test_setup_depose_user(hass): assert len(totp_auth_module._users) == 1 -async def test_login_flow_validates_mfa(hass): +async def test_login_flow_validates_mfa(hass: HomeAssistant) -> None: """Test login flow with mfa enabled.""" hass.auth = await auth_manager_from_config( hass, @@ -130,7 +131,7 @@ async def test_login_flow_validates_mfa(hass): assert result["data"].id == "mock-id" -async def test_race_condition_in_data_loading(hass): +async def test_race_condition_in_data_loading(hass: HomeAssistant) -> None: """Test race condition in the data loading.""" counter = 0 diff --git a/tests/auth/providers/test_homeassistant.py b/tests/auth/providers/test_homeassistant.py index 42c188f5200..1fecdf583a3 100644 --- a/tests/auth/providers/test_homeassistant.py +++ b/tests/auth/providers/test_homeassistant.py @@ -11,6 +11,7 @@ from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth, ) +from homeassistant.core import HomeAssistant @pytest.fixture @@ -273,7 +274,7 @@ async def test_legacy_get_or_create_credentials(hass, legacy_data): assert credentials1 is not credentials3 -async def test_race_condition_in_data_loading(hass): +async def test_race_condition_in_data_loading(hass: HomeAssistant) -> None: """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/core/issues/21569 diff --git a/tests/auth/test_auth_store.py b/tests/auth/test_auth_store.py index e52a0dc88f5..8250d94f6de 100644 --- a/tests/auth/test_auth_store.py +++ b/tests/auth/test_auth_store.py @@ -3,6 +3,7 @@ import asyncio from unittest.mock import patch from homeassistant.auth import auth_store +from homeassistant.core import HomeAssistant async def test_loading_no_group_data_format(hass, hass_storage): @@ -232,7 +233,7 @@ async def test_system_groups_store_id_and_name(hass, hass_storage): ] -async def test_loading_race_condition(hass): +async def test_loading_race_condition(hass: HomeAssistant) -> None: """Test only one storage load called when concurrent loading occurred .""" store = auth_store.AuthStore(hass) with patch( diff --git a/tests/auth/test_init.py b/tests/auth/test_init.py index ceb497fddf5..0f602a0e547 100644 --- a/tests/auth/test_init.py +++ b/tests/auth/test_init.py @@ -15,7 +15,7 @@ from homeassistant.auth import ( models as auth_models, ) from homeassistant.auth.const import GROUP_ID_ADMIN, MFA_SESSION_EXPIRATION -from homeassistant.core import callback +from homeassistant.core import HomeAssistant, callback from homeassistant.util import dt as dt_util from tests.common import ( @@ -140,7 +140,7 @@ async def test_auth_manager_from_config_auth_modules(mock_hass): ] -async def test_create_new_user(hass): +async def test_create_new_user(hass: HomeAssistant) -> None: """Test creating new user.""" events = [] @@ -355,7 +355,7 @@ async def test_saving_loading(hass, hass_storage): pytest.fail(f"Unknown client_id: {r_token.client_id}") -async def test_cannot_retrieve_expired_access_token(hass): +async def test_cannot_retrieve_expired_access_token(hass: HomeAssistant) -> None: """Test that we cannot retrieve expired access tokens.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) @@ -377,7 +377,7 @@ async def test_cannot_retrieve_expired_access_token(hass): assert await manager.async_validate_access_token(access_token) is None -async def test_generating_system_user(hass): +async def test_generating_system_user(hass: HomeAssistant) -> None: """Test that we can add a system user.""" events = [] @@ -416,7 +416,7 @@ async def test_generating_system_user(hass): assert events[1].data["user_id"] == user.id -async def test_refresh_token_requires_client_for_user(hass): +async def test_refresh_token_requires_client_for_user(hass: HomeAssistant) -> None: """Test create refresh token for a user with client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) @@ -433,7 +433,9 @@ async def test_refresh_token_requires_client_for_user(hass): assert token.access_token_expiration == auth_const.ACCESS_TOKEN_EXPIRATION -async def test_refresh_token_not_requires_client_for_system_user(hass): +async def test_refresh_token_not_requires_client_for_system_user( + hass: HomeAssistant, +) -> None: """Test create refresh token for a system user w/o client_id.""" manager = await auth.auth_manager_from_config(hass, [], []) user = await manager.async_create_system_user("Hass.io") @@ -448,7 +450,9 @@ async def test_refresh_token_not_requires_client_for_system_user(hass): assert token.token_type == auth_models.TOKEN_TYPE_SYSTEM -async def test_refresh_token_with_specific_access_token_expiration(hass): +async def test_refresh_token_with_specific_access_token_expiration( + hass: HomeAssistant, +) -> None: """Test create a refresh token with specific access token expiration.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) @@ -461,7 +465,7 @@ async def test_refresh_token_with_specific_access_token_expiration(hass): assert token.access_token_expiration == timedelta(days=100) -async def test_refresh_token_type(hass): +async def test_refresh_token_type(hass: HomeAssistant) -> None: """Test create a refresh token with token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) @@ -479,7 +483,7 @@ async def test_refresh_token_type(hass): assert token.token_type == auth_models.TOKEN_TYPE_NORMAL -async def test_refresh_token_type_long_lived_access_token(hass): +async def test_refresh_token_type_long_lived_access_token(hass: HomeAssistant) -> None: """Test create a refresh token has long-lived access token type.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) @@ -963,7 +967,7 @@ async def test_enable_mfa_for_user(hass, hass_storage): await manager.async_disable_user_mfa(user, "insecure_example") -async def test_async_remove_user(hass): +async def test_async_remove_user(hass: HomeAssistant) -> None: """Test removing a user.""" events = async_capture_events(hass, "user_removed") manager = await auth.auth_manager_from_config( @@ -1100,7 +1104,7 @@ async def test_rename_does_not_change_refresh_token(mock_hass): assert token_before == token_after -async def test_event_user_updated_fires(hass): +async def test_event_user_updated_fires(hass: HomeAssistant) -> None: """Test the user updated event fires.""" manager = await auth.auth_manager_from_config(hass, [], []) user = MockUser().add_to_auth_manager(manager) diff --git a/tests/helpers/test_aiohttp_client.py b/tests/helpers/test_aiohttp_client.py index 5af3fd89703..23ef8878c21 100644 --- a/tests/helpers/test_aiohttp_client.py +++ b/tests/helpers/test_aiohttp_client.py @@ -17,7 +17,7 @@ from homeassistant.const import ( CONF_VERIFY_SSL, HTTP_BASIC_AUTHENTICATION, ) -from homeassistant.core import EVENT_HOMEASSISTANT_CLOSE +from homeassistant.core import EVENT_HOMEASSISTANT_CLOSE, HomeAssistant import homeassistant.helpers.aiohttp_client as client from homeassistant.util.color import RGBColor @@ -48,7 +48,7 @@ def camera_client_fixture(hass, hass_client): return hass.loop.run_until_complete(hass_client()) -async def test_get_clientsession_with_ssl(hass): +async def test_get_clientsession_with_ssl(hass: HomeAssistant) -> None: """Test init clientsession with ssl.""" client.async_get_clientsession(hass) @@ -56,7 +56,7 @@ async def test_get_clientsession_with_ssl(hass): assert isinstance(hass.data[client.DATA_CONNECTOR], aiohttp.TCPConnector) -async def test_get_clientsession_without_ssl(hass): +async def test_get_clientsession_without_ssl(hass: HomeAssistant) -> None: """Test init clientsession without ssl.""" client.async_get_clientsession(hass, verify_ssl=False) @@ -66,21 +66,23 @@ async def test_get_clientsession_without_ssl(hass): assert isinstance(hass.data[client.DATA_CONNECTOR_NOTVERIFY], aiohttp.TCPConnector) -async def test_create_clientsession_with_ssl_and_cookies(hass): +async def test_create_clientsession_with_ssl_and_cookies(hass: HomeAssistant) -> None: """Test create clientsession with ssl.""" session = client.async_create_clientsession(hass, cookies={"bla": True}) assert isinstance(session, aiohttp.ClientSession) assert isinstance(hass.data[client.DATA_CONNECTOR], aiohttp.TCPConnector) -async def test_create_clientsession_without_ssl_and_cookies(hass): +async def test_create_clientsession_without_ssl_and_cookies( + hass: HomeAssistant, +) -> None: """Test create clientsession without ssl.""" session = client.async_create_clientsession(hass, False, cookies={"bla": True}) assert isinstance(session, aiohttp.ClientSession) assert isinstance(hass.data[client.DATA_CONNECTOR_NOTVERIFY], aiohttp.TCPConnector) -async def test_get_clientsession_cleanup(hass): +async def test_get_clientsession_cleanup(hass: HomeAssistant) -> None: """Test init clientsession with ssl.""" client.async_get_clientsession(hass) @@ -94,7 +96,7 @@ async def test_get_clientsession_cleanup(hass): assert hass.data[client.DATA_CONNECTOR].closed -async def test_get_clientsession_cleanup_without_ssl(hass): +async def test_get_clientsession_cleanup_without_ssl(hass: HomeAssistant) -> None: """Test init clientsession with ssl.""" client.async_get_clientsession(hass, verify_ssl=False) @@ -110,7 +112,7 @@ async def test_get_clientsession_cleanup_without_ssl(hass): assert hass.data[client.DATA_CONNECTOR_NOTVERIFY].closed -async def test_get_clientsession_patched_close(hass): +async def test_get_clientsession_patched_close(hass: HomeAssistant) -> None: """Test closing clientsession does not work.""" with patch("aiohttp.ClientSession.close") as mock_close: session = client.async_get_clientsession(hass) @@ -226,7 +228,7 @@ async def test_sending_named_tuple(hass, aioclient_mock): aioclient_mock.mock_calls[0][2]["rgb"] == RGBColor(4, 3, 2) -async def test_client_session_immutable_headers(hass): +async def test_client_session_immutable_headers(hass: HomeAssistant) -> None: """Test we can't mutate headers.""" session = client.async_get_clientsession(hass) diff --git a/tests/helpers/test_check_config.py b/tests/helpers/test_check_config.py index 73f24002e91..91ef17d526d 100644 --- a/tests/helpers/test_check_config.py +++ b/tests/helpers/test_check_config.py @@ -3,6 +3,7 @@ import logging from unittest.mock import Mock, patch from homeassistant.config import YAML_CONFIG_FILE +from homeassistant.core import HomeAssistant from homeassistant.helpers.check_config import ( CheckConfigError, async_check_ha_config_file, @@ -38,7 +39,7 @@ def log_ha_config(conf): _LOGGER.debug("error[%s] = %s", cnt, err) -async def test_bad_core_config(hass): +async def test_bad_core_config(hass: HomeAssistant) -> None: """Test a bad core config setup.""" files = {YAML_CONFIG_FILE: BAD_CORE_CONFIG} with patch("os.path.isfile", return_value=True), patch_yaml_files(files): @@ -54,7 +55,7 @@ async def test_bad_core_config(hass): assert not res.errors -async def test_config_platform_valid(hass): +async def test_config_platform_valid(hass: HomeAssistant) -> None: """Test a valid platform setup.""" files = {YAML_CONFIG_FILE: BASE_CONFIG + "light:\n platform: demo"} with patch("os.path.isfile", return_value=True), patch_yaml_files(files): @@ -66,7 +67,7 @@ async def test_config_platform_valid(hass): assert not res.errors -async def test_component_platform_not_found(hass): +async def test_component_platform_not_found(hass: HomeAssistant) -> None: """Test errors if component or platform not found.""" # Make sure they don't exist files = {YAML_CONFIG_FILE: BASE_CONFIG + "beer:"} @@ -84,7 +85,7 @@ async def test_component_platform_not_found(hass): assert not res.errors -async def test_component_requirement_not_found(hass): +async def test_component_requirement_not_found(hass: HomeAssistant) -> None: """Test errors if component with a requirement not found not found.""" # Make sure they don't exist files = {YAML_CONFIG_FILE: BASE_CONFIG + "test_custom_component:"} @@ -110,7 +111,7 @@ async def test_component_requirement_not_found(hass): assert not res.errors -async def test_component_not_found_safe_mode(hass): +async def test_component_not_found_safe_mode(hass: HomeAssistant) -> None: """Test no errors if component not found in safe mode.""" # Make sure they don't exist files = {YAML_CONFIG_FILE: BASE_CONFIG + "beer:"} @@ -123,7 +124,7 @@ async def test_component_not_found_safe_mode(hass): assert not res.errors -async def test_component_platform_not_found_2(hass): +async def test_component_platform_not_found_2(hass: HomeAssistant) -> None: """Test errors if component or platform not found.""" # Make sure they don't exist files = {YAML_CONFIG_FILE: BASE_CONFIG + "light:\n platform: beer"} @@ -143,7 +144,7 @@ async def test_component_platform_not_found_2(hass): assert not res.errors -async def test_platform_not_found_safe_mode(hass): +async def test_platform_not_found_safe_mode(hass: HomeAssistant) -> None: """Test no errors if platform not found in safe_mode.""" # Make sure they don't exist files = {YAML_CONFIG_FILE: BASE_CONFIG + "light:\n platform: beer"} @@ -158,7 +159,7 @@ async def test_platform_not_found_safe_mode(hass): assert not res.errors -async def test_package_invalid(hass): +async def test_package_invalid(hass: HomeAssistant) -> None: """Test a valid platform setup.""" files = {YAML_CONFIG_FILE: BASE_CONFIG + ' packages:\n p1:\n group: ["a"]'} with patch("os.path.isfile", return_value=True), patch_yaml_files(files): @@ -174,7 +175,7 @@ async def test_package_invalid(hass): assert res.keys() == {"homeassistant"} -async def test_bootstrap_error(hass): +async def test_bootstrap_error(hass: HomeAssistant) -> None: """Test a valid platform setup.""" files = {YAML_CONFIG_FILE: BASE_CONFIG + "automation: !include no.yaml"} with patch("os.path.isfile", return_value=True), patch_yaml_files(files): @@ -188,7 +189,7 @@ async def test_bootstrap_error(hass): assert not res.errors -async def test_automation_config_platform(hass): +async def test_automation_config_platform(hass: HomeAssistant) -> None: """Test automation async config.""" files = { YAML_CONFIG_FILE: BASE_CONFIG @@ -224,7 +225,7 @@ action: assert "input_datetime" in res -async def test_config_platform_raise(hass): +async def test_config_platform_raise(hass: HomeAssistant) -> None: """Test bad config validation platform.""" mock_platform( hass, diff --git a/tests/helpers/test_collection.py b/tests/helpers/test_collection.py index be8cd2e907f..9e5526ff32c 100644 --- a/tests/helpers/test_collection.py +++ b/tests/helpers/test_collection.py @@ -6,6 +6,7 @@ import logging import pytest import voluptuous as vol +from homeassistant.core import HomeAssistant from homeassistant.helpers import ( collection, entity_component, @@ -188,7 +189,7 @@ async def test_yaml_collection_skipping_duplicate_ids() -> None: ) -async def test_storage_collection(hass): +async def test_storage_collection(hass: HomeAssistant) -> None: """Test storage collection.""" store = storage.Store(hass, 1, "test-data") await store.async_save( @@ -251,7 +252,7 @@ async def test_storage_collection(hass): } -async def test_attach_entity_component_collection(hass): +async def test_attach_entity_component_collection(hass: HomeAssistant) -> None: """Test attaching collection to entity component.""" ent_comp = entity_component.EntityComponent(_LOGGER, "test", hass) coll = MockObservableCollection(_LOGGER) @@ -290,7 +291,7 @@ async def test_attach_entity_component_collection(hass): assert hass.states.get("test.mock_1") is None -async def test_entity_component_collection_abort(hass): +async def test_entity_component_collection_abort(hass: HomeAssistant) -> None: """Test aborted entity adding is handled.""" ent_comp = entity_component.EntityComponent(_LOGGER, "test", hass) coll = MockObservableCollection(_LOGGER) @@ -356,7 +357,7 @@ async def test_entity_component_collection_abort(hass): assert len(async_remove_calls) == 0 -async def test_entity_component_collection_entity_removed(hass): +async def test_entity_component_collection_entity_removed(hass: HomeAssistant) -> None: """Test entity removal is handled.""" ent_comp = entity_component.EntityComponent(_LOGGER, "test", hass) coll = MockObservableCollection(_LOGGER) diff --git a/tests/helpers/test_condition.py b/tests/helpers/test_condition.py index fb355b7bf7a..80b40baae04 100644 --- a/tests/helpers/test_condition.py +++ b/tests/helpers/test_condition.py @@ -86,7 +86,7 @@ def assert_condition_trace(expected): assert_element(condition_trace[key][index], element, path) -async def test_invalid_condition(hass): +async def test_invalid_condition(hass: HomeAssistant) -> None: """Test if invalid condition raises.""" with pytest.raises(HomeAssistantError): await condition.async_from_config( @@ -104,7 +104,7 @@ async def test_invalid_condition(hass): ) -async def test_and_condition(hass): +async def test_and_condition(hass: HomeAssistant) -> None: """Test the 'and' condition.""" config = { "alias": "And Condition", @@ -177,7 +177,7 @@ async def test_and_condition(hass): ) -async def test_and_condition_raises(hass): +async def test_and_condition_raises(hass: HomeAssistant) -> None: """Test the 'and' condition.""" config = { "alias": "And Condition", @@ -250,7 +250,7 @@ async def test_and_condition_raises(hass): ) -async def test_and_condition_with_template(hass): +async def test_and_condition_with_template(hass: HomeAssistant) -> None: """Test the 'and' condition.""" config = { "condition": "and", @@ -289,7 +289,7 @@ async def test_and_condition_with_template(hass): assert test(hass) -async def test_and_condition_shorthand(hass): +async def test_and_condition_shorthand(hass: HomeAssistant) -> None: """Test the 'and' condition shorthand.""" config = { "alias": "And Condition Shorthand", @@ -331,7 +331,7 @@ async def test_and_condition_shorthand(hass): assert test(hass) -async def test_and_condition_list_shorthand(hass): +async def test_and_condition_list_shorthand(hass: HomeAssistant) -> None: """Test the 'and' condition list shorthand.""" config = { "alias": "And Condition List Shorthand", @@ -373,7 +373,7 @@ async def test_and_condition_list_shorthand(hass): assert test(hass) -async def test_malformed_and_condition_list_shorthand(hass): +async def test_malformed_and_condition_list_shorthand(hass: HomeAssistant) -> None: """Test the 'and' condition list shorthand syntax check.""" config = { "alias": "Bad shorthand syntax", @@ -384,7 +384,7 @@ async def test_malformed_and_condition_list_shorthand(hass): cv.CONDITION_SCHEMA(config) -async def test_or_condition(hass): +async def test_or_condition(hass: HomeAssistant) -> None: """Test the 'or' condition.""" config = { "alias": "Or Condition", @@ -467,7 +467,7 @@ async def test_or_condition(hass): ) -async def test_or_condition_raises(hass): +async def test_or_condition_raises(hass: HomeAssistant) -> None: """Test the 'or' condition.""" config = { "alias": "Or Condition", @@ -540,7 +540,7 @@ async def test_or_condition_raises(hass): ) -async def test_or_condition_with_template(hass): +async def test_or_condition_with_template(hass: HomeAssistant) -> None: """Test the 'or' condition.""" config = { "condition": "or", @@ -567,7 +567,7 @@ async def test_or_condition_with_template(hass): assert test(hass) -async def test_or_condition_shorthand(hass): +async def test_or_condition_shorthand(hass: HomeAssistant) -> None: """Test the 'or' condition shorthand.""" config = { "alias": "Or Condition Shorthand", @@ -597,7 +597,7 @@ async def test_or_condition_shorthand(hass): assert test(hass) -async def test_not_condition(hass): +async def test_not_condition(hass: HomeAssistant) -> None: """Test the 'not' condition.""" config = { "alias": "Not Condition", @@ -696,7 +696,7 @@ async def test_not_condition(hass): ) -async def test_not_condition_raises(hass): +async def test_not_condition_raises(hass: HomeAssistant) -> None: """Test the 'and' condition.""" config = { "alias": "Not Condition", @@ -763,7 +763,7 @@ async def test_not_condition_raises(hass): ) -async def test_not_condition_with_template(hass): +async def test_not_condition_with_template(hass: HomeAssistant) -> None: """Test the 'or' condition.""" config = { "condition": "not", @@ -796,7 +796,7 @@ async def test_not_condition_with_template(hass): assert not test(hass) -async def test_not_condition_shorthand(hass): +async def test_not_condition_shorthand(hass: HomeAssistant) -> None: """Test the 'or' condition shorthand.""" config = { "alias": "Not Condition Shorthand", @@ -832,7 +832,7 @@ async def test_not_condition_shorthand(hass): assert not test(hass) -async def test_time_window(hass): +async def test_time_window(hass: HomeAssistant) -> None: """Test time condition windows.""" sixam = "06:00:00" sixpm = "18:00:00" @@ -885,7 +885,7 @@ async def test_time_window(hass): assert test2(hass) -async def test_time_using_input_datetime(hass): +async def test_time_using_input_datetime(hass: HomeAssistant) -> None: """Test time conditions using input_datetime entities.""" await async_setup_component( hass, @@ -1005,7 +1005,7 @@ async def test_time_using_input_datetime(hass): condition.time(hass, before="input_datetime.not_existing") -async def test_time_using_sensor(hass): +async def test_time_using_sensor(hass: HomeAssistant) -> None: """Test time conditions using sensor entities.""" hass.states.async_set( "sensor.am", @@ -1089,7 +1089,7 @@ async def test_time_using_sensor(hass): condition.time(hass, before="sensor.not_existing") -async def test_state_raises(hass): +async def test_state_raises(hass: HomeAssistant) -> None: """Test that state raises ConditionError on errors.""" # No entity with pytest.raises(ConditionError, match="no entity"): @@ -1124,7 +1124,7 @@ async def test_state_raises(hass): test(hass) -async def test_state_unknown_attribute(hass): +async def test_state_unknown_attribute(hass: HomeAssistant) -> None: """Test that state returns False on unknown attribute.""" # Unknown attribute config = { @@ -1156,7 +1156,7 @@ async def test_state_unknown_attribute(hass): ) -async def test_state_multiple_entities(hass): +async def test_state_multiple_entities(hass: HomeAssistant) -> None: """Test with multiple entities in condition.""" config = { "condition": "and", @@ -1219,7 +1219,7 @@ async def test_state_multiple_entities_match_any(hass: HomeAssistant) -> None: assert not test(hass) -async def test_multiple_states(hass): +async def test_multiple_states(hass: HomeAssistant) -> None: """Test with multiple states in condition.""" config = { "condition": "and", @@ -1246,7 +1246,7 @@ async def test_multiple_states(hass): assert not test(hass) -async def test_state_attribute(hass): +async def test_state_attribute(hass: HomeAssistant) -> None: """Test with state attribute in condition.""" config = { "condition": "and", @@ -1279,7 +1279,7 @@ async def test_state_attribute(hass): assert not test(hass) -async def test_state_attribute_boolean(hass): +async def test_state_attribute_boolean(hass: HomeAssistant) -> None: """Test with boolean state attribute in condition.""" config = { "condition": "state", @@ -1304,7 +1304,7 @@ async def test_state_attribute_boolean(hass): assert test(hass) -async def test_state_entity_registry_id(hass): +async def test_state_entity_registry_id(hass: HomeAssistant) -> None: """Test with entity specified by entity registry id.""" registry = er.async_get(hass) entry = registry.async_get_or_create( @@ -1327,7 +1327,7 @@ async def test_state_entity_registry_id(hass): assert not test(hass) -async def test_state_using_input_entities(hass): +async def test_state_using_input_entities(hass: HomeAssistant) -> None: """Test state conditions using input_* entities.""" await async_setup_component( hass, @@ -1408,7 +1408,7 @@ async def test_state_using_input_entities(hass): assert test(hass) -async def test_numeric_state_known_non_matching(hass): +async def test_numeric_state_known_non_matching(hass: HomeAssistant) -> None: """Test that numeric_state doesn't match on known non-matching states.""" hass.states.async_set("sensor.temperature", "unavailable") config = { @@ -1460,7 +1460,7 @@ async def test_numeric_state_known_non_matching(hass): ) -async def test_numeric_state_raises(hass): +async def test_numeric_state_raises(hass: HomeAssistant) -> None: """Test that numeric_state raises ConditionError on errors.""" # Unknown entities config = { @@ -1550,7 +1550,7 @@ async def test_numeric_state_raises(hass): test(hass) -async def test_numeric_state_unknown_attribute(hass): +async def test_numeric_state_unknown_attribute(hass: HomeAssistant) -> None: """Test that numeric_state returns False on unknown attribute.""" # Unknown attribute config = { @@ -1583,7 +1583,7 @@ async def test_numeric_state_unknown_attribute(hass): ) -async def test_numeric_state_multiple_entities(hass): +async def test_numeric_state_multiple_entities(hass: HomeAssistant) -> None: """Test with multiple entities in condition.""" config = { "condition": "and", @@ -1613,7 +1613,7 @@ async def test_numeric_state_multiple_entities(hass): assert not test(hass) -async def test_numeric_state_attribute(hass): +async def test_numeric_state_attribute(hass: HomeAssistant) -> None: """Test with numeric state attribute in condition.""" config = { "condition": "and", @@ -1646,7 +1646,7 @@ async def test_numeric_state_attribute(hass): assert not test(hass) -async def test_numeric_state_entity_registry_id(hass): +async def test_numeric_state_entity_registry_id(hass: HomeAssistant) -> None: """Test with entity specified by entity registry id.""" registry = er.async_get(hass) entry = registry.async_get_or_create( @@ -1669,7 +1669,7 @@ async def test_numeric_state_entity_registry_id(hass): assert not test(hass) -async def test_numeric_state_using_input_number(hass): +async def test_numeric_state_using_input_number(hass: HomeAssistant) -> None: """Test numeric_state conditions using input_number entities.""" hass.states.async_set("number.low", 10) await async_setup_component( @@ -1739,7 +1739,7 @@ async def test_numeric_state_using_input_number(hass): ) -async def test_zone_raises(hass): +async def test_zone_raises(hass: HomeAssistant) -> None: """Test that zone raises ConditionError on errors.""" config = { "condition": "zone", @@ -1825,7 +1825,7 @@ async def test_zone_raises(hass): assert test(hass) -async def test_zone_multiple_entities(hass): +async def test_zone_multiple_entities(hass: HomeAssistant) -> None: """Test with multiple entities in condition.""" config = { "condition": "and", @@ -1885,7 +1885,7 @@ async def test_zone_multiple_entities(hass): assert not test(hass) -async def test_multiple_zones(hass): +async def test_multiple_zones(hass: HomeAssistant) -> None: """Test with multiple entities in condition.""" config = { "condition": "and", @@ -2056,7 +2056,7 @@ async def test_extract_devices() -> None: ) == {"abcd", "qwer", "abcd_not", "qwer_not", "abcd_or", "qwer_or"} -async def test_condition_template_error(hass): +async def test_condition_template_error(hass: HomeAssistant) -> None: """Test invalid template.""" config = {"condition": "template", "value_template": "{{ undefined.state }}"} config = cv.CONDITION_SCHEMA(config) @@ -2067,7 +2067,7 @@ async def test_condition_template_error(hass): test(hass) -async def test_condition_template_invalid_results(hass): +async def test_condition_template_invalid_results(hass: HomeAssistant) -> None: """Test template condition render false with invalid results.""" config = {"condition": "template", "value_template": "{{ 'string' }}"} config = cv.CONDITION_SCHEMA(config) @@ -3260,7 +3260,7 @@ async def test_if_action_after_sunset_no_offset_kotzebue(hass, hass_ws_client, c ) -async def test_trigger(hass): +async def test_trigger(hass: HomeAssistant) -> None: """Test trigger condition.""" config = {"alias": "Trigger Cond", "condition": "trigger", "id": "123456"} config = cv.CONDITION_SCHEMA(config) @@ -3274,7 +3274,7 @@ async def test_trigger(hass): assert test(hass, {"trigger": {"id": "123456"}}) -async def test_platform_async_validate_condition_config(hass): +async def test_platform_async_validate_condition_config(hass: HomeAssistant) -> None: """Test platform.async_validate_condition_config will be called if it exists.""" config = {CONF_DEVICE_ID: "test", CONF_DOMAIN: "test", CONF_CONDITION: "device"} with patch( @@ -3305,7 +3305,7 @@ async def test_disabled_condition(hass: HomeAssistant) -> None: assert test(hass) is None -async def test_and_condition_with_disabled_condition(hass): +async def test_and_condition_with_disabled_condition(hass: HomeAssistant) -> None: """Test the 'and' condition with one of the conditions disabled.""" config = { "alias": "And Condition", @@ -3370,7 +3370,7 @@ async def test_and_condition_with_disabled_condition(hass): ) -async def test_or_condition_with_disabled_condition(hass): +async def test_or_condition_with_disabled_condition(hass: HomeAssistant) -> None: """Test the 'or' condition with one of the conditions disabled.""" config = { "alias": "Or Condition", diff --git a/tests/helpers/test_debounce.py b/tests/helpers/test_debounce.py index cdced565e73..eb1cdf6db76 100644 --- a/tests/helpers/test_debounce.py +++ b/tests/helpers/test_debounce.py @@ -1,10 +1,11 @@ """Tests for debounce.""" from unittest.mock import AsyncMock +from homeassistant.core import HomeAssistant from homeassistant.helpers import debounce -async def test_immediate_works(hass): +async def test_immediate_works(hass: HomeAssistant) -> None: """Test immediate works.""" calls = [] debouncer = debounce.Debouncer( @@ -57,7 +58,7 @@ async def test_immediate_works(hass): assert debouncer._job.target == debouncer.function -async def test_not_immediate_works(hass): +async def test_not_immediate_works(hass: HomeAssistant) -> None: """Test immediate works.""" calls = [] debouncer = debounce.Debouncer( @@ -107,7 +108,7 @@ async def test_not_immediate_works(hass): assert debouncer._job.target == debouncer.function -async def test_immediate_works_with_function_swapped(hass): +async def test_immediate_works_with_function_swapped(hass: HomeAssistant) -> None: """Test immediate works and we can change out the function.""" calls = [] diff --git a/tests/helpers/test_device_registry.py b/tests/helpers/test_device_registry.py index 9d5c95ccaa3..fd7637d5c53 100644 --- a/tests/helpers/test_device_registry.py +++ b/tests/helpers/test_device_registry.py @@ -6,7 +6,7 @@ import pytest from homeassistant import config_entries from homeassistant.const import EVENT_HOMEASSISTANT_STARTED -from homeassistant.core import CoreState, callback +from homeassistant.core import CoreState, HomeAssistant, callback from homeassistant.exceptions import RequiredParameterMissing from homeassistant.helpers import device_registry, entity_registry @@ -1159,7 +1159,7 @@ async def test_cleanup_device_registry_removes_expired_orphaned_devices(hass, re assert len(registry.deleted_devices) == 0 -async def test_cleanup_startup(hass): +async def test_cleanup_startup(hass: HomeAssistant) -> None: """Test we run a cleanup on startup.""" hass.state = CoreState.not_running @@ -1173,7 +1173,7 @@ async def test_cleanup_startup(hass): @pytest.mark.parametrize("load_registries", [False]) -async def test_cleanup_entity_registry_change(hass): +async def test_cleanup_entity_registry_change(hass: HomeAssistant) -> None: """Test we run a cleanup when entity registry changes. Don't pre-load the registries as the debouncer will then not be waiting for diff --git a/tests/helpers/test_discovery.py b/tests/helpers/test_discovery.py index 3a2d0e7fbac..a3913fd9599 100644 --- a/tests/helpers/test_discovery.py +++ b/tests/helpers/test_discovery.py @@ -5,7 +5,7 @@ import pytest from homeassistant import setup from homeassistant.const import Platform -from homeassistant.core import callback +from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import discovery from homeassistant.helpers.dispatcher import async_dispatcher_send @@ -104,7 +104,7 @@ async def test_platform(hass, mock_setup_component): assert len(calls) == 1 -async def test_circular_import(hass): +async def test_circular_import(hass: HomeAssistant) -> None: """Test we don't break doing circular import. This test will have test_component discover the switch.test_circular @@ -155,7 +155,7 @@ async def test_circular_import(hass): assert "switch" in hass.config.components -async def test_1st_discovers_2nd_component(hass): +async def test_1st_discovers_2nd_component(hass: HomeAssistant) -> None: """Test that we don't break if one component discovers the other. If the first component fires a discovery event to set up the diff --git a/tests/helpers/test_dispatcher.py b/tests/helpers/test_dispatcher.py index 09c7942d08f..639157607b3 100644 --- a/tests/helpers/test_dispatcher.py +++ b/tests/helpers/test_dispatcher.py @@ -3,14 +3,14 @@ from functools import partial import pytest -from homeassistant.core import callback +from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, async_dispatcher_send, ) -async def test_simple_function(hass): +async def test_simple_function(hass: HomeAssistant) -> None: """Test simple function (executor).""" calls = [] @@ -30,7 +30,7 @@ async def test_simple_function(hass): assert calls == [3, "bla"] -async def test_simple_function_unsub(hass): +async def test_simple_function_unsub(hass: HomeAssistant) -> None: """Test simple function (executor) and unsub.""" calls1 = [] calls2 = [] @@ -72,7 +72,7 @@ async def test_simple_function_unsub(hass): assert calls2 == [4] -async def test_simple_callback(hass): +async def test_simple_callback(hass: HomeAssistant) -> None: """Test simple callback (async).""" calls = [] @@ -93,7 +93,7 @@ async def test_simple_callback(hass): assert calls == [3, "bla"] -async def test_simple_coro(hass): +async def test_simple_coro(hass: HomeAssistant) -> None: """Test simple coro (async).""" calls = [] @@ -113,7 +113,7 @@ async def test_simple_coro(hass): assert calls == [3, "bla"] -async def test_simple_function_multiargs(hass): +async def test_simple_function_multiargs(hass: HomeAssistant) -> None: """Test simple function (executor).""" calls = [] diff --git a/tests/helpers/test_entity.py b/tests/helpers/test_entity.py index 2a83ff998b5..80298686dde 100644 --- a/tests/helpers/test_entity.py +++ b/tests/helpers/test_entity.py @@ -16,7 +16,7 @@ from homeassistant.const import ( STATE_UNAVAILABLE, STATE_UNKNOWN, ) -from homeassistant.core import Context, HomeAssistantError +from homeassistant.core import Context, HomeAssistant, HomeAssistantError from homeassistant.helpers import device_registry as dr, entity, entity_registry as er from tests.common import ( @@ -53,7 +53,7 @@ def test_generate_entity_id_given_keys() -> None: ) -async def test_async_update_support(hass): +async def test_async_update_support(hass: HomeAssistant) -> None: """Test async update getting called.""" sync_update = [] async_update = [] @@ -196,7 +196,7 @@ async def test_warn_slow_device_update_disabled(hass, caplog): assert update_call -async def test_async_schedule_update_ha_state(hass): +async def test_async_schedule_update_ha_state(hass: HomeAssistant) -> None: """Warn we log when entity update takes a long time and trow exception.""" update_call = False @@ -216,7 +216,7 @@ async def test_async_schedule_update_ha_state(hass): assert update_call is True -async def test_async_async_request_call_without_lock(hass): +async def test_async_async_request_call_without_lock(hass: HomeAssistant) -> None: """Test for async_requests_call works without a lock.""" updates = [] @@ -251,7 +251,7 @@ async def test_async_async_request_call_without_lock(hass): assert updates == [1, 2] -async def test_async_async_request_call_with_lock(hass): +async def test_async_async_request_call_with_lock(hass: HomeAssistant) -> None: """Test for async_requests_call works with a semaphore.""" updates = [] @@ -302,7 +302,7 @@ async def test_async_async_request_call_with_lock(hass): assert updates == [1, 2] -async def test_async_parallel_updates_with_zero(hass): +async def test_async_parallel_updates_with_zero(hass: HomeAssistant) -> None: """Test parallel updates with 0 (disabled).""" updates = [] test_lock = asyncio.Event() @@ -339,7 +339,9 @@ async def test_async_parallel_updates_with_zero(hass): test_lock.set() -async def test_async_parallel_updates_with_zero_on_sync_update(hass): +async def test_async_parallel_updates_with_zero_on_sync_update( + hass: HomeAssistant, +) -> None: """Test parallel updates with 0 (disabled).""" updates = [] test_lock = threading.Event() @@ -379,7 +381,7 @@ async def test_async_parallel_updates_with_zero_on_sync_update(hass): await asyncio.sleep(0) -async def test_async_parallel_updates_with_one(hass): +async def test_async_parallel_updates_with_one(hass: HomeAssistant) -> None: """Test parallel updates with 1 (sequential).""" updates = [] test_lock = asyncio.Lock() @@ -455,7 +457,7 @@ async def test_async_parallel_updates_with_one(hass): test_lock.release() -async def test_async_parallel_updates_with_two(hass): +async def test_async_parallel_updates_with_two(hass: HomeAssistant) -> None: """Test parallel updates with 2 (parallel).""" updates = [] test_lock = asyncio.Lock() @@ -524,7 +526,7 @@ async def test_async_parallel_updates_with_two(hass): test_lock.release() -async def test_async_remove_no_platform(hass): +async def test_async_remove_no_platform(hass: HomeAssistant) -> None: """Test async_remove method when no platform set.""" ent = entity.Entity() ent.hass = hass @@ -535,7 +537,7 @@ async def test_async_remove_no_platform(hass): assert len(hass.states.async_entity_ids()) == 0 -async def test_async_remove_runs_callbacks(hass): +async def test_async_remove_runs_callbacks(hass: HomeAssistant) -> None: """Test async_remove method when no platform set.""" result = [] @@ -547,7 +549,7 @@ async def test_async_remove_runs_callbacks(hass): assert len(result) == 1 -async def test_async_remove_ignores_in_flight_polling(hass): +async def test_async_remove_ignores_in_flight_polling(hass: HomeAssistant) -> None: """Test in flight polling is ignored after removing.""" result = [] @@ -563,7 +565,7 @@ async def test_async_remove_ignores_in_flight_polling(hass): ent.async_write_ha_state() -async def test_set_context(hass): +async def test_set_context(hass: HomeAssistant) -> None: """Test setting context.""" context = Context() ent = entity.Entity() @@ -574,7 +576,7 @@ async def test_set_context(hass): assert hass.states.get("hello.world").context == context -async def test_set_context_expired(hass): +async def test_set_context_expired(hass: HomeAssistant) -> None: """Test setting context.""" context = Context() @@ -620,7 +622,7 @@ async def test_warn_disabled(hass, caplog): assert caplog.text == "" -async def test_disabled_in_entity_registry(hass): +async def test_disabled_in_entity_registry(hass: HomeAssistant) -> None: """Test entity is removed if we disable entity registry entry.""" entry = er.RegistryEntry( entity_id="hello.world", @@ -656,7 +658,7 @@ async def test_disabled_in_entity_registry(hass): assert ent.registry_entry == entry2 -async def test_capability_attrs(hass): +async def test_capability_attrs(hass: HomeAssistant) -> None: """Test we still include capabilities even when unavailable.""" with patch.object( entity.Entity, "available", PropertyMock(return_value=False) @@ -718,7 +720,7 @@ async def test_warn_slow_write_state_custom_component(hass, caplog): ) in caplog.text -async def test_setup_source(hass): +async def test_setup_source(hass: HomeAssistant) -> None: """Check that we register sources correctly.""" platform = MockEntityPlatform(hass) @@ -748,7 +750,7 @@ async def test_setup_source(hass): assert entity.entity_sources(hass) == {} -async def test_removing_entity_unavailable(hass): +async def test_removing_entity_unavailable(hass: HomeAssistant) -> None: """Test removing an entity that is still registered creates an unavailable state.""" entry = er.RegistryEntry( entity_id="hello.world", @@ -774,7 +776,7 @@ async def test_removing_entity_unavailable(hass): assert state.state == STATE_UNAVAILABLE -async def test_get_supported_features_entity_registry(hass): +async def test_get_supported_features_entity_registry(hass: HomeAssistant) -> None: """Test get_supported_features falls back to entity registry.""" entity_reg = mock_registry(hass) entity_id = entity_reg.async_get_or_create( @@ -783,7 +785,7 @@ async def test_get_supported_features_entity_registry(hass): assert entity.get_supported_features(hass, entity_id) == 456 -async def test_get_supported_features_prioritize_state(hass): +async def test_get_supported_features_prioritize_state(hass: HomeAssistant) -> None: """Test get_supported_features gives priority to state.""" entity_reg = mock_registry(hass) entity_id = entity_reg.async_get_or_create( @@ -796,13 +798,13 @@ async def test_get_supported_features_prioritize_state(hass): assert entity.get_supported_features(hass, entity_id) == 123 -async def test_get_supported_features_raises_on_unknown(hass): +async def test_get_supported_features_raises_on_unknown(hass: HomeAssistant) -> None: """Test get_supported_features raises on unknown entity_id.""" with pytest.raises(HomeAssistantError): entity.get_supported_features(hass, "hello.world") -async def test_float_conversion(hass): +async def test_float_conversion(hass: HomeAssistant) -> None: """Test conversion of float state to string rounds.""" assert 2.4 + 1.2 != 3.6 with patch.object(entity.Entity, "state", PropertyMock(return_value=2.4 + 1.2)): @@ -816,7 +818,7 @@ async def test_float_conversion(hass): assert state.state == "3.6" -async def test_attribution_attribute(hass): +async def test_attribution_attribute(hass: HomeAssistant) -> None: """Test attribution attribute.""" mock_entity = entity.Entity() mock_entity.hass = hass @@ -830,7 +832,7 @@ async def test_attribution_attribute(hass): assert state.attributes.get(ATTR_ATTRIBUTION) == "Home Assistant" -async def test_entity_category_property(hass): +async def test_entity_category_property(hass: HomeAssistant) -> None: """Test entity category property.""" mock_entity1 = entity.Entity() mock_entity1.hass = hass @@ -935,7 +937,7 @@ async def test_friendly_name( assert state.attributes.get(ATTR_FRIENDLY_NAME) == expected_friendly_name -async def test_translation_key(hass): +async def test_translation_key(hass: HomeAssistant) -> None: """Test translation key property.""" mock_entity1 = entity.Entity() mock_entity1.hass = hass diff --git a/tests/helpers/test_entity_component.py b/tests/helpers/test_entity_component.py index 8c51d0a2f07..3104da02df5 100644 --- a/tests/helpers/test_entity_component.py +++ b/tests/helpers/test_entity_component.py @@ -14,7 +14,7 @@ from homeassistant.const import ( ENTITY_MATCH_NONE, EVENT_HOMEASSISTANT_STOP, ) -import homeassistant.core as ha +from homeassistant.core import HomeAssistant, ServiceCall, callback from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers import discovery from homeassistant.helpers.entity_component import EntityComponent, async_update_entity @@ -35,7 +35,7 @@ _LOGGER = logging.getLogger(__name__) DOMAIN = "test_domain" -async def test_setup_loads_platforms(hass): +async def test_setup_loads_platforms(hass: HomeAssistant) -> None: """Test the loading of the platforms.""" component_setup = Mock(return_value=True) platform_setup = Mock(return_value=None) @@ -57,7 +57,7 @@ async def test_setup_loads_platforms(hass): assert platform_setup.called -async def test_setup_recovers_when_setup_raises(hass): +async def test_setup_recovers_when_setup_raises(hass: HomeAssistant) -> None: """Test the setup if exceptions are happening.""" platform1_setup = Mock(side_effect=Exception("Broken")) platform2_setup = Mock(return_value=None) @@ -126,7 +126,7 @@ async def test_set_scan_interval_via_config(mock_track, hass): assert timedelta(seconds=30) == mock_track.call_args[0][2] -async def test_set_entity_namespace_via_config(hass): +async def test_set_entity_namespace_via_config(hass: HomeAssistant) -> None: """Test setting an entity namespace.""" def platform_setup(hass, config, add_entities, discovery_info=None): @@ -149,7 +149,7 @@ async def test_set_entity_namespace_via_config(hass): ] -async def test_extract_from_service_available_device(hass): +async def test_extract_from_service_available_device(hass: HomeAssistant) -> None: """Test the extraction of entity from service and device is available.""" component = EntityComponent(_LOGGER, DOMAIN, hass) await component.async_add_entities( @@ -161,13 +161,13 @@ async def test_extract_from_service_available_device(hass): ] ) - call_1 = ha.ServiceCall("test", "service", data={"entity_id": ENTITY_MATCH_ALL}) + call_1 = ServiceCall("test", "service", data={"entity_id": ENTITY_MATCH_ALL}) assert ["test_domain.test_1", "test_domain.test_3"] == sorted( ent.entity_id for ent in (await component.async_extract_from_service(call_1)) ) - call_2 = ha.ServiceCall( + call_2 = ServiceCall( "test", "service", data={"entity_id": ["test_domain.test_3", "test_domain.test_4"]}, @@ -178,7 +178,7 @@ async def test_extract_from_service_available_device(hass): ) -async def test_platform_not_ready(hass): +async def test_platform_not_ready(hass: HomeAssistant) -> None: """Test that we retry when platform not ready.""" platform1_setup = Mock(side_effect=[PlatformNotReady, PlatformNotReady, None]) mock_integration(hass, MockModule("mod1")) @@ -217,7 +217,7 @@ async def test_platform_not_ready(hass): assert "test_domain.mod1" in hass.config.components -async def test_extract_from_service_fails_if_no_entity_id(hass): +async def test_extract_from_service_fails_if_no_entity_id(hass: HomeAssistant) -> None: """Test the extraction of everything from service.""" component = EntityComponent(_LOGGER, DOMAIN, hass) await component.async_add_entities( @@ -225,31 +225,32 @@ async def test_extract_from_service_fails_if_no_entity_id(hass): ) assert ( - await component.async_extract_from_service(ha.ServiceCall("test", "service")) - == [] + await component.async_extract_from_service(ServiceCall("test", "service")) == [] ) assert ( await component.async_extract_from_service( - ha.ServiceCall("test", "service", {"entity_id": ENTITY_MATCH_NONE}) + ServiceCall("test", "service", {"entity_id": ENTITY_MATCH_NONE}) ) == [] ) assert ( await component.async_extract_from_service( - ha.ServiceCall("test", "service", {"area_id": ENTITY_MATCH_NONE}) + ServiceCall("test", "service", {"area_id": ENTITY_MATCH_NONE}) ) == [] ) -async def test_extract_from_service_filter_out_non_existing_entities(hass): +async def test_extract_from_service_filter_out_non_existing_entities( + hass: HomeAssistant, +) -> None: """Test the extraction of non existing entities from service.""" component = EntityComponent(_LOGGER, DOMAIN, hass) await component.async_add_entities( [MockEntity(name="test_1"), MockEntity(name="test_2")] ) - call = ha.ServiceCall( + call = ServiceCall( "test", "service", {"entity_id": ["test_domain.test_2", "test_domain.non_exist"]}, @@ -260,19 +261,19 @@ async def test_extract_from_service_filter_out_non_existing_entities(hass): ] -async def test_extract_from_service_no_group_expand(hass): +async def test_extract_from_service_no_group_expand(hass: HomeAssistant) -> None: """Test not expanding a group.""" component = EntityComponent(_LOGGER, DOMAIN, hass) await component.async_add_entities([MockEntity(entity_id="group.test_group")]) - call = ha.ServiceCall("test", "service", {"entity_id": ["group.test_group"]}) + call = ServiceCall("test", "service", {"entity_id": ["group.test_group"]}) extracted = await component.async_extract_from_service(call, expand_group=False) assert len(extracted) == 1 assert extracted[0].entity_id == "group.test_group" -async def test_setup_dependencies_platform(hass): +async def test_setup_dependencies_platform(hass: HomeAssistant) -> None: """Test we setup the dependencies of a platform. We're explicitly testing that we process dependencies even if a component @@ -293,7 +294,7 @@ async def test_setup_dependencies_platform(hass): assert "test_domain.test_component" in hass.config.components -async def test_setup_entry(hass): +async def test_setup_entry(hass: HomeAssistant) -> None: """Test setup entry calls async_setup_entry on platform.""" mock_setup_entry = AsyncMock(return_value=True) mock_entity_platform( @@ -316,7 +317,7 @@ async def test_setup_entry(hass): assert component._platforms[entry.entry_id].scan_interval == timedelta(seconds=5) -async def test_setup_entry_platform_not_exist(hass): +async def test_setup_entry_platform_not_exist(hass: HomeAssistant) -> None: """Test setup entry fails if platform does not exist.""" component = EntityComponent(_LOGGER, DOMAIN, hass) entry = MockConfigEntry(domain="non_existing") @@ -324,7 +325,7 @@ async def test_setup_entry_platform_not_exist(hass): assert (await component.async_setup_entry(entry)) is False -async def test_setup_entry_fails_duplicate(hass): +async def test_setup_entry_fails_duplicate(hass: HomeAssistant) -> None: """Test we don't allow setting up a config entry twice.""" mock_setup_entry = AsyncMock(return_value=True) mock_entity_platform( @@ -342,7 +343,7 @@ async def test_setup_entry_fails_duplicate(hass): await component.async_setup_entry(entry) -async def test_unload_entry_resets_platform(hass): +async def test_unload_entry_resets_platform(hass: HomeAssistant) -> None: """Test unloading an entry removes all entities.""" mock_setup_entry = AsyncMock(return_value=True) mock_entity_platform( @@ -366,7 +367,7 @@ async def test_unload_entry_resets_platform(hass): assert len(hass.states.async_entity_ids()) == 0 -async def test_unload_entry_fails_if_never_loaded(hass): +async def test_unload_entry_fails_if_never_loaded(hass: HomeAssistant) -> None: """.""" component = EntityComponent(_LOGGER, DOMAIN, hass) entry = MockConfigEntry(domain="entry_domain") @@ -375,7 +376,7 @@ async def test_unload_entry_fails_if_never_loaded(hass): await component.async_unload_entry(entry) -async def test_update_entity(hass): +async def test_update_entity(hass: HomeAssistant) -> None: """Test that we can update an entity with the helper.""" component = EntityComponent(_LOGGER, DOMAIN, hass) entity = MockEntity() @@ -392,7 +393,7 @@ async def test_update_entity(hass): assert entity.async_update_ha_state.mock_calls[-1][1][0] is True -async def test_set_service_race(hass): +async def test_set_service_race(hass: HomeAssistant) -> None: """Test race condition on setting service.""" exception = False @@ -420,7 +421,7 @@ async def test_extract_all_omit_entity_id(hass, caplog): [MockEntity(name="test_1"), MockEntity(name="test_2")] ) - call = ha.ServiceCall("test", "service") + call = ServiceCall("test", "service") assert [] == sorted( ent.entity_id for ent in await component.async_extract_from_service(call) @@ -434,7 +435,7 @@ async def test_extract_all_use_match_all(hass, caplog): [MockEntity(name="test_1"), MockEntity(name="test_2")] ) - call = ha.ServiceCall("test", "service", {"entity_id": "all"}) + call = ServiceCall("test", "service", {"entity_id": "all"}) assert ["test_domain.test_1", "test_domain.test_2"] == sorted( ent.entity_id for ent in await component.async_extract_from_service(call) @@ -444,12 +445,12 @@ async def test_extract_all_use_match_all(hass, caplog): ) not in caplog.text -async def test_register_entity_service(hass): +async def test_register_entity_service(hass: HomeAssistant) -> None: """Test not expanding a group.""" entity = MockEntity(entity_id=f"{DOMAIN}.entity") calls = [] - @ha.callback + @callback def appender(**kwargs): calls.append(kwargs) @@ -494,7 +495,7 @@ async def test_register_entity_service(hass): assert len(calls) == 2 -async def test_platforms_shutdown_on_stop(hass): +async def test_platforms_shutdown_on_stop(hass: HomeAssistant) -> None: """Test that we shutdown platforms on stop.""" platform1_setup = Mock(side_effect=[PlatformNotReady, PlatformNotReady, None]) mock_integration(hass, MockModule("mod1")) diff --git a/tests/helpers/test_entity_platform.py b/tests/helpers/test_entity_platform.py index c7721f7f78c..e1473bbc4cb 100644 --- a/tests/helpers/test_entity_platform.py +++ b/tests/helpers/test_entity_platform.py @@ -40,7 +40,9 @@ DOMAIN = "test_domain" PLATFORM = "test_platform" -async def test_polling_only_updates_entities_it_should_poll(hass): +async def test_polling_only_updates_entities_it_should_poll( + hass: HomeAssistant, +) -> None: """Test the polling of only updated entities.""" component = EntityComponent(_LOGGER, DOMAIN, hass, timedelta(seconds=20)) @@ -61,7 +63,7 @@ async def test_polling_only_updates_entities_it_should_poll(hass): assert poll_ent.async_update.called -async def test_polling_disabled_by_config_entry(hass): +async def test_polling_disabled_by_config_entry(hass: HomeAssistant) -> None: """Test the polling of only updated entities.""" entity_platform = MockEntityPlatform(hass) entity_platform.config_entry = MockConfigEntry(pref_disable_polling=True) @@ -72,7 +74,7 @@ async def test_polling_disabled_by_config_entry(hass): assert entity_platform._async_unsub_polling is None -async def test_polling_updates_entities_with_exception(hass): +async def test_polling_updates_entities_with_exception(hass: HomeAssistant) -> None: """Test the updated entities that not break with an exception.""" component = EntityComponent(_LOGGER, DOMAIN, hass, timedelta(seconds=20)) @@ -109,7 +111,7 @@ async def test_polling_updates_entities_with_exception(hass): assert len(update_err) == 1 -async def test_update_state_adds_entities(hass): +async def test_update_state_adds_entities(hass: HomeAssistant) -> None: """Test if updating poll entities cause an entity to be added works.""" component = EntityComponent(_LOGGER, DOMAIN, hass) @@ -126,7 +128,9 @@ async def test_update_state_adds_entities(hass): assert len(hass.states.async_entity_ids()) == 2 -async def test_update_state_adds_entities_with_update_before_add_true(hass): +async def test_update_state_adds_entities_with_update_before_add_true( + hass: HomeAssistant, +) -> None: """Test if call update before add to state machine.""" component = EntityComponent(_LOGGER, DOMAIN, hass) @@ -140,7 +144,9 @@ async def test_update_state_adds_entities_with_update_before_add_true(hass): assert ent.update.called -async def test_update_state_adds_entities_with_update_before_add_false(hass): +async def test_update_state_adds_entities_with_update_before_add_false( + hass: HomeAssistant, +) -> None: """Test if not call update before add to state machine.""" component = EntityComponent(_LOGGER, DOMAIN, hass) @@ -176,7 +182,9 @@ async def test_set_scan_interval_via_platform(mock_track, hass): assert timedelta(seconds=30) == mock_track.call_args[0][2] -async def test_adding_entities_with_generator_and_thread_callback(hass): +async def test_adding_entities_with_generator_and_thread_callback( + hass: HomeAssistant, +) -> None: """Test generator in add_entities that calls thread method. We should make sure we resolve the generator to a list before passing @@ -193,7 +201,7 @@ async def test_adding_entities_with_generator_and_thread_callback(hass): await component.async_add_entities(create_entity(i) for i in range(2)) -async def test_platform_warn_slow_setup(hass): +async def test_platform_warn_slow_setup(hass: HomeAssistant) -> None: """Warn we log when platform setup takes a long time.""" platform = MockPlatform() @@ -235,7 +243,7 @@ async def test_platform_error_slow_setup(hass, caplog): assert "test_platform is taking longer than 0 seconds" in caplog.text -async def test_updated_state_used_for_entity_id(hass): +async def test_updated_state_used_for_entity_id(hass: HomeAssistant) -> None: """Test that first update results used for entity ID generation.""" component = EntityComponent(_LOGGER, DOMAIN, hass) @@ -253,7 +261,7 @@ async def test_updated_state_used_for_entity_id(hass): assert entity_ids[0] == "test_domain.living_room" -async def test_parallel_updates_async_platform(hass): +async def test_parallel_updates_async_platform(hass: HomeAssistant) -> None: """Test async platform does not have parallel_updates limit by default.""" platform = MockPlatform() @@ -279,7 +287,9 @@ async def test_parallel_updates_async_platform(hass): assert entity.parallel_updates is None -async def test_parallel_updates_async_platform_with_constant(hass): +async def test_parallel_updates_async_platform_with_constant( + hass: HomeAssistant, +) -> None: """Test async platform can set parallel_updates limit.""" platform = MockPlatform() platform.PARALLEL_UPDATES = 2 @@ -306,7 +316,7 @@ async def test_parallel_updates_async_platform_with_constant(hass): assert entity.parallel_updates._value == 2 -async def test_parallel_updates_sync_platform(hass): +async def test_parallel_updates_sync_platform(hass: HomeAssistant) -> None: """Test sync platform parallel_updates default set to 1.""" platform = MockPlatform() @@ -332,7 +342,7 @@ async def test_parallel_updates_sync_platform(hass): assert entity.parallel_updates._value == 1 -async def test_parallel_updates_no_update_method(hass): +async def test_parallel_updates_no_update_method(hass: HomeAssistant) -> None: """Test platform parallel_updates default set to 0.""" platform = MockPlatform() @@ -351,7 +361,9 @@ async def test_parallel_updates_no_update_method(hass): assert entity.parallel_updates is None -async def test_parallel_updates_sync_platform_with_constant(hass): +async def test_parallel_updates_sync_platform_with_constant( + hass: HomeAssistant, +) -> None: """Test sync platform can set parallel_updates limit.""" platform = MockPlatform() platform.PARALLEL_UPDATES = 2 @@ -378,7 +390,7 @@ async def test_parallel_updates_sync_platform_with_constant(hass): assert entity.parallel_updates._value == 2 -async def test_raise_error_on_update(hass): +async def test_raise_error_on_update(hass: HomeAssistant) -> None: """Test the add entity if they raise an error on update.""" updates = [] component = EntityComponent(_LOGGER, DOMAIN, hass) @@ -403,7 +415,7 @@ async def test_raise_error_on_update(hass): assert entity2.platform is not None -async def test_async_remove_with_platform(hass): +async def test_async_remove_with_platform(hass: HomeAssistant) -> None: """Remove an entity from a platform.""" component = EntityComponent(_LOGGER, DOMAIN, hass) entity1 = MockEntity(name="test_1") @@ -413,7 +425,7 @@ async def test_async_remove_with_platform(hass): assert len(hass.states.async_entity_ids()) == 0 -async def test_async_remove_with_platform_update_finishes(hass): +async def test_async_remove_with_platform_update_finishes(hass: HomeAssistant) -> None: """Remove an entity when an update finishes after its been removed.""" component = EntityComponent(_LOGGER, DOMAIN, hass) entity1 = MockEntity(name="test_1") @@ -474,7 +486,7 @@ async def test_not_adding_duplicate_entities_with_unique_id(hass, caplog): assert entry.original_name == "test1" -async def test_using_prescribed_entity_id(hass): +async def test_using_prescribed_entity_id(hass: HomeAssistant) -> None: """Test for using predefined entity ID.""" component = EntityComponent(_LOGGER, DOMAIN, hass) await component.async_add_entities( @@ -483,7 +495,7 @@ async def test_using_prescribed_entity_id(hass): assert "hello.world" in hass.states.async_entity_ids() -async def test_using_prescribed_entity_id_with_unique_id(hass): +async def test_using_prescribed_entity_id_with_unique_id(hass: HomeAssistant) -> None: """Test for amending predefined entity ID because currently exists.""" component = EntityComponent(_LOGGER, DOMAIN, hass) @@ -495,7 +507,9 @@ async def test_using_prescribed_entity_id_with_unique_id(hass): assert "test_domain.world_2" in hass.states.async_entity_ids() -async def test_using_prescribed_entity_id_which_is_registered(hass): +async def test_using_prescribed_entity_id_which_is_registered( + hass: HomeAssistant, +) -> None: """Test not allowing predefined entity ID that already registered.""" component = EntityComponent(_LOGGER, DOMAIN, hass) registry = mock_registry(hass) @@ -508,7 +522,7 @@ async def test_using_prescribed_entity_id_which_is_registered(hass): assert "test_domain.world_2" in hass.states.async_entity_ids() -async def test_name_which_conflict_with_registered(hass): +async def test_name_which_conflict_with_registered(hass: HomeAssistant) -> None: """Test not generating conflicting entity ID based on name.""" component = EntityComponent(_LOGGER, DOMAIN, hass) registry = mock_registry(hass) @@ -521,7 +535,9 @@ async def test_name_which_conflict_with_registered(hass): assert "test_domain.world_2" in hass.states.async_entity_ids() -async def test_entity_with_name_and_entity_id_getting_registered(hass): +async def test_entity_with_name_and_entity_id_getting_registered( + hass: HomeAssistant, +) -> None: """Ensure that entity ID is used for registration.""" component = EntityComponent(_LOGGER, DOMAIN, hass) await component.async_add_entities( @@ -530,7 +546,7 @@ async def test_entity_with_name_and_entity_id_getting_registered(hass): assert "test_domain.world" in hass.states.async_entity_ids() -async def test_overriding_name_from_registry(hass): +async def test_overriding_name_from_registry(hass: HomeAssistant) -> None: """Test that we can override a name via the Entity Registry.""" component = EntityComponent(_LOGGER, DOMAIN, hass) mock_registry( @@ -554,7 +570,7 @@ async def test_overriding_name_from_registry(hass): assert state.name == "Overridden" -async def test_registry_respect_entity_namespace(hass): +async def test_registry_respect_entity_namespace(hass: HomeAssistant) -> None: """Test that the registry respects entity namespace.""" mock_registry(hass) platform = MockEntityPlatform(hass, entity_namespace="ns") @@ -563,7 +579,7 @@ async def test_registry_respect_entity_namespace(hass): assert entity.entity_id == "test_domain.ns_device_name" -async def test_registry_respect_entity_disabled(hass): +async def test_registry_respect_entity_disabled(hass: HomeAssistant) -> None: """Test that the registry respects entity disabled.""" mock_registry( hass, @@ -606,7 +622,7 @@ async def test_unique_id_conflict_has_priority_over_disabled_entity(hass, caplog assert entry.original_name == "test1" -async def test_entity_registry_updates_name(hass): +async def test_entity_registry_updates_name(hass: HomeAssistant) -> None: """Test that updates on the entity registry update platform entities.""" registry = mock_registry( hass, @@ -636,7 +652,7 @@ async def test_entity_registry_updates_name(hass): assert state.name == "after update" -async def test_setup_entry(hass): +async def test_setup_entry(hass: HomeAssistant) -> None: """Test we can setup an entry.""" registry = mock_registry(hass) @@ -725,7 +741,7 @@ async def test_setup_entry_platform_not_ready_from_exception(hass, caplog): assert len(mock_call_later.mock_calls) == 1 -async def test_reset_cancels_retry_setup(hass): +async def test_reset_cancels_retry_setup(hass: HomeAssistant) -> None: """Test that resetting a platform will cancel scheduled a setup retry.""" async_setup_entry = Mock(side_effect=PlatformNotReady) platform = MockPlatform(async_setup_entry=async_setup_entry) @@ -747,7 +763,7 @@ async def test_reset_cancels_retry_setup(hass): assert ent_platform._async_cancel_retry_setup is None -async def test_reset_cancels_retry_setup_when_not_started(hass): +async def test_reset_cancels_retry_setup_when_not_started(hass: HomeAssistant) -> None: """Test that resetting a platform will cancel scheduled a setup retry when not yet started.""" hass.state = CoreState.starting async_setup_entry = Mock(side_effect=PlatformNotReady) @@ -772,7 +788,9 @@ async def test_reset_cancels_retry_setup_when_not_started(hass): assert ent_platform._async_cancel_retry_setup is None -async def test_stop_shutdown_cancels_retry_setup_and_interval_listener(hass): +async def test_stop_shutdown_cancels_retry_setup_and_interval_listener( + hass: HomeAssistant, +) -> None: """Test that shutdown will cancel scheduled a setup retry and interval listener.""" async_setup_entry = Mock(side_effect=PlatformNotReady) platform = MockPlatform(async_setup_entry=async_setup_entry) @@ -795,7 +813,7 @@ async def test_stop_shutdown_cancels_retry_setup_and_interval_listener(hass): assert ent_platform._async_cancel_retry_setup is None -async def test_not_fails_with_adding_empty_entities_(hass): +async def test_not_fails_with_adding_empty_entities_(hass: HomeAssistant) -> None: """Test for not fails on empty entities list.""" component = EntityComponent(_LOGGER, DOMAIN, hass) @@ -804,7 +822,7 @@ async def test_not_fails_with_adding_empty_entities_(hass): assert len(hass.states.async_entity_ids()) == 0 -async def test_entity_registry_updates_entity_id(hass): +async def test_entity_registry_updates_entity_id(hass: HomeAssistant) -> None: """Test that updates on the entity registry update platform entities.""" registry = mock_registry( hass, @@ -836,7 +854,7 @@ async def test_entity_registry_updates_entity_id(hass): assert hass.states.get("test_domain.planet") is not None -async def test_entity_registry_updates_invalid_entity_id(hass): +async def test_entity_registry_updates_invalid_entity_id(hass: HomeAssistant) -> None: """Test that we can't update to an invalid entity id.""" registry = mock_registry( hass, @@ -886,7 +904,7 @@ async def test_entity_registry_updates_invalid_entity_id(hass): assert hass.states.get("diff_domain.world") is None -async def test_device_info_called(hass): +async def test_device_info_called(hass: HomeAssistant) -> None: """Test device info is forwarded correctly.""" registry = dr.async_get(hass) via = registry.async_get_or_create( @@ -950,7 +968,7 @@ async def test_device_info_called(hass): assert device.via_device_id == via.id -async def test_device_info_not_overrides(hass): +async def test_device_info_not_overrides(hass: HomeAssistant) -> None: """Test device info is forwarded correctly.""" registry = dr.async_get(hass) device = registry.async_get_or_create( @@ -1134,7 +1152,7 @@ async def test_device_info_change_to_no_url(hass, caplog): assert device.configuration_url is None -async def test_entity_disabled_by_integration(hass): +async def test_entity_disabled_by_integration(hass: HomeAssistant) -> None: """Test entity disabled by integration.""" component = EntityComponent(_LOGGER, DOMAIN, hass, timedelta(seconds=20)) @@ -1196,7 +1214,7 @@ async def test_entity_disabled_by_device(hass: HomeAssistant): assert entry_disabled.disabled_by is er.RegistryEntryDisabler.DEVICE -async def test_entity_hidden_by_integration(hass): +async def test_entity_hidden_by_integration(hass: HomeAssistant) -> None: """Test entity hidden by integration.""" component = EntityComponent(_LOGGER, DOMAIN, hass, timedelta(seconds=20)) @@ -1215,7 +1233,7 @@ async def test_entity_hidden_by_integration(hass): assert entry_hidden.hidden_by is er.RegistryEntryHider.INTEGRATION -async def test_entity_info_added_to_entity_registry(hass): +async def test_entity_info_added_to_entity_registry(hass: HomeAssistant) -> None: """Test entity info is written to entity registry.""" component = EntityComponent(_LOGGER, DOMAIN, hass, timedelta(seconds=20)) @@ -1257,7 +1275,7 @@ async def test_entity_info_added_to_entity_registry(hass): ) -async def test_override_restored_entities(hass): +async def test_override_restored_entities(hass: HomeAssistant) -> None: """Test that we allow overriding restored entities.""" registry = mock_registry(hass) registry.async_get_or_create( @@ -1290,7 +1308,7 @@ async def test_platform_with_no_setup(hass, caplog): ) -async def test_platforms_sharing_services(hass): +async def test_platforms_sharing_services(hass: HomeAssistant) -> None: """Test platforms share services.""" entity_platform1 = MockEntityPlatform( hass, domain="mock_integration", platform_name="mock_platform", platform=None @@ -1333,7 +1351,7 @@ async def test_platforms_sharing_services(hass): assert entity2 in entities -async def test_invalid_entity_id(hass): +async def test_invalid_entity_id(hass: HomeAssistant) -> None: """Test specifying an invalid entity id.""" platform = MockEntityPlatform(hass) entity = MockEntity(entity_id="invalid_entity_id") @@ -1381,7 +1399,7 @@ async def test_setup_entry_with_entities_that_block_forever(hass, caplog): assert "test" in caplog.text -async def test_two_platforms_add_same_entity(hass): +async def test_two_platforms_add_same_entity(hass: HomeAssistant) -> None: """Test two platforms in the same domain adding an entity with the same name.""" entity_platform1 = MockEntityPlatform( hass, domain="mock_integration", platform_name="mock_platform", platform=None diff --git a/tests/helpers/test_entity_registry.py b/tests/helpers/test_entity_registry.py index 0c3ba9ceb87..37de867b57a 100644 --- a/tests/helpers/test_entity_registry.py +++ b/tests/helpers/test_entity_registry.py @@ -748,7 +748,7 @@ async def test_disabled_by_config_entry_pref(registry): assert entry2.disabled_by is er.RegistryEntryDisabler.USER -async def test_restore_states(hass): +async def test_restore_states(hass: HomeAssistant) -> None: """Test restoring states.""" hass.state = CoreState.not_running @@ -814,7 +814,7 @@ async def test_restore_states(hass): assert hass.states.get("light.all_info_set") is None -async def test_async_get_device_class_lookup(hass): +async def test_async_get_device_class_lookup(hass: HomeAssistant) -> None: """Test registry device class lookup.""" hass.state = CoreState.not_running @@ -1318,7 +1318,7 @@ def test_entity_registry_items() -> None: assert entities.get_entry(entry2.id) is None -async def test_disabled_by_str_not_allowed(hass): +async def test_disabled_by_str_not_allowed(hass: HomeAssistant) -> None: """Test we need to pass disabled by type.""" reg = er.async_get(hass) @@ -1334,7 +1334,7 @@ async def test_disabled_by_str_not_allowed(hass): ) -async def test_entity_category_str_not_allowed(hass): +async def test_entity_category_str_not_allowed(hass: HomeAssistant) -> None: """Test we need to pass entity category type.""" reg = er.async_get(hass) @@ -1350,7 +1350,7 @@ async def test_entity_category_str_not_allowed(hass): ) -async def test_hidden_by_str_not_allowed(hass): +async def test_hidden_by_str_not_allowed(hass: HomeAssistant) -> None: """Test we need to pass hidden by type.""" reg = er.async_get(hass) diff --git a/tests/helpers/test_event.py b/tests/helpers/test_event.py index 6775f0e3084..4a90c0638bc 100644 --- a/tests/helpers/test_event.py +++ b/tests/helpers/test_event.py @@ -16,7 +16,7 @@ import pytest from homeassistant.components import sun from homeassistant.const import MATCH_ALL import homeassistant.core as ha -from homeassistant.core import callback +from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import TemplateError from homeassistant.helpers.entity_registry import EVENT_ENTITY_REGISTRY_UPDATED from homeassistant.helpers.event import ( @@ -51,7 +51,7 @@ from tests.common import async_fire_time_changed, async_fire_time_changed_exact DEFAULT_TIME_ZONE = dt_util.DEFAULT_TIME_ZONE -async def test_track_point_in_time(hass): +async def test_track_point_in_time(hass: HomeAssistant) -> None: """Test track point in time.""" before_birthday = datetime(1985, 7, 9, 12, 0, 0, tzinfo=dt_util.UTC) birthday_paulus = datetime(1986, 7, 9, 12, 0, 0, tzinfo=dt_util.UTC) @@ -94,7 +94,7 @@ async def test_track_point_in_time(hass): assert len(runs) == 2 -async def test_track_point_in_time_drift_rearm(hass): +async def test_track_point_in_time_drift_rearm(hass: HomeAssistant) -> None: """Test tasks with the time rolling backwards.""" specific_runs = [] @@ -126,7 +126,7 @@ async def test_track_point_in_time_drift_rearm(hass): assert len(specific_runs) == 1 -async def test_track_state_change_from_to_state_match(hass): +async def test_track_state_change_from_to_state_match(hass: HomeAssistant) -> None: """Test track_state_change with from and to state matchers.""" from_and_to_state_runs = [] only_from_runs = [] @@ -210,7 +210,7 @@ async def test_track_state_change_from_to_state_match(hass): assert len(no_to_from_specified_runs) == 4 -async def test_track_state_change(hass): +async def test_track_state_change(hass: HomeAssistant) -> None: """Test track_state_change.""" # 2 lists to track how often our callbacks get called specific_runs = [] @@ -290,7 +290,7 @@ async def test_track_state_change(hass): assert len(wildercard_runs) == 6 -async def test_async_track_state_change_filtered(hass): +async def test_async_track_state_change_filtered(hass: HomeAssistant) -> None: """Test async_track_state_change_filtered.""" single_entity_id_tracker = [] multiple_entity_id_tracker = [] @@ -426,7 +426,7 @@ async def test_async_track_state_change_filtered(hass): track_throws.async_remove() -async def test_async_track_state_change_event(hass): +async def test_async_track_state_change_event(hass: HomeAssistant) -> None: """Test async_track_state_change_event.""" single_entity_id_tracker = [] multiple_entity_id_tracker = [] @@ -519,7 +519,9 @@ async def test_async_track_state_change_event(hass): unsub_throws() -async def test_async_track_state_change_event_with_empty_list(hass): +async def test_async_track_state_change_event_with_empty_list( + hass: HomeAssistant, +) -> None: """Test async_track_state_change_event passing an empty list of entities.""" unsub_single = async_track_state_change_event( hass, [], ha.callback(lambda event: None) @@ -532,7 +534,7 @@ async def test_async_track_state_change_event_with_empty_list(hass): unsub_single() -async def test_async_track_state_added_domain(hass): +async def test_async_track_state_added_domain(hass: HomeAssistant) -> None: """Test async_track_state_added_domain.""" single_entity_id_tracker = [] multiple_entity_id_tracker = [] @@ -614,7 +616,9 @@ async def test_async_track_state_added_domain(hass): unsub_throws() -async def test_async_track_state_added_domain_with_empty_list(hass): +async def test_async_track_state_added_domain_with_empty_list( + hass: HomeAssistant, +) -> None: """Test async_track_state_added_domain passing an empty list of domains.""" unsub_single = async_track_state_added_domain( hass, [], ha.callback(lambda event: None) @@ -627,7 +631,9 @@ async def test_async_track_state_added_domain_with_empty_list(hass): unsub_single() -async def test_async_track_state_removed_domain_with_empty_list(hass): +async def test_async_track_state_removed_domain_with_empty_list( + hass: HomeAssistant, +) -> None: """Test async_track_state_removed_domain passing an empty list of domains.""" unsub_single = async_track_state_removed_domain( hass, [], ha.callback(lambda event: None) @@ -640,7 +646,7 @@ async def test_async_track_state_removed_domain_with_empty_list(hass): unsub_single() -async def test_async_track_state_removed_domain(hass): +async def test_async_track_state_removed_domain(hass: HomeAssistant) -> None: """Test async_track_state_removed_domain.""" single_entity_id_tracker = [] multiple_entity_id_tracker = [] @@ -722,7 +728,7 @@ async def test_async_track_state_removed_domain(hass): unsub_throws() -async def test_async_track_state_removed_domain_match_all(hass): +async def test_async_track_state_removed_domain_match_all(hass: HomeAssistant) -> None: """Test async_track_state_removed_domain with a match_all.""" single_entity_id_tracker = [] match_all_entity_id_tracker = [] @@ -766,7 +772,7 @@ async def test_async_track_state_removed_domain_match_all(hass): assert len(match_all_entity_id_tracker) == 2 -async def test_track_template(hass): +async def test_track_template(hass: HomeAssistant) -> None: """Test tracking template.""" specific_runs = [] wildcard_runs = [] @@ -936,7 +942,7 @@ async def test_track_template_time_change(hass, caplog): assert calls[0] == (None, None, None) -async def test_track_template_result(hass): +async def test_track_template_result(hass: HomeAssistant) -> None: """Test tracking template.""" specific_runs = [] wildcard_runs = [] @@ -1022,7 +1028,7 @@ async def test_track_template_result(hass): assert len(wildercard_runs) == 4 -async def test_track_template_result_none(hass): +async def test_track_template_result_none(hass: HomeAssistant) -> None: """Test tracking template.""" specific_runs = [] wildcard_runs = [] @@ -1089,7 +1095,7 @@ async def test_track_template_result_none(hass): assert wildercard_runs == [(None, 5), (5, 10)] -async def test_track_template_result_super_template(hass): +async def test_track_template_result_super_template(hass: HomeAssistant) -> None: """Test tracking template with super template listening to same entity.""" specific_runs = [] specific_runs_availability = [] @@ -1233,7 +1239,9 @@ async def test_track_template_result_super_template(hass): assert len(wildercard_runs_availability) == 6 -async def test_track_template_result_super_template_initially_false(hass): +async def test_track_template_result_super_template_initially_false( + hass: HomeAssistant, +) -> None: """Test tracking template with super template listening to same entity.""" specific_runs = [] specific_runs_availability = [] @@ -1654,7 +1662,7 @@ async def test_track_template_result_super_template_2_initially_false( assert wildercard_runs == [(0, 10), (10, 35)] -async def test_track_template_result_complex(hass): +async def test_track_template_result_complex(hass: HomeAssistant) -> None: """Test tracking template.""" specific_runs = [] template_complex_str = """ @@ -1810,7 +1818,7 @@ async def test_track_template_result_complex(hass): } -async def test_track_template_result_with_wildcard(hass): +async def test_track_template_result_with_wildcard(hass: HomeAssistant) -> None: """Test tracking template with a wildcard.""" specific_runs = [] template_complex_str = r""" @@ -1851,7 +1859,7 @@ async def test_track_template_result_with_wildcard(hass): assert "cover.office_skylight=open" in specific_runs[0] -async def test_track_template_result_with_group(hass): +async def test_track_template_result_with_group(hass: HomeAssistant) -> None: """Test tracking template with a group.""" hass.states.async_set("sensor.power_1", 0) hass.states.async_set("sensor.power_2", 200.2) @@ -1924,7 +1932,7 @@ async def test_track_template_result_with_group(hass): assert specific_runs[-1] == 100.1 + 200.2 + 0 + 800.8 -async def test_track_template_result_and_conditional(hass): +async def test_track_template_result_and_conditional(hass: HomeAssistant) -> None: """Test tracking template with an and conditional.""" specific_runs = [] hass.states.async_set("light.a", "off") @@ -1987,7 +1995,9 @@ async def test_track_template_result_and_conditional(hass): assert specific_runs[2] == "on" -async def test_track_template_result_and_conditional_upper_case(hass): +async def test_track_template_result_and_conditional_upper_case( + hass: HomeAssistant, +) -> None: """Test tracking template with an and conditional with an upper case template.""" specific_runs = [] hass.states.async_set("light.a", "off") @@ -2050,7 +2060,7 @@ async def test_track_template_result_and_conditional_upper_case(hass): assert specific_runs[2] == "on" -async def test_track_template_result_iterator(hass): +async def test_track_template_result_iterator(hass: HomeAssistant) -> None: """Test tracking template.""" iterator_runs = [] @@ -2209,7 +2219,7 @@ async def test_track_template_result_errors(hass, caplog): assert isinstance(not_exist_runs[2][3], TemplateError) -async def test_static_string(hass): +async def test_static_string(hass: HomeAssistant) -> None: """Test a static string.""" template_refresh = Template("{{ 'static' }}", hass) @@ -2229,7 +2239,7 @@ async def test_static_string(hass): assert refresh_runs == ["static"] -async def test_track_template_rate_limit(hass): +async def test_track_template_rate_limit(hass: HomeAssistant) -> None: """Test template rate limit.""" template_refresh = Template("{{ states | count }}", hass) @@ -2282,7 +2292,7 @@ async def test_track_template_rate_limit(hass): assert refresh_runs == [0, 1, 2, 4] -async def test_track_template_rate_limit_super(hass): +async def test_track_template_rate_limit_super(hass: HomeAssistant) -> None: """Test template rate limit with super template.""" template_availability = Template( "{{ states('sensor.one') != 'unavailable' }}", hass @@ -2354,7 +2364,7 @@ async def test_track_template_rate_limit_super(hass): assert refresh_runs == [0, 1, 4] -async def test_track_template_rate_limit_super_2(hass): +async def test_track_template_rate_limit_super_2(hass: HomeAssistant) -> None: """Test template rate limit with rate limited super template.""" # Somewhat forced example of a rate limited template template_availability = Template("{{ states | count % 2 == 1 }}", hass) @@ -2421,7 +2431,7 @@ async def test_track_template_rate_limit_super_2(hass): assert refresh_runs == [1, 5] -async def test_track_template_rate_limit_super_3(hass): +async def test_track_template_rate_limit_super_3(hass: HomeAssistant) -> None: """Test template with rate limited super template.""" # Somewhat forced example of a rate limited template template_availability = Template("{{ states | count % 2 == 1 }}", hass) @@ -2493,7 +2503,7 @@ async def test_track_template_rate_limit_super_3(hass): assert refresh_runs == [1, 2, 5, 6, 7] -async def test_track_template_rate_limit_suppress_listener(hass): +async def test_track_template_rate_limit_suppress_listener(hass: HomeAssistant) -> None: """Test template rate limit will suppress the listener during the rate limit.""" template_refresh = Template("{{ states | count }}", hass) @@ -2588,7 +2598,7 @@ async def test_track_template_rate_limit_suppress_listener(hass): assert refresh_runs == [0, 1, 2, 4] -async def test_track_template_rate_limit_five(hass): +async def test_track_template_rate_limit_five(hass: HomeAssistant) -> None: """Test template rate limit of 5 seconds.""" template_refresh = Template("{{ states | count }}", hass) @@ -2621,7 +2631,7 @@ async def test_track_template_rate_limit_five(hass): assert refresh_runs == [0, 1] -async def test_track_template_has_default_rate_limit(hass): +async def test_track_template_has_default_rate_limit(hass: HomeAssistant) -> None: """Test template has a rate limit by default.""" hass.states.async_set("sensor.zero", "any") template_refresh = Template("{{ states | list | count }}", hass) @@ -2655,7 +2665,9 @@ async def test_track_template_has_default_rate_limit(hass): assert refresh_runs == [1, 2] -async def test_track_template_unavailable_states_has_default_rate_limit(hass): +async def test_track_template_unavailable_states_has_default_rate_limit( + hass: HomeAssistant, +) -> None: """Test template watching for unavailable states has a rate limit by default.""" hass.states.async_set("sensor.zero", "unknown") template_refresh = Template( @@ -2696,7 +2708,9 @@ async def test_track_template_unavailable_states_has_default_rate_limit(hass): info.async_remove() -async def test_specifically_referenced_entity_is_not_rate_limited(hass): +async def test_specifically_referenced_entity_is_not_rate_limited( + hass: HomeAssistant, +) -> None: """Test template rate limit of 5 seconds.""" hass.states.async_set("sensor.one", "none") @@ -2735,7 +2749,9 @@ async def test_specifically_referenced_entity_is_not_rate_limited(hass): info.async_remove() -async def test_track_two_templates_with_different_rate_limits(hass): +async def test_track_two_templates_with_different_rate_limits( + hass: HomeAssistant, +) -> None: """Test two templates with different rate limits.""" template_one = Template("{{ (states | count) + 0 }}", hass) template_five = Template("{{ states | count }}", hass) @@ -2800,7 +2816,7 @@ async def test_track_two_templates_with_different_rate_limits(hass): info.async_remove() -async def test_string(hass): +async def test_string(hass: HomeAssistant) -> None: """Test a string.""" template_refresh = Template("no_template", hass) @@ -2820,7 +2836,7 @@ async def test_string(hass): assert refresh_runs == ["no_template"] -async def test_track_template_result_refresh_cancel(hass): +async def test_track_template_result_refresh_cancel(hass: HomeAssistant) -> None: """Test cancelling and refreshing result.""" template_refresh = Template("{{states.switch.test.state == 'on' and now() }}", hass) @@ -2874,7 +2890,9 @@ async def test_track_template_result_refresh_cancel(hass): assert refresh_runs == ["duck"] -async def test_async_track_template_result_multiple_templates(hass): +async def test_async_track_template_result_multiple_templates( + hass: HomeAssistant, +) -> None: """Test tracking multiple templates.""" template_1 = Template("{{ states.switch.test.state == 'on' }}") @@ -2933,7 +2951,9 @@ async def test_async_track_template_result_multiple_templates(hass): ] -async def test_async_track_template_result_multiple_templates_mixing_domain(hass): +async def test_async_track_template_result_multiple_templates_mixing_domain( + hass: HomeAssistant, +) -> None: """Test tracking multiple templates when tracking entities and an entire domain.""" template_1 = Template("{{ states.switch.test.state == 'on' }}") @@ -3001,7 +3021,9 @@ async def test_async_track_template_result_multiple_templates_mixing_domain(hass ] -async def test_async_track_template_result_raise_on_template_error(hass): +async def test_async_track_template_result_raise_on_template_error( + hass: HomeAssistant, +) -> None: """Test that we raise as soon as we encounter a failed template.""" with pytest.raises(TemplateError): @@ -3020,7 +3042,7 @@ async def test_async_track_template_result_raise_on_template_error(hass): ) -async def test_track_template_with_time(hass): +async def test_track_template_with_time(hass: HomeAssistant) -> None: """Test tracking template with time.""" hass.states.async_set("switch.test", "on") @@ -3051,7 +3073,7 @@ async def test_track_template_with_time(hass): info.async_remove() -async def test_track_template_with_time_default(hass): +async def test_track_template_with_time_default(hass: HomeAssistant) -> None: """Test tracking template with time.""" specific_runs = [] @@ -3087,7 +3109,7 @@ async def test_track_template_with_time_default(hass): info.async_remove() -async def test_track_template_with_time_that_leaves_scope(hass): +async def test_track_template_with_time_that_leaves_scope(hass: HomeAssistant) -> None: """Test tracking template with time.""" now = dt_util.utcnow() test_time = datetime(now.year + 1, 5, 24, 11, 59, 1, 500000, tzinfo=dt_util.UTC) @@ -3160,7 +3182,9 @@ async def test_track_template_with_time_that_leaves_scope(hass): info.async_remove() -async def test_async_track_template_result_multiple_templates_mixing_listeners(hass): +async def test_async_track_template_result_multiple_templates_mixing_listeners( + hass: HomeAssistant, +) -> None: """Test tracking multiple templates with mixing listener types.""" template_1 = Template("{{ states.switch.test.state == 'on' }}") @@ -3228,7 +3252,7 @@ async def test_async_track_template_result_multiple_templates_mixing_listeners(h ] -async def test_track_same_state_simple_no_trigger(hass): +async def test_track_same_state_simple_no_trigger(hass: HomeAssistant) -> None: """Test track_same_change with no trigger.""" callback_runs = [] period = timedelta(minutes=1) @@ -3262,7 +3286,7 @@ async def test_track_same_state_simple_no_trigger(hass): assert len(callback_runs) == 0 -async def test_track_same_state_simple_trigger_check_funct(hass): +async def test_track_same_state_simple_trigger_check_funct(hass: HomeAssistant) -> None: """Test track_same_change with trigger and check funct.""" callback_runs = [] check_func = [] @@ -3300,7 +3324,7 @@ async def test_track_same_state_simple_trigger_check_funct(hass): assert len(callback_runs) == 1 -async def test_track_time_interval(hass): +async def test_track_time_interval(hass: HomeAssistant) -> None: """Test tracking time interval.""" specific_runs = [] @@ -3328,7 +3352,7 @@ async def test_track_time_interval(hass): assert len(specific_runs) == 2 -async def test_track_sunrise(hass): +async def test_track_sunrise(hass: HomeAssistant) -> None: """Test track the sunrise.""" latitude = 32.87336 longitude = 117.22743 @@ -3396,7 +3420,7 @@ async def test_track_sunrise(hass): assert len(offset_runs) == 1 -async def test_track_sunrise_update_location(hass): +async def test_track_sunrise_update_location(hass: HomeAssistant) -> None: """Test track the sunrise.""" # Setup sun component hass.config.latitude = 32.87336 @@ -3465,7 +3489,7 @@ async def test_track_sunrise_update_location(hass): assert len(runs) == 2 -async def test_track_sunset(hass): +async def test_track_sunset(hass: HomeAssistant) -> None: """Test track the sunset.""" latitude = 32.87336 longitude = 117.22743 @@ -3531,7 +3555,7 @@ async def test_track_sunset(hass): assert len(offset_runs) == 1 -async def test_async_track_time_change(hass): +async def test_async_track_time_change(hass: HomeAssistant) -> None: """Test tracking time change.""" wildcard_runs = [] specific_runs = [] @@ -3584,7 +3608,7 @@ async def test_async_track_time_change(hass): assert len(wildcard_runs) == 3 -async def test_periodic_task_minute(hass): +async def test_periodic_task_minute(hass: HomeAssistant) -> None: """Test periodic tasks per minute.""" specific_runs = [] @@ -3628,7 +3652,7 @@ async def test_periodic_task_minute(hass): assert len(specific_runs) == 2 -async def test_periodic_task_hour(hass): +async def test_periodic_task_hour(hass: HomeAssistant) -> None: """Test periodic tasks per hour.""" specific_runs = [] @@ -3688,7 +3712,7 @@ async def test_periodic_task_hour(hass): assert len(specific_runs) == 3 -async def test_periodic_task_wrong_input(hass): +async def test_periodic_task_wrong_input(hass: HomeAssistant) -> None: """Test periodic tasks with wrong input.""" specific_runs = [] @@ -3706,7 +3730,7 @@ async def test_periodic_task_wrong_input(hass): assert len(specific_runs) == 0 -async def test_periodic_task_clock_rollback(hass): +async def test_periodic_task_clock_rollback(hass: HomeAssistant) -> None: """Test periodic tasks with the time rolling backwards.""" specific_runs = [] @@ -3770,7 +3794,7 @@ async def test_periodic_task_clock_rollback(hass): assert len(specific_runs) == 2 -async def test_periodic_task_duplicate_time(hass): +async def test_periodic_task_duplicate_time(hass: HomeAssistant) -> None: """Test periodic tasks not triggering on duplicate time.""" specific_runs = [] @@ -4048,7 +4072,7 @@ async def test_periodic_task_leaving_dst_2(hass, freezer): unsub() -async def test_call_later(hass): +async def test_call_later(hass: HomeAssistant) -> None: """Test calling an action later.""" future = asyncio.get_running_loop().create_future() delay = 5 @@ -4068,7 +4092,7 @@ async def test_call_later(hass): assert await future, "callback was called but the delay was wrong" -async def test_async_call_later(hass): +async def test_async_call_later(hass: HomeAssistant) -> None: """Test calling an action later.""" future = asyncio.get_running_loop().create_future() delay = 5 @@ -4090,7 +4114,7 @@ async def test_async_call_later(hass): remove() -async def test_async_call_later_timedelta(hass): +async def test_async_call_later_timedelta(hass: HomeAssistant) -> None: """Test calling an action later with a timedelta.""" future = asyncio.get_running_loop().create_future() delay = 5 @@ -4112,7 +4136,7 @@ async def test_async_call_later_timedelta(hass): remove() -async def test_async_call_later_cancel(hass): +async def test_async_call_later_cancel(hass: HomeAssistant) -> None: """Test canceling a call_later action.""" future = asyncio.get_running_loop().create_future() delay = 0.25 @@ -4137,7 +4161,9 @@ async def test_async_call_later_cancel(hass): assert await future, "callback not canceled" -async def test_track_state_change_event_chain_multple_entity(hass): +async def test_track_state_change_event_chain_multple_entity( + hass: HomeAssistant, +) -> None: """Test that adding a new state tracker inside a tracker does not fire right away.""" tracker_called = [] chained_tracker_called = [] @@ -4189,7 +4215,9 @@ async def test_track_state_change_event_chain_multple_entity(hass): assert len(chained_tracker_unsub) == 3 -async def test_track_state_change_event_chain_single_entity(hass): +async def test_track_state_change_event_chain_single_entity( + hass: HomeAssistant, +) -> None: """Test that adding a new state tracker inside a tracker does not fire right away.""" tracker_called = [] chained_tracker_called = [] @@ -4238,7 +4266,7 @@ async def test_track_state_change_event_chain_single_entity(hass): assert len(chained_tracker_unsub) == 2 -async def test_track_point_in_utc_time_cancel(hass): +async def test_track_point_in_utc_time_cancel(hass: HomeAssistant) -> None: """Test cancel of async track point in time.""" times = [] @@ -4270,7 +4298,7 @@ async def test_track_point_in_utc_time_cancel(hass): assert times[0].tzinfo == dt_util.UTC -async def test_async_track_point_in_time_cancel(hass): +async def test_async_track_point_in_time_cancel(hass: HomeAssistant) -> None: """Test cancel of async track point in time.""" times = [] @@ -4298,7 +4326,7 @@ async def test_async_track_point_in_time_cancel(hass): assert "US/Hawaii" in str(times[0].tzinfo) -async def test_async_track_entity_registry_updated_event(hass): +async def test_async_track_entity_registry_updated_event(hass: HomeAssistant) -> None: """Test tracking entity registry updates for an entity_id.""" entity_id = "switch.puppy_feeder" @@ -4395,7 +4423,9 @@ async def test_async_track_entity_registry_updated_event_with_a_callback_that_th assert event_data[0] == {"action": "create", "entity_id": "switch.puppy_feeder"} -async def test_async_track_entity_registry_updated_event_with_empty_list(hass): +async def test_async_track_entity_registry_updated_event_with_empty_list( + hass: HomeAssistant, +) -> None: """Test async_track_entity_registry_updated_event passing an empty list of entities.""" unsub_single = async_track_entity_registry_updated_event( hass, [], ha.callback(lambda event: None) diff --git a/tests/helpers/test_httpx_client.py b/tests/helpers/test_httpx_client.py index eabc3f43d2d..eb6b971f132 100644 --- a/tests/helpers/test_httpx_client.py +++ b/tests/helpers/test_httpx_client.py @@ -5,25 +5,27 @@ from unittest.mock import Mock, patch import httpx import pytest -from homeassistant.core import EVENT_HOMEASSISTANT_CLOSE +from homeassistant.core import EVENT_HOMEASSISTANT_CLOSE, HomeAssistant import homeassistant.helpers.httpx_client as client -async def test_get_async_client_with_ssl(hass): +async def test_get_async_client_with_ssl(hass: HomeAssistant) -> None: """Test init async client with ssl.""" client.get_async_client(hass) assert isinstance(hass.data[client.DATA_ASYNC_CLIENT], httpx.AsyncClient) -async def test_get_async_client_without_ssl(hass): +async def test_get_async_client_without_ssl(hass: HomeAssistant) -> None: """Test init async client without ssl.""" client.get_async_client(hass, verify_ssl=False) assert isinstance(hass.data[client.DATA_ASYNC_CLIENT_NOVERIFY], httpx.AsyncClient) -async def test_create_async_httpx_client_with_ssl_and_cookies(hass): +async def test_create_async_httpx_client_with_ssl_and_cookies( + hass: HomeAssistant, +) -> None: """Test init async client with ssl and cookies.""" client.get_async_client(hass) @@ -32,7 +34,9 @@ async def test_create_async_httpx_client_with_ssl_and_cookies(hass): assert hass.data[client.DATA_ASYNC_CLIENT] != httpx_client -async def test_create_async_httpx_client_without_ssl_and_cookies(hass): +async def test_create_async_httpx_client_without_ssl_and_cookies( + hass: HomeAssistant, +) -> None: """Test init async client without ssl and cookies.""" client.get_async_client(hass, verify_ssl=False) @@ -43,7 +47,7 @@ async def test_create_async_httpx_client_without_ssl_and_cookies(hass): assert hass.data[client.DATA_ASYNC_CLIENT_NOVERIFY] != httpx_client -async def test_get_async_client_cleanup(hass): +async def test_get_async_client_cleanup(hass: HomeAssistant) -> None: """Test init async client with ssl.""" client.get_async_client(hass) @@ -55,7 +59,7 @@ async def test_get_async_client_cleanup(hass): assert hass.data[client.DATA_ASYNC_CLIENT].is_closed -async def test_get_async_client_cleanup_without_ssl(hass): +async def test_get_async_client_cleanup_without_ssl(hass: HomeAssistant) -> None: """Test init async client without ssl.""" client.get_async_client(hass, verify_ssl=False) @@ -67,7 +71,7 @@ async def test_get_async_client_cleanup_without_ssl(hass): assert hass.data[client.DATA_ASYNC_CLIENT_NOVERIFY].is_closed -async def test_get_async_client_patched_close(hass): +async def test_get_async_client_patched_close(hass: HomeAssistant) -> None: """Test closing the async client does not work.""" with patch("httpx.AsyncClient.aclose") as mock_aclose: @@ -80,7 +84,7 @@ async def test_get_async_client_patched_close(hass): assert mock_aclose.call_count == 0 -async def test_get_async_client_context_manager(hass): +async def test_get_async_client_context_manager(hass: HomeAssistant) -> None: """Test using the async client with a context manager does not close the session.""" with patch("httpx.AsyncClient.aclose") as mock_aclose: diff --git a/tests/helpers/test_integration_platform.py b/tests/helpers/test_integration_platform.py index 584af602062..5848c6f9541 100644 --- a/tests/helpers/test_integration_platform.py +++ b/tests/helpers/test_integration_platform.py @@ -1,6 +1,7 @@ """Test integration platform helpers.""" from unittest.mock import Mock +from homeassistant.core import HomeAssistant from homeassistant.helpers.integration_platform import ( async_process_integration_platform_for_component, async_process_integration_platforms, @@ -10,7 +11,7 @@ from homeassistant.setup import ATTR_COMPONENT, EVENT_COMPONENT_LOADED from tests.common import mock_platform -async def test_process_integration_platforms(hass): +async def test_process_integration_platforms(hass: HomeAssistant) -> None: """Test processing integrations.""" loaded_platform = Mock() mock_platform(hass, "loaded.platform_to_check", loaded_platform) @@ -45,7 +46,7 @@ async def test_process_integration_platforms(hass): assert len(processed) == 2 -async def test_process_integration_platforms_none_loaded(hass): +async def test_process_integration_platforms_none_loaded(hass: HomeAssistant) -> None: """Test processing integrations with none loaded.""" # Verify we can call async_process_integration_platform_for_component # when there are none loaded and it does not throw diff --git a/tests/helpers/test_intent.py b/tests/helpers/test_intent.py index a8f75c64435..0932433baa5 100644 --- a/tests/helpers/test_intent.py +++ b/tests/helpers/test_intent.py @@ -5,7 +5,7 @@ import voluptuous as vol from homeassistant.components.switch import SwitchDeviceClass from homeassistant.const import ATTR_FRIENDLY_NAME -from homeassistant.core import State +from homeassistant.core import HomeAssistant, State from homeassistant.helpers import ( area_registry, config_validation as cv, @@ -23,7 +23,7 @@ class MockIntentHandler(intent.IntentHandler): self.slot_schema = slot_schema -async def test_async_match_states(hass): +async def test_async_match_states(hass: HomeAssistant) -> None: """Test async_match_state helper.""" areas = area_registry.async_get(hass) area_kitchen = areas.async_get_or_create("kitchen") @@ -101,7 +101,7 @@ async def test_async_match_states(hass): ) == [state2] -async def test_match_device_area(hass): +async def test_match_device_area(hass: HomeAssistant) -> None: """Test async_match_state with a device in an area.""" areas = area_registry.async_get(hass) area_kitchen = areas.async_get_or_create("kitchen") diff --git a/tests/helpers/test_location.py b/tests/helpers/test_location.py index 72e4720023b..435df26b94c 100644 --- a/tests/helpers/test_location.py +++ b/tests/helpers/test_location.py @@ -45,7 +45,7 @@ def test_closest_returns_closest() -> None: assert state == location.closest(123.45, 123.45, [state, state2]) -async def test_coordinates_function_as_attributes(hass): +async def test_coordinates_function_as_attributes(hass: HomeAssistant) -> None: """Test coordinates function.""" hass.states.async_set( "test.object", "happy", {"latitude": 32.87336, "longitude": -117.22943} @@ -53,13 +53,13 @@ async def test_coordinates_function_as_attributes(hass): assert location.find_coordinates(hass, "test.object") == "32.87336,-117.22943" -async def test_coordinates_function_as_state(hass): +async def test_coordinates_function_as_state(hass: HomeAssistant) -> None: """Test coordinates function.""" hass.states.async_set("test.object", "32.87336,-117.22943") assert location.find_coordinates(hass, "test.object") == "32.87336,-117.22943" -async def test_coordinates_function_device_tracker_in_zone(hass): +async def test_coordinates_function_device_tracker_in_zone(hass: HomeAssistant) -> None: """Test coordinates function.""" hass.states.async_set( "zone.home", @@ -73,7 +73,7 @@ async def test_coordinates_function_device_tracker_in_zone(hass): ) -async def test_coordinates_function_zone_friendly_name(hass): +async def test_coordinates_function_zone_friendly_name(hass: HomeAssistant) -> None: """Test coordinates function.""" hass.states.async_set( "zone.home", @@ -88,7 +88,9 @@ async def test_coordinates_function_zone_friendly_name(hass): assert location.find_coordinates(hass, "my_home") == "32.87336,-117.22943" -async def test_coordinates_function_device_tracker_from_input_select(hass): +async def test_coordinates_function_device_tracker_from_input_select( + hass: HomeAssistant, +) -> None: """Test coordinates function.""" hass.states.async_set( "input_select.select", @@ -111,7 +113,9 @@ def test_coordinates_function_returns_none_on_recursion(hass: HomeAssistant) -> assert location.find_coordinates(hass, "test.first") is None -async def test_coordinates_function_returns_state_if_no_coords(hass): +async def test_coordinates_function_returns_state_if_no_coords( + hass: HomeAssistant, +) -> None: """Test test_coordinates function.""" hass.states.async_set( "test.object", diff --git a/tests/helpers/test_network.py b/tests/helpers/test_network.py index 13f1a3cdd78..1606842b752 100644 --- a/tests/helpers/test_network.py +++ b/tests/helpers/test_network.py @@ -674,7 +674,7 @@ async def test_is_internal_request(hass: HomeAssistant, mock_current_request): assert is_internal_request(hass), mock_current_request.return_value.url -async def test_is_hass_url(hass): +async def test_is_hass_url(hass: HomeAssistant) -> None: """Test is_hass_url.""" assert hass.config.api is None assert hass.config.internal_url is None @@ -721,7 +721,7 @@ async def test_is_hass_url(hass): assert is_hass_url(hass, "http://example.nabu.casa") is False -async def test_is_hass_url_addon_url(hass): +async def test_is_hass_url_addon_url(hass: HomeAssistant) -> None: """Test is_hass_url with a supervisor network URL.""" assert is_hass_url(hass, "http://homeassistant:8123") is False @@ -741,7 +741,7 @@ async def test_is_hass_url_addon_url(hass): assert is_hass_url(hass, "https://homeassistant:8123") -async def test_get_supervisor_network_url(hass): +async def test_get_supervisor_network_url(hass: HomeAssistant) -> None: """Test get_supervisor_network_url.""" assert get_supervisor_network_url(hass) is None diff --git a/tests/helpers/test_ratelimit.py b/tests/helpers/test_ratelimit.py index c34de9586dd..e7fa639261b 100644 --- a/tests/helpers/test_ratelimit.py +++ b/tests/helpers/test_ratelimit.py @@ -2,12 +2,12 @@ import asyncio from datetime import timedelta -from homeassistant.core import callback +from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import ratelimit from homeassistant.util import dt as dt_util -async def test_hit(hass): +async def test_hit(hass: HomeAssistant) -> None: """Test hitting the rate limit.""" refresh_called = False @@ -44,7 +44,7 @@ async def test_hit(hass): rate_limiter.async_remove() -async def test_miss(hass): +async def test_miss(hass: HomeAssistant) -> None: """Test missing the rate limit.""" refresh_called = False @@ -76,7 +76,7 @@ async def test_miss(hass): rate_limiter.async_remove() -async def test_no_limit(hass): +async def test_no_limit(hass: HomeAssistant) -> None: """Test async_schedule_action always return None when there is no rate limit.""" refresh_called = False diff --git a/tests/helpers/test_reload.py b/tests/helpers/test_reload.py index b99951493ca..fdc8ef31e1b 100644 --- a/tests/helpers/test_reload.py +++ b/tests/helpers/test_reload.py @@ -6,6 +6,7 @@ import pytest from homeassistant import config from homeassistant.const import SERVICE_RELOAD +from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.entity_platform import async_get_platforms from homeassistant.helpers.reload import ( @@ -29,7 +30,7 @@ DOMAIN = "test_domain" PLATFORM = "test_platform" -async def test_reload_platform(hass): +async def test_reload_platform(hass: HomeAssistant) -> None: """Test the polling of only updated entities.""" component_setup = Mock(return_value=True) @@ -69,7 +70,7 @@ async def test_reload_platform(hass): assert not async_get_platform_without_config_entry(hass, PLATFORM, DOMAIN) -async def test_setup_reload_service(hass): +async def test_setup_reload_service(hass: HomeAssistant) -> None: """Test setting up a reload service.""" component_setup = Mock(return_value=True) @@ -108,7 +109,9 @@ async def test_setup_reload_service(hass): assert len(setup_called) == 2 -async def test_setup_reload_service_when_async_process_component_config_fails(hass): +async def test_setup_reload_service_when_async_process_component_config_fails( + hass: HomeAssistant, +) -> None: """Test setting up a reload service with the config processing failing.""" component_setup = Mock(return_value=True) @@ -198,7 +201,7 @@ async def test_setup_reload_service_with_platform_that_provides_async_reset_plat assert len(async_reset_platform_called) == 1 -async def test_async_integration_yaml_config(hass): +async def test_async_integration_yaml_config(hass: HomeAssistant) -> None: """Test loading yaml config for an integration.""" mock_integration(hass, MockModule(DOMAIN)) @@ -209,7 +212,7 @@ async def test_async_integration_yaml_config(hass): assert processed_config == {DOMAIN: [{"name": "one"}, {"name": "two"}]} -async def test_async_integration_missing_yaml_config(hass): +async def test_async_integration_missing_yaml_config(hass: HomeAssistant) -> None: """Test loading missing yaml config for an integration.""" mock_integration(hass, MockModule(DOMAIN)) diff --git a/tests/helpers/test_restore_state.py b/tests/helpers/test_restore_state.py index efe951342fa..fdd3e4b8e18 100644 --- a/tests/helpers/test_restore_state.py +++ b/tests/helpers/test_restore_state.py @@ -3,7 +3,7 @@ from datetime import datetime, timedelta from unittest.mock import patch from homeassistant.const import EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP -from homeassistant.core import CoreState, State +from homeassistant.core import CoreState, HomeAssistant, State from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity import Entity from homeassistant.helpers.restore_state import ( @@ -18,7 +18,7 @@ from homeassistant.util import dt as dt_util from tests.common import async_fire_time_changed -async def test_caching_data(hass): +async def test_caching_data(hass: HomeAssistant) -> None: """Test that we cache data.""" now = dt_util.utcnow() stored_states = [ @@ -52,7 +52,7 @@ async def test_caching_data(hass): assert mock_write_data.called -async def test_periodic_write(hass): +async def test_periodic_write(hass: HomeAssistant) -> None: """Test that we write periodiclly but not after stop.""" data = await RestoreStateData.async_get_instance(hass) await hass.async_block_till_done() @@ -98,7 +98,7 @@ async def test_periodic_write(hass): assert not mock_write_data.called -async def test_save_persistent_states(hass): +async def test_save_persistent_states(hass: HomeAssistant) -> None: """Test that we cancel the currently running job, save the data, and verify the perdiodic job continues.""" data = await RestoreStateData.async_get_instance(hass) await hass.async_block_till_done() @@ -154,7 +154,7 @@ async def test_save_persistent_states(hass): assert mock_write_data.called -async def test_hass_starting(hass): +async def test_hass_starting(hass: HomeAssistant) -> None: """Test that we cache data.""" hass.state = CoreState.starting @@ -203,7 +203,7 @@ async def test_hass_starting(hass): assert mock_write_data.called -async def test_dump_data(hass): +async def test_dump_data(hass: HomeAssistant) -> None: """Test that we cache data.""" states = [ State("input_boolean.b0", "on"), @@ -278,7 +278,7 @@ async def test_dump_data(hass): assert written_states[1]["state"]["state"] == "off" -async def test_dump_error(hass): +async def test_dump_error(hass: HomeAssistant) -> None: """Test that we cache data.""" states = [ State("input_boolean.b0", "on"), @@ -307,7 +307,7 @@ async def test_dump_error(hass): assert mock_write_data.called -async def test_load_error(hass): +async def test_load_error(hass: HomeAssistant) -> None: """Test that we cache data.""" entity = RestoreEntity() entity.hass = hass @@ -322,7 +322,7 @@ async def test_load_error(hass): assert state is None -async def test_state_saved_on_remove(hass): +async def test_state_saved_on_remove(hass: HomeAssistant) -> None: """Test that we save entity state on removal.""" entity = RestoreEntity() entity.hass = hass diff --git a/tests/helpers/test_script.py b/tests/helpers/test_script.py index f774a26bbc6..cd6cba56ba5 100644 --- a/tests/helpers/test_script.py +++ b/tests/helpers/test_script.py @@ -177,7 +177,7 @@ async def test_firing_event_basic(hass, caplog): ) -async def test_firing_event_template(hass): +async def test_firing_event_template(hass: HomeAssistant) -> None: """Test the firing of events.""" event = "test_event" context = Context() @@ -276,7 +276,7 @@ async def test_calling_service_basic(hass, caplog): ) -async def test_calling_service_template(hass): +async def test_calling_service_template(hass: HomeAssistant) -> None: """Test the calling of a service.""" context = Context() calls = async_mock_service(hass, "test", "script") @@ -329,7 +329,7 @@ async def test_calling_service_template(hass): ) -async def test_data_template_with_templated_key(hass): +async def test_data_template_with_templated_key(hass: HomeAssistant) -> None: """Test the calling of a service with a data_template with a templated key.""" context = Context() calls = async_mock_service(hass, "test", "script") @@ -368,7 +368,7 @@ async def test_data_template_with_templated_key(hass): ) -async def test_multiple_runs_no_wait(hass): +async def test_multiple_runs_no_wait(hass: HomeAssistant) -> None: """Test multiple runs with no wait in script.""" logger = logging.getLogger("TEST") calls = [] @@ -516,7 +516,7 @@ async def test_stop_no_wait(hass, count): assert len(events) == 0 -async def test_delay_basic(hass): +async def test_delay_basic(hass: HomeAssistant) -> None: """Test the delay.""" delay_alias = "delay step" sequence = cv.SCRIPT_SCHEMA({"delay": {"seconds": 5}, "alias": delay_alias}) @@ -546,7 +546,7 @@ async def test_delay_basic(hass): ) -async def test_multiple_runs_delay(hass): +async def test_multiple_runs_delay(hass: HomeAssistant) -> None: """Test multiple runs with delay in script.""" event = "test_event" events = async_capture_events(hass, event) @@ -589,7 +589,7 @@ async def test_multiple_runs_delay(hass): assert events[-1].data["value"] == 2 -async def test_delay_template_ok(hass): +async def test_delay_template_ok(hass: HomeAssistant) -> None: """Test the delay as a template.""" sequence = cv.SCRIPT_SCHEMA({"delay": "00:00:{{ 5 }}"}) script_obj = script.Script(hass, sequence, "Test Name", "test_domain") @@ -651,7 +651,7 @@ async def test_delay_template_invalid(hass, caplog): ) -async def test_delay_template_complex_ok(hass): +async def test_delay_template_complex_ok(hass: HomeAssistant) -> None: """Test the delay with a working complex template.""" sequence = cv.SCRIPT_SCHEMA({"delay": {"seconds": "{{ 5 }}"}}) script_obj = script.Script(hass, sequence, "Test Name", "test_domain") @@ -712,7 +712,7 @@ async def test_delay_template_complex_invalid(hass, caplog): ) -async def test_cancel_delay(hass): +async def test_cancel_delay(hass: HomeAssistant) -> None: """Test the cancelling while the delay is present.""" event = "test_event" events = async_capture_events(hass, event) @@ -808,7 +808,7 @@ async def test_wait_basic(hass, action_type): ) -async def test_wait_for_trigger_variables(hass): +async def test_wait_for_trigger_variables(hass: HomeAssistant) -> None: """Test variables are passed to wait_for_trigger action.""" context = Context() wait_alias = "wait step" @@ -1014,7 +1014,7 @@ async def test_cancel_wait(hass, action_type): ) -async def test_wait_template_not_schedule(hass): +async def test_wait_template_not_schedule(hass: HomeAssistant) -> None: """Test the wait template with correct condition.""" event = "test_event" events = async_capture_events(hass, event) @@ -1180,7 +1180,7 @@ async def test_wait_continue_on_timeout( assert_action_trace(expected_trace, expected_script_execution) -async def test_wait_template_variables_in(hass): +async def test_wait_template_variables_in(hass: HomeAssistant) -> None: """Test the wait template with input variables.""" sequence = cv.SCRIPT_SCHEMA({"wait_template": "{{ is_state(data, 'off') }}"}) script_obj = script.Script(hass, sequence, "Test Name", "test_domain") @@ -1210,7 +1210,7 @@ async def test_wait_template_variables_in(hass): ) -async def test_wait_template_with_utcnow(hass): +async def test_wait_template_with_utcnow(hass: HomeAssistant) -> None: """Test the wait template with utcnow.""" sequence = cv.SCRIPT_SCHEMA({"wait_template": "{{ utcnow().hour == 12 }}"}) script_obj = script.Script(hass, sequence, "Test Name", "test_domain") @@ -1241,7 +1241,7 @@ async def test_wait_template_with_utcnow(hass): ) -async def test_wait_template_with_utcnow_no_match(hass): +async def test_wait_template_with_utcnow_no_match(hass: HomeAssistant) -> None: """Test the wait template with utcnow that does not match.""" sequence = cv.SCRIPT_SCHEMA({"wait_template": "{{ utcnow().hour == 12 }}"}) script_obj = script.Script(hass, sequence, "Test Name", "test_domain") @@ -1745,7 +1745,7 @@ async def test_condition_created_once(async_from_config, hass): assert len(script_obj._config_cache) == 1 -async def test_condition_all_cached(hass): +async def test_condition_all_cached(hass: HomeAssistant) -> None: """Test that multiple conditions get cached.""" sequence = cv.SCRIPT_SCHEMA( [ @@ -3317,7 +3317,7 @@ async def test_parallel_error( assert_action_trace(expected_trace, expected_script_execution="error") -async def test_last_triggered(hass): +async def test_last_triggered(hass: HomeAssistant) -> None: """Test the last_triggered.""" event = "test_event" sequence = cv.SCRIPT_SCHEMA({"event": event}) @@ -3333,7 +3333,7 @@ async def test_last_triggered(hass): assert script_obj.last_triggered == time -async def test_propagate_error_service_not_found(hass): +async def test_propagate_error_service_not_found(hass: HomeAssistant) -> None: """Test that a script aborts when a service is not found.""" event = "test_event" events = async_capture_events(hass, event) @@ -3366,7 +3366,7 @@ async def test_propagate_error_service_not_found(hass): assert_action_trace(expected_trace, expected_script_execution="error") -async def test_propagate_error_invalid_service_data(hass): +async def test_propagate_error_invalid_service_data(hass: HomeAssistant) -> None: """Test that a script aborts when we send invalid service data.""" event = "test_event" events = async_capture_events(hass, event) @@ -3403,7 +3403,7 @@ async def test_propagate_error_invalid_service_data(hass): assert_action_trace(expected_trace, expected_script_execution="error") -async def test_propagate_error_service_exception(hass): +async def test_propagate_error_service_exception(hass: HomeAssistant) -> None: """Test that a script aborts when a service throws an exception.""" event = "test_event" events = async_capture_events(hass, event) @@ -3444,7 +3444,7 @@ async def test_propagate_error_service_exception(hass): assert_action_trace(expected_trace, expected_script_execution="error") -async def test_referenced_areas(hass): +async def test_referenced_areas(hass: HomeAssistant) -> None: """Test referenced areas.""" script_obj = script.Script( hass, @@ -3546,7 +3546,7 @@ async def test_referenced_areas(hass): assert script_obj.referenced_areas is script_obj.referenced_areas -async def test_referenced_entities(hass): +async def test_referenced_entities(hass: HomeAssistant) -> None: """Test referenced entities.""" script_obj = script.Script( hass, @@ -3667,7 +3667,7 @@ async def test_referenced_entities(hass): assert script_obj.referenced_entities is script_obj.referenced_entities -async def test_referenced_devices(hass): +async def test_referenced_devices(hass: HomeAssistant) -> None: """Test referenced entities.""" script_obj = script.Script( hass, @@ -3952,7 +3952,7 @@ async def test_script_mode_2(hass, caplog, script_mode, messages, last_events): assert events[idx].data["value"] == value -async def test_script_mode_queued(hass): +async def test_script_mode_queued(hass: HomeAssistant) -> None: """Test overlapping runs with script_mode = 'queued' & max_runs > 1.""" event = "test_event" events = async_capture_events(hass, event) @@ -4049,7 +4049,7 @@ async def test_script_mode_queued(hass): assert events[3].data["value"] == 2 -async def test_script_mode_queued_cancel(hass): +async def test_script_mode_queued_cancel(hass: HomeAssistant) -> None: """Test canceling with a queued run.""" script_obj = script.Script( hass, @@ -4091,7 +4091,7 @@ async def test_script_mode_queued_cancel(hass): raise -async def test_script_mode_queued_stop(hass): +async def test_script_mode_queued_stop(hass: HomeAssistant) -> None: """Test stopping with a queued run.""" script_obj = script.Script( hass, @@ -4350,7 +4350,7 @@ async def test_set_redefines_variable(hass, caplog): assert_action_trace(expected_trace) -async def test_validate_action_config(hass): +async def test_validate_action_config(hass: HomeAssistant) -> None: """Validate action config.""" def templated_device_action(message): @@ -4456,7 +4456,7 @@ async def test_validate_action_config(hass): assert isinstance(device_action["message"], template.Template) -async def test_embedded_wait_for_trigger_in_automation(hass): +async def test_embedded_wait_for_trigger_in_automation(hass: HomeAssistant) -> None: """Test an embedded wait for trigger.""" assert await async_setup_component( hass, @@ -4515,7 +4515,7 @@ async def test_embedded_wait_for_trigger_in_automation(hass): assert len(mock_calls) == 1 -async def test_breakpoints_1(hass): +async def test_breakpoints_1(hass: HomeAssistant) -> None: """Test setting a breakpoint halts execution, and execution can be resumed.""" event = "test_event" events = async_capture_events(hass, event) @@ -4610,7 +4610,7 @@ async def test_breakpoints_1(hass): assert events[-1].data["value"] == 7 -async def test_breakpoints_2(hass): +async def test_breakpoints_2(hass: HomeAssistant) -> None: """Test setting a breakpoint halts execution, and execution can be aborted.""" event = "test_event" events = async_capture_events(hass, event) @@ -4677,7 +4677,7 @@ async def test_breakpoints_2(hass): assert len(events) == 1 -async def test_platform_async_validate_action_config(hass): +async def test_platform_async_validate_action_config(hass: HomeAssistant) -> None: """Test platform.async_validate_action_config will be called if it exists.""" config = {CONF_DEVICE_ID: "test", CONF_DOMAIN: "test"} with patch( diff --git a/tests/helpers/test_script_variables.py b/tests/helpers/test_script_variables.py index 61a6209d49c..99aae08587e 100644 --- a/tests/helpers/test_script_variables.py +++ b/tests/helpers/test_script_variables.py @@ -1,6 +1,7 @@ """Test script variables.""" import pytest +from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, template @@ -46,14 +47,14 @@ async def test_static_vars_run_args_no_default() -> None: assert orig == orig_copy -async def test_template_vars(hass): +async def test_template_vars(hass: HomeAssistant) -> None: """Test template vars.""" var = cv.SCRIPT_VARIABLES_SCHEMA({"hello": "{{ 1 + 1 }}"}) rendered = var.async_render(hass, None) assert rendered == {"hello": 2} -async def test_template_vars_run_args(hass): +async def test_template_vars_run_args(hass: HomeAssistant) -> None: """Test template vars.""" var = cv.SCRIPT_VARIABLES_SCHEMA( { @@ -75,14 +76,14 @@ async def test_template_vars_run_args(hass): } -async def test_template_vars_no_default(hass): +async def test_template_vars_no_default(hass: HomeAssistant) -> None: """Test template vars.""" var = cv.SCRIPT_VARIABLES_SCHEMA({"hello": "{{ 1 + 1 }}"}) rendered = var.async_render(hass, None, render_as_defaults=False) assert rendered == {"hello": 2} -async def test_template_vars_run_args_no_default(hass): +async def test_template_vars_run_args_no_default(hass: HomeAssistant) -> None: """Test template vars.""" var = cv.SCRIPT_VARIABLES_SCHEMA( { @@ -105,7 +106,7 @@ async def test_template_vars_run_args_no_default(hass): } -async def test_template_vars_error(hass): +async def test_template_vars_error(hass: HomeAssistant) -> None: """Test template vars.""" var = cv.SCRIPT_VARIABLES_SCHEMA({"hello": "{{ canont.work }}"}) with pytest.raises(template.TemplateError): diff --git a/tests/helpers/test_service.py b/tests/helpers/test_service.py index f109e09fee2..8a6109ed72b 100644 --- a/tests/helpers/test_service.py +++ b/tests/helpers/test_service.py @@ -8,7 +8,7 @@ import pytest import voluptuous as vol # To prevent circular import when running just this file -from homeassistant import core as ha, exceptions +from homeassistant import exceptions from homeassistant.auth.permissions import PolicyPermissions import homeassistant.components # noqa: F401, pylint: disable=unused-import from homeassistant.const import ( @@ -18,6 +18,7 @@ from homeassistant.const import ( STATE_OFF, STATE_ON, ) +from homeassistant.core import Context, HomeAssistant, ServiceCall from homeassistant.helpers import ( device_registry as dev_reg, entity_registry as ent_reg, @@ -401,7 +402,7 @@ class TestServiceHelpers(unittest.TestCase): assert mock_log.call_count == 3 -async def test_service_call_entry_id(hass): +async def test_service_call_entry_id(hass: HomeAssistant) -> None: """Test service call with entity specified by entity registry ID.""" registry = ent_reg.async_get(hass) calls = async_mock_service(hass, "test_domain", "test_service") @@ -438,7 +439,7 @@ async def test_service_call_all_none(hass, target): assert dict(calls[0].data) == {"entity_id": target} -async def test_extract_entity_ids(hass): +async def test_extract_entity_ids(hass: HomeAssistant) -> None: """Test extract_entity_ids method.""" hass.states.async_set("light.Bowl", STATE_ON) hass.states.async_set("light.Ceiling", STATE_OFF) @@ -450,11 +451,11 @@ async def test_extract_entity_ids(hass): hass, "test", ["light.Ceiling", "light.Kitchen"] ) - call = ha.ServiceCall("light", "turn_on", {ATTR_ENTITY_ID: "light.Bowl"}) + call = ServiceCall("light", "turn_on", {ATTR_ENTITY_ID: "light.Bowl"}) assert {"light.bowl"} == await service.async_extract_entity_ids(hass, call) - call = ha.ServiceCall("light", "turn_on", {ATTR_ENTITY_ID: "group.test"}) + call = ServiceCall("light", "turn_on", {ATTR_ENTITY_ID: "group.test"}) assert {"light.ceiling", "light.kitchen"} == await service.async_extract_entity_ids( hass, call @@ -467,7 +468,7 @@ async def test_extract_entity_ids(hass): assert ( await service.async_extract_entity_ids( hass, - ha.ServiceCall("light", "turn_on", {ATTR_ENTITY_ID: ENTITY_MATCH_NONE}), + ServiceCall("light", "turn_on", {ATTR_ENTITY_ID: ENTITY_MATCH_NONE}), ) == set() ) @@ -475,20 +476,20 @@ async def test_extract_entity_ids(hass): async def test_extract_entity_ids_from_area(hass, area_mock): """Test extract_entity_ids method with areas.""" - call = ha.ServiceCall("light", "turn_on", {"area_id": "own-area"}) + call = ServiceCall("light", "turn_on", {"area_id": "own-area"}) assert { "light.in_own_area", } == await service.async_extract_entity_ids(hass, call) - call = ha.ServiceCall("light", "turn_on", {"area_id": "test-area"}) + call = ServiceCall("light", "turn_on", {"area_id": "test-area"}) assert { "light.in_area", "light.assigned_to_area", } == await service.async_extract_entity_ids(hass, call) - call = ha.ServiceCall("light", "turn_on", {"area_id": ["test-area", "diff-area"]}) + call = ServiceCall("light", "turn_on", {"area_id": ["test-area", "diff-area"]}) assert { "light.in_area", @@ -498,7 +499,7 @@ async def test_extract_entity_ids_from_area(hass, area_mock): assert ( await service.async_extract_entity_ids( - hass, ha.ServiceCall("light", "turn_on", {"area_id": ENTITY_MATCH_NONE}) + hass, ServiceCall("light", "turn_on", {"area_id": ENTITY_MATCH_NONE}) ) == set() ) @@ -507,13 +508,13 @@ async def test_extract_entity_ids_from_area(hass, area_mock): async def test_extract_entity_ids_from_devices(hass, area_mock): """Test extract_entity_ids method with devices.""" assert await service.async_extract_entity_ids( - hass, ha.ServiceCall("light", "turn_on", {"device_id": "device-no-area-id"}) + hass, ServiceCall("light", "turn_on", {"device_id": "device-no-area-id"}) ) == { "light.no_area", } assert await service.async_extract_entity_ids( - hass, ha.ServiceCall("light", "turn_on", {"device_id": "device-area-a-id"}) + hass, ServiceCall("light", "turn_on", {"device_id": "device-area-a-id"}) ) == { "light.in_area_a", "light.in_area_b", @@ -521,13 +522,13 @@ async def test_extract_entity_ids_from_devices(hass, area_mock): assert ( await service.async_extract_entity_ids( - hass, ha.ServiceCall("light", "turn_on", {"device_id": "non-existing-id"}) + hass, ServiceCall("light", "turn_on", {"device_id": "non-existing-id"}) ) == set() ) -async def test_async_get_all_descriptions(hass): +async def test_async_get_all_descriptions(hass: HomeAssistant) -> None: """Test async_get_all_descriptions.""" group = hass.components.group group_config = {group.DOMAIN: {}} @@ -557,7 +558,7 @@ async def test_call_with_required_features(hass, mock_entities): hass, [Mock(entities=mock_entities)], test_service_mock, - ha.ServiceCall("test_domain", "test_service", {"entity_id": "all"}), + ServiceCall("test_domain", "test_service", {"entity_id": "all"}), required_features=[SUPPORT_A], ) @@ -576,7 +577,7 @@ async def test_call_with_required_features(hass, mock_entities): hass, [Mock(entities=mock_entities)], test_service_mock, - ha.ServiceCall( + ServiceCall( "test_domain", "test_service", {"entity_id": "light.living_room"} ), required_features=[SUPPORT_A], @@ -591,7 +592,7 @@ async def test_call_with_both_required_features(hass, mock_entities): hass, [Mock(entities=mock_entities)], test_service_mock, - ha.ServiceCall("test_domain", "test_service", {"entity_id": "all"}), + ServiceCall("test_domain", "test_service", {"entity_id": "all"}), required_features=[SUPPORT_A | SUPPORT_B], ) @@ -608,7 +609,7 @@ async def test_call_with_one_of_required_features(hass, mock_entities): hass, [Mock(entities=mock_entities)], test_service_mock, - ha.ServiceCall("test_domain", "test_service", {"entity_id": "all"}), + ServiceCall("test_domain", "test_service", {"entity_id": "all"}), required_features=[SUPPORT_A, SUPPORT_C], ) @@ -629,7 +630,7 @@ async def test_call_with_sync_func(hass, mock_entities): hass, [Mock(entities=mock_entities)], test_service_mock, - ha.ServiceCall("test_domain", "test_service", {"entity_id": "light.kitchen"}), + ServiceCall("test_domain", "test_service", {"entity_id": "light.kitchen"}), ) assert test_service_mock.call_count == 1 @@ -641,7 +642,7 @@ async def test_call_with_sync_attr(hass, mock_entities): hass, [Mock(entities=mock_entities)], "sync_method", - ha.ServiceCall( + ServiceCall( "test_domain", "test_service", {"entity_id": "light.kitchen", "area_id": "abcd"}, @@ -652,17 +653,17 @@ async def test_call_with_sync_attr(hass, mock_entities): assert mock_method.mock_calls[0][2] == {} -async def test_call_context_user_not_exist(hass): +async def test_call_context_user_not_exist(hass: HomeAssistant) -> None: """Check we don't allow deleted users to do things.""" with pytest.raises(exceptions.UnknownUser) as err: await service.entity_service_call( hass, [], Mock(), - ha.ServiceCall( + ServiceCall( "test_domain", "test_service", - context=ha.Context(user_id="non-existing"), + context=Context(user_id="non-existing"), ), ) @@ -683,11 +684,11 @@ async def test_call_context_target_all(hass, mock_handle_entity_call, mock_entit hass, [Mock(entities=mock_entities)], Mock(), - ha.ServiceCall( + ServiceCall( "test_domain", "test_service", data={"entity_id": ENTITY_MATCH_ALL}, - context=ha.Context(user_id="mock-id"), + context=Context(user_id="mock-id"), ), ) @@ -711,11 +712,11 @@ async def test_call_context_target_specific( hass, [Mock(entities=mock_entities)], Mock(), - ha.ServiceCall( + ServiceCall( "test_domain", "test_service", {"entity_id": "light.kitchen"}, - context=ha.Context(user_id="mock-id"), + context=Context(user_id="mock-id"), ), ) @@ -735,11 +736,11 @@ async def test_call_context_target_specific_no_auth( hass, [Mock(entities=mock_entities)], Mock(), - ha.ServiceCall( + ServiceCall( "test_domain", "test_service", {"entity_id": "light.kitchen"}, - context=ha.Context(user_id="mock-id"), + context=Context(user_id="mock-id"), ), ) @@ -753,7 +754,7 @@ async def test_call_no_context_target_all(hass, mock_handle_entity_call, mock_en hass, [Mock(entities=mock_entities)], Mock(), - ha.ServiceCall( + ServiceCall( "test_domain", "test_service", data={"entity_id": ENTITY_MATCH_ALL} ), ) @@ -772,7 +773,7 @@ async def test_call_no_context_target_specific( hass, [Mock(entities=mock_entities)], Mock(), - ha.ServiceCall( + ServiceCall( "test_domain", "test_service", {"entity_id": ["light.kitchen", "light.non-existing"]}, @@ -791,7 +792,7 @@ async def test_call_with_match_all( hass, [Mock(entities=mock_entities)], Mock(), - ha.ServiceCall("test_domain", "test_service", {"entity_id": "all"}), + ServiceCall("test_domain", "test_service", {"entity_id": "all"}), ) assert len(mock_handle_entity_call.mock_calls) == 4 @@ -806,7 +807,7 @@ async def test_call_with_omit_entity_id(hass, mock_handle_entity_call, mock_enti hass, [Mock(entities=mock_entities)], Mock(), - ha.ServiceCall("test_domain", "test_service"), + ServiceCall("test_domain", "test_service"), ) assert len(mock_handle_entity_call.mock_calls) == 0 @@ -834,7 +835,7 @@ async def test_register_admin_service(hass, hass_read_only_user, hass_admin_user "test", {}, blocking=True, - context=ha.Context(user_id="non-existing"), + context=Context(user_id="non-existing"), ) assert len(calls) == 0 @@ -844,7 +845,7 @@ async def test_register_admin_service(hass, hass_read_only_user, hass_admin_user "test", {}, blocking=True, - context=ha.Context(user_id=hass_read_only_user.id), + context=Context(user_id=hass_read_only_user.id), ) assert len(calls) == 0 @@ -854,7 +855,7 @@ async def test_register_admin_service(hass, hass_read_only_user, hass_admin_user "test", {"invalid": True}, blocking=True, - context=ha.Context(user_id=hass_admin_user.id), + context=Context(user_id=hass_admin_user.id), ) assert len(calls) == 0 @@ -864,7 +865,7 @@ async def test_register_admin_service(hass, hass_read_only_user, hass_admin_user "test2", {}, blocking=True, - context=ha.Context(user_id=hass_admin_user.id), + context=Context(user_id=hass_admin_user.id), ) assert len(calls) == 0 @@ -873,7 +874,7 @@ async def test_register_admin_service(hass, hass_read_only_user, hass_admin_user "test2", {"required": True}, blocking=True, - context=ha.Context(user_id=hass_admin_user.id), + context=Context(user_id=hass_admin_user.id), ) assert len(calls) == 1 assert calls[0].context.user_id == hass_admin_user.id @@ -917,7 +918,7 @@ async def test_domain_control_unknown(hass, mock_entities): "test_service", {}, blocking=True, - context=ha.Context(user_id="fake_user_id"), + context=Context(user_id="fake_user_id"), ) assert len(calls) == 0 @@ -955,7 +956,7 @@ async def test_domain_control_unauthorized(hass, hass_read_only_user): "test_service", {}, blocking=True, - context=ha.Context(user_id=hass_read_only_user.id), + context=Context(user_id=hass_read_only_user.id), ) assert len(calls) == 0 @@ -993,13 +994,13 @@ async def test_domain_control_admin(hass, hass_admin_user): "test_service", {}, blocking=True, - context=ha.Context(user_id=hass_admin_user.id), + context=Context(user_id=hass_admin_user.id), ) assert len(calls) == 1 -async def test_domain_control_no_user(hass): +async def test_domain_control_no_user(hass: HomeAssistant) -> None: """Test domain verification in a service call with no user.""" mock_registry( hass, @@ -1031,13 +1032,13 @@ async def test_domain_control_no_user(hass): "test_service", {}, blocking=True, - context=ha.Context(user_id=None), + context=Context(user_id=None), ) assert len(calls) == 1 -async def test_extract_from_service_available_device(hass): +async def test_extract_from_service_available_device(hass: HomeAssistant) -> None: """Test the extraction of entity from service and device is available.""" entities = [ MockEntity(name="test_1", entity_id="test_domain.test_1"), @@ -1046,14 +1047,14 @@ async def test_extract_from_service_available_device(hass): MockEntity(name="test_4", entity_id="test_domain.test_4", available=False), ] - call_1 = ha.ServiceCall("test", "service", data={"entity_id": ENTITY_MATCH_ALL}) + call_1 = ServiceCall("test", "service", data={"entity_id": ENTITY_MATCH_ALL}) assert ["test_domain.test_1", "test_domain.test_3"] == [ ent.entity_id for ent in (await service.async_extract_entities(hass, entities, call_1)) ] - call_2 = ha.ServiceCall( + call_2 = ServiceCall( "test", "service", data={"entity_id": ["test_domain.test_3", "test_domain.test_4"]}, @@ -1068,7 +1069,7 @@ async def test_extract_from_service_available_device(hass): await service.async_extract_entities( hass, entities, - ha.ServiceCall( + ServiceCall( "test", "service", data={"entity_id": ENTITY_MATCH_NONE}, @@ -1078,13 +1079,13 @@ async def test_extract_from_service_available_device(hass): ) -async def test_extract_from_service_empty_if_no_entity_id(hass): +async def test_extract_from_service_empty_if_no_entity_id(hass: HomeAssistant) -> None: """Test the extraction from service without specifying entity.""" entities = [ MockEntity(name="test_1", entity_id="test_domain.test_1"), MockEntity(name="test_2", entity_id="test_domain.test_2"), ] - call = ha.ServiceCall("test", "service") + call = ServiceCall("test", "service") assert [] == [ ent.entity_id @@ -1092,14 +1093,16 @@ async def test_extract_from_service_empty_if_no_entity_id(hass): ] -async def test_extract_from_service_filter_out_non_existing_entities(hass): +async def test_extract_from_service_filter_out_non_existing_entities( + hass: HomeAssistant, +) -> None: """Test the extraction of non existing entities from service.""" entities = [ MockEntity(name="test_1", entity_id="test_domain.test_1"), MockEntity(name="test_2", entity_id="test_domain.test_2"), ] - call = ha.ServiceCall( + call = ServiceCall( "test", "service", {"entity_id": ["test_domain.test_2", "test_domain.non_exist"]}, @@ -1119,12 +1122,12 @@ async def test_extract_from_service_area_id(hass, area_mock): MockEntity(name="diff_area", entity_id="light.diff_area"), ] - call = ha.ServiceCall("light", "turn_on", {"area_id": "test-area"}) + call = ServiceCall("light", "turn_on", {"area_id": "test-area"}) extracted = await service.async_extract_entities(hass, entities, call) assert len(extracted) == 1 assert extracted[0].entity_id == "light.in_area" - call = ha.ServiceCall("light", "turn_on", {"area_id": ["test-area", "diff-area"]}) + call = ServiceCall("light", "turn_on", {"area_id": ["test-area", "diff-area"]}) extracted = await service.async_extract_entities(hass, entities, call) assert len(extracted) == 2 assert sorted(ent.entity_id for ent in extracted) == [ @@ -1132,7 +1135,7 @@ async def test_extract_from_service_area_id(hass, area_mock): "light.in_area", ] - call = ha.ServiceCall( + call = ServiceCall( "light", "turn_on", {"area_id": ["test-area", "diff-area"], "device_id": "device-no-area-id"}, @@ -1148,7 +1151,7 @@ async def test_extract_from_service_area_id(hass, area_mock): async def test_entity_service_call_warn_referenced(hass, caplog): """Test we only warn for referenced entities in entity_service_call.""" - call = ha.ServiceCall( + call = ServiceCall( "light", "turn_on", { @@ -1166,7 +1169,7 @@ async def test_entity_service_call_warn_referenced(hass, caplog): async def test_async_extract_entities_warn_referenced(hass, caplog): """Test we only warn for referenced entities in async_extract_entities.""" - call = ha.ServiceCall( + call = ServiceCall( "light", "turn_on", { @@ -1183,14 +1186,14 @@ async def test_async_extract_entities_warn_referenced(hass, caplog): ) -async def test_async_extract_config_entry_ids(hass): +async def test_async_extract_config_entry_ids(hass: HomeAssistant) -> None: """Test we can find devices that have no entities.""" device_no_entities = dev_reg.DeviceEntry( id="device-no-entities", config_entries={"abc"} ) - call = ha.ServiceCall( + call = ServiceCall( "homeassistant", "reload_config_entry", { diff --git a/tests/helpers/test_start.py b/tests/helpers/test_start.py index bccf99a4274..574c28a6588 100644 --- a/tests/helpers/test_start.py +++ b/tests/helpers/test_start.py @@ -1,12 +1,12 @@ """Test starting HA helpers.""" -from homeassistant import core from homeassistant.const import EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STARTED +from homeassistant.core import CoreState, HomeAssistant, callback from homeassistant.helpers import start -async def test_at_start_when_running_awaitable(hass): +async def test_at_start_when_running_awaitable(hass: HomeAssistant) -> None: """Test at start when already running.""" - assert hass.state == core.CoreState.running + assert hass.state == CoreState.running assert hass.is_running calls = [] @@ -19,7 +19,7 @@ async def test_at_start_when_running_awaitable(hass): await hass.async_block_till_done() assert len(calls) == 1 - hass.state = core.CoreState.starting + hass.state = CoreState.starting assert hass.is_running start.async_at_start(hass, cb_at_start) @@ -29,12 +29,12 @@ async def test_at_start_when_running_awaitable(hass): async def test_at_start_when_running_callback(hass, caplog): """Test at start when already running.""" - assert hass.state == core.CoreState.running + assert hass.state == CoreState.running assert hass.is_running calls = [] - @core.callback + @callback def cb_at_start(hass): """Home Assistant is started.""" calls.append(1) @@ -42,7 +42,7 @@ async def test_at_start_when_running_callback(hass, caplog): start.async_at_start(hass, cb_at_start)() assert len(calls) == 1 - hass.state = core.CoreState.starting + hass.state = CoreState.starting assert hass.is_running start.async_at_start(hass, cb_at_start)() @@ -53,9 +53,9 @@ async def test_at_start_when_running_callback(hass, caplog): assert record.levelname in ("DEBUG", "INFO") -async def test_at_start_when_starting_awaitable(hass): +async def test_at_start_when_starting_awaitable(hass: HomeAssistant) -> None: """Test at start when yet to start.""" - hass.state = core.CoreState.not_running + hass.state = CoreState.not_running assert not hass.is_running calls = [] @@ -75,12 +75,12 @@ async def test_at_start_when_starting_awaitable(hass): async def test_at_start_when_starting_callback(hass, caplog): """Test at start when yet to start.""" - hass.state = core.CoreState.not_running + hass.state = CoreState.not_running assert not hass.is_running calls = [] - @core.callback + @callback def cb_at_start(hass): """Home Assistant is started.""" calls.append(1) @@ -102,7 +102,7 @@ async def test_at_start_when_starting_callback(hass, caplog): async def test_cancelling_at_start_when_running(hass, caplog): """Test cancelling at start when already running.""" - assert hass.state == core.CoreState.running + assert hass.state == CoreState.running assert hass.is_running calls = [] @@ -120,14 +120,14 @@ async def test_cancelling_at_start_when_running(hass, caplog): assert record.levelname in ("DEBUG", "INFO") -async def test_cancelling_at_start_when_starting(hass): +async def test_cancelling_at_start_when_starting(hass: HomeAssistant) -> None: """Test cancelling at start when yet to start.""" - hass.state = core.CoreState.not_running + hass.state = CoreState.not_running assert not hass.is_running calls = [] - @core.callback + @callback def cb_at_start(hass): """Home Assistant is started.""" calls.append(1) @@ -141,9 +141,9 @@ async def test_cancelling_at_start_when_starting(hass): assert len(calls) == 0 -async def test_at_started_when_running_awaitable(hass): +async def test_at_started_when_running_awaitable(hass: HomeAssistant) -> None: """Test at started when already started.""" - assert hass.state == core.CoreState.running + assert hass.state == CoreState.running calls = [] @@ -156,7 +156,7 @@ async def test_at_started_when_running_awaitable(hass): assert len(calls) == 1 # Test the job is not run if state is CoreState.starting - hass.state = core.CoreState.starting + hass.state = CoreState.starting start.async_at_started(hass, cb_at_start) await hass.async_block_till_done() @@ -165,11 +165,11 @@ async def test_at_started_when_running_awaitable(hass): async def test_at_started_when_running_callback(hass, caplog): """Test at started when already running.""" - assert hass.state == core.CoreState.running + assert hass.state == CoreState.running calls = [] - @core.callback + @callback def cb_at_start(hass): """Home Assistant is started.""" calls.append(1) @@ -178,7 +178,7 @@ async def test_at_started_when_running_callback(hass, caplog): assert len(calls) == 1 # Test the job is not run if state is CoreState.starting - hass.state = core.CoreState.starting + hass.state = CoreState.starting start.async_at_started(hass, cb_at_start)() assert len(calls) == 1 @@ -188,9 +188,9 @@ async def test_at_started_when_running_callback(hass, caplog): assert record.levelname in ("DEBUG", "INFO") -async def test_at_started_when_starting_awaitable(hass): +async def test_at_started_when_starting_awaitable(hass: HomeAssistant) -> None: """Test at started when yet to start.""" - hass.state = core.CoreState.not_running + hass.state = CoreState.not_running calls = [] @@ -213,11 +213,11 @@ async def test_at_started_when_starting_awaitable(hass): async def test_at_started_when_starting_callback(hass, caplog): """Test at started when yet to start.""" - hass.state = core.CoreState.not_running + hass.state = CoreState.not_running calls = [] - @core.callback + @callback def cb_at_start(hass): """Home Assistant is started.""" calls.append(1) @@ -243,7 +243,7 @@ async def test_at_started_when_starting_callback(hass, caplog): async def test_cancelling_at_started_when_running(hass, caplog): """Test cancelling at start when already running.""" - assert hass.state == core.CoreState.running + assert hass.state == CoreState.running assert hass.is_running calls = [] @@ -261,14 +261,14 @@ async def test_cancelling_at_started_when_running(hass, caplog): assert record.levelname in ("DEBUG", "INFO") -async def test_cancelling_at_started_when_starting(hass): +async def test_cancelling_at_started_when_starting(hass: HomeAssistant) -> None: """Test cancelling at start when yet to start.""" - hass.state = core.CoreState.not_running + hass.state = CoreState.not_running assert not hass.is_running calls = [] - @core.callback + @callback def cb_at_start(hass): """Home Assistant is started.""" calls.append(1) diff --git a/tests/helpers/test_state.py b/tests/helpers/test_state.py index aa1d148fbd7..9744a94265b 100644 --- a/tests/helpers/test_state.py +++ b/tests/helpers/test_state.py @@ -18,7 +18,7 @@ from homeassistant.const import ( STATE_OPEN, STATE_UNLOCKED, ) -import homeassistant.core as ha +from homeassistant.core import HomeAssistant, State from homeassistant.helpers import state from homeassistant.util import dt as dt_util @@ -49,7 +49,7 @@ async def test_async_track_states(hass, mock_integration_frame): assert [state2, state3] == sorted(states, key=lambda state: state.entity_id) -async def test_call_to_component(hass): +async def test_call_to_component(hass: HomeAssistant) -> None: """Test calls to components state reproduction functions.""" with patch( "homeassistant.components.media_player.reproduce_state.async_reproduce_states" @@ -63,8 +63,8 @@ async def test_call_to_component(hass): climate_fun.return_value = asyncio.Future() climate_fun.return_value.set_result(None) - state_media_player = ha.State("media_player.test", "bad") - state_climate = ha.State("climate.test", "bad") + state_media_player = State("media_player.test", "bad") + state_climate = State("climate.test", "bad") context = "dummy_context" await state.async_reproduce_state( @@ -103,11 +103,11 @@ async def test_get_changed_since(hass, mock_integration_frame): assert [state2, state3] == state.get_changed_since([state1, state2, state3], point2) -async def test_reproduce_with_no_entity(hass): +async def test_reproduce_with_no_entity(hass: HomeAssistant) -> None: """Test reproduce_state with no entity.""" calls = async_mock_service(hass, "light", SERVICE_TURN_ON) - await state.async_reproduce_state(hass, ha.State("light.test", "on")) + await state.async_reproduce_state(hass, State("light.test", "on")) await hass.async_block_till_done() @@ -115,13 +115,13 @@ async def test_reproduce_with_no_entity(hass): assert hass.states.get("light.test") is None -async def test_reproduce_turn_on(hass): +async def test_reproduce_turn_on(hass: HomeAssistant) -> None: """Test reproduce_state with SERVICE_TURN_ON.""" calls = async_mock_service(hass, "light", SERVICE_TURN_ON) hass.states.async_set("light.test", "off") - await state.async_reproduce_state(hass, ha.State("light.test", "on")) + await state.async_reproduce_state(hass, State("light.test", "on")) await hass.async_block_till_done() @@ -132,13 +132,13 @@ async def test_reproduce_turn_on(hass): assert last_call.data.get("entity_id") == "light.test" -async def test_reproduce_turn_off(hass): +async def test_reproduce_turn_off(hass: HomeAssistant) -> None: """Test reproduce_state with SERVICE_TURN_OFF.""" calls = async_mock_service(hass, "light", SERVICE_TURN_OFF) hass.states.async_set("light.test", "on") - await state.async_reproduce_state(hass, ha.State("light.test", "off")) + await state.async_reproduce_state(hass, State("light.test", "off")) await hass.async_block_till_done() @@ -149,7 +149,7 @@ async def test_reproduce_turn_off(hass): assert last_call.data.get("entity_id") == "light.test" -async def test_reproduce_complex_data(hass): +async def test_reproduce_complex_data(hass: HomeAssistant) -> None: """Test reproduce_state with complex service data.""" calls = async_mock_service(hass, "light", SERVICE_TURN_ON) @@ -158,7 +158,7 @@ async def test_reproduce_complex_data(hass): complex_data = [255, 100, 100] await state.async_reproduce_state( - hass, ha.State("light.test", "on", {"rgb_color": complex_data}) + hass, State("light.test", "on", {"rgb_color": complex_data}) ) await hass.async_block_till_done() @@ -170,13 +170,13 @@ async def test_reproduce_complex_data(hass): assert last_call.data.get("rgb_color") == complex_data -async def test_reproduce_bad_state(hass): +async def test_reproduce_bad_state(hass: HomeAssistant) -> None: """Test reproduce_state with bad state.""" calls = async_mock_service(hass, "light", SERVICE_TURN_ON) hass.states.async_set("light.test", "off") - await state.async_reproduce_state(hass, ha.State("light.test", "bad")) + await state.async_reproduce_state(hass, State("light.test", "bad")) await hass.async_block_till_done() @@ -184,7 +184,7 @@ async def test_reproduce_bad_state(hass): assert hass.states.get("light.test").state == "off" -async def test_as_number_states(hass): +async def test_as_number_states(hass: HomeAssistant) -> None: """Test state_as_number with states.""" zero_states = ( STATE_OFF, @@ -195,21 +195,21 @@ async def test_as_number_states(hass): ) one_states = (STATE_ON, STATE_OPEN, STATE_LOCKED, STATE_ABOVE_HORIZON, STATE_HOME) for _state in zero_states: - assert state.state_as_number(ha.State("domain.test", _state, {})) == 0 + assert state.state_as_number(State("domain.test", _state, {})) == 0 for _state in one_states: - assert state.state_as_number(ha.State("domain.test", _state, {})) == 1 + assert state.state_as_number(State("domain.test", _state, {})) == 1 -async def test_as_number_coercion(hass): +async def test_as_number_coercion(hass: HomeAssistant) -> None: """Test state_as_number with number.""" for _state in ("0", "0.0", 0, 0.0): - assert state.state_as_number(ha.State("domain.test", _state, {})) == 0.0 + assert state.state_as_number(State("domain.test", _state, {})) == 0.0 for _state in ("1", "1.0", 1, 1.0): - assert state.state_as_number(ha.State("domain.test", _state, {})) == 1.0 + assert state.state_as_number(State("domain.test", _state, {})) == 1.0 -async def test_as_number_invalid_cases(hass): +async def test_as_number_invalid_cases(hass: HomeAssistant) -> None: """Test state_as_number with invalid cases.""" for _state in ("", "foo", "foo.bar", None, False, True, object, object()): with pytest.raises(ValueError): - state.state_as_number(ha.State("domain.test", _state, {})) + state.state_as_number(State("domain.test", _state, {})) diff --git a/tests/helpers/test_storage.py b/tests/helpers/test_storage.py index af217971e99..4613a9162c2 100644 --- a/tests/helpers/test_storage.py +++ b/tests/helpers/test_storage.py @@ -11,7 +11,7 @@ from homeassistant.const import ( EVENT_HOMEASSISTANT_FINAL_WRITE, EVENT_HOMEASSISTANT_STOP, ) -from homeassistant.core import CoreState +from homeassistant.core import CoreState, HomeAssistant from homeassistant.helpers import storage from homeassistant.util import dt from homeassistant.util.color import RGBColor @@ -64,7 +64,7 @@ async def test_loading(hass, store): assert data == MOCK_DATA -async def test_custom_encoder(hass): +async def test_custom_encoder(hass: HomeAssistant) -> None: """Test we can save and load data.""" class JSONEncoder(json.JSONEncoder): diff --git a/tests/helpers/test_system_info.py b/tests/helpers/test_system_info.py index a3b6dafe600..ba43386b821 100644 --- a/tests/helpers/test_system_info.py +++ b/tests/helpers/test_system_info.py @@ -3,10 +3,11 @@ import json from unittest.mock import patch from homeassistant.const import __version__ as current_version +from homeassistant.core import HomeAssistant from homeassistant.helpers.system_info import async_get_system_info -async def test_get_system_info(hass): +async def test_get_system_info(hass: HomeAssistant) -> None: """Test the get system info.""" info = await async_get_system_info(hass) assert isinstance(info, dict) @@ -15,7 +16,7 @@ async def test_get_system_info(hass): assert json.dumps(info) is not None -async def test_container_installationtype(hass): +async def test_container_installationtype(hass: HomeAssistant) -> None: """Test container installation type.""" with patch("platform.system", return_value="Linux"), patch( "os.path.isfile", return_value=True @@ -30,7 +31,7 @@ async def test_container_installationtype(hass): assert info["installation_type"] == "Unsupported Third Party Container" -async def test_getuser_keyerror(hass): +async def test_getuser_keyerror(hass: HomeAssistant) -> None: """Test getuser keyerror.""" with patch("homeassistant.helpers.system_info.getuser", side_effect=KeyError): info = await async_get_system_info(hass) diff --git a/tests/helpers/test_translation.py b/tests/helpers/test_translation.py index 463f55204b0..0cafe48f008 100644 --- a/tests/helpers/test_translation.py +++ b/tests/helpers/test_translation.py @@ -195,7 +195,7 @@ async def test_get_translations_loads_config_flows(hass, mock_config_flows): assert "component2" not in hass.config.components -async def test_get_translations_while_loading_components(hass): +async def test_get_translations_while_loading_components(hass: HomeAssistant) -> None: """Test the get translations helper loads config flow translations.""" integration = Mock(file_path=pathlib.Path(__file__)) integration.name = "Component 1" @@ -231,7 +231,7 @@ async def test_get_translations_while_loading_components(hass): assert load_count == 1 -async def test_get_translation_categories(hass): +async def test_get_translation_categories(hass: HomeAssistant) -> None: """Test the get translations helper loads config flow translations.""" with patch.object(translation, "async_get_config_flows", return_value={"light"}): translations = await translation.async_get_translations( @@ -351,7 +351,7 @@ async def test_translation_merging_loaded_together(hass, caplog): assert translations == hue_translations | homekit_translations -async def test_caching(hass): +async def test_caching(hass: HomeAssistant) -> None: """Test we cache data.""" hass.config.components.add("sensor") hass.config.components.add("light") diff --git a/tests/helpers/test_trigger.py b/tests/helpers/test_trigger.py index 4718e3130d5..1481df3b97b 100644 --- a/tests/helpers/test_trigger.py +++ b/tests/helpers/test_trigger.py @@ -23,14 +23,14 @@ def calls(hass): return async_mock_service(hass, "test", "automation") -async def test_bad_trigger_platform(hass): +async def test_bad_trigger_platform(hass: HomeAssistant) -> None: """Test bad trigger platform.""" with pytest.raises(vol.Invalid) as ex: await async_validate_trigger_config(hass, [{"platform": "not_a_platform"}]) assert "Invalid platform 'not_a_platform' specified" in str(ex) -async def test_trigger_subtype(hass): +async def test_trigger_subtype(hass: HomeAssistant) -> None: """Test trigger subtypes.""" with patch( "homeassistant.helpers.trigger.async_get_integration", return_value=MagicMock() @@ -39,7 +39,7 @@ async def test_trigger_subtype(hass): assert integration_mock.call_args == call(hass, "test") -async def test_trigger_variables(hass): +async def test_trigger_variables(hass: HomeAssistant) -> None: """Test trigger variables.""" diff --git a/tests/helpers/test_update_coordinator.py b/tests/helpers/test_update_coordinator.py index 4e5f07a2232..5af4f02cc87 100644 --- a/tests/helpers/test_update_coordinator.py +++ b/tests/helpers/test_update_coordinator.py @@ -11,7 +11,7 @@ import requests from homeassistant import config_entries from homeassistant.const import EVENT_HOMEASSISTANT_STOP -from homeassistant.core import CoreState +from homeassistant.core import CoreState, HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import update_coordinator from homeassistant.util.dt import utcnow @@ -395,7 +395,9 @@ async def test_async_config_entry_first_refresh_success(crd, caplog): assert crd.last_update_success is True -async def test_not_schedule_refresh_if_system_option_disable_polling(hass): +async def test_not_schedule_refresh_if_system_option_disable_polling( + hass: HomeAssistant, +) -> None: """Test we do not schedule a refresh if disable polling in config entry.""" entry = MockConfigEntry(pref_disable_polling=True) config_entries.current_entry.set(entry) diff --git a/tests/test_bootstrap.py b/tests/test_bootstrap.py index f3526901d3d..99304b5b336 100644 --- a/tests/test_bootstrap.py +++ b/tests/test_bootstrap.py @@ -7,9 +7,10 @@ from unittest.mock import Mock, patch import pytest -from homeassistant import bootstrap, core, runner +from homeassistant import bootstrap, runner import homeassistant.config as config_util from homeassistant.const import SIGNAL_BOOTSTRAP_INTEGRATIONS +from homeassistant.core import HomeAssistant, async_get_hass, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.dispatcher import async_dispatcher_connect @@ -45,7 +46,7 @@ def mock_http_start_stop(): @patch("homeassistant.bootstrap.async_enable_logging", Mock()) -async def test_home_assistant_core_config_validation(hass): +async def test_home_assistant_core_config_validation(hass: HomeAssistant) -> None: """Test if we pass in wrong information for HA conf.""" # Extensive HA conf validation testing is done result = await bootstrap.async_from_config_dict( @@ -79,7 +80,7 @@ async def test_async_enable_logging(hass, caplog): assert "Error rolling over log file" in caplog.text -async def test_load_hassio(hass): +async def test_load_hassio(hass: HomeAssistant) -> None: """Test that we load Hass.io component.""" with patch.dict(os.environ, {}, clear=True): assert bootstrap._get_domains(hass, {}) == set() @@ -89,7 +90,7 @@ async def test_load_hassio(hass): @pytest.mark.parametrize("load_registries", [False]) -async def test_empty_setup(hass): +async def test_empty_setup(hass: HomeAssistant) -> None: """Test an empty set up loads the core.""" await bootstrap.async_from_config_dict({}, hass) for domain in bootstrap.CORE_INTEGRATIONS: @@ -110,7 +111,7 @@ async def test_core_failure_loads_safe_mode(hass, caplog): @pytest.mark.parametrize("load_registries", [False]) -async def test_setting_up_config(hass): +async def test_setting_up_config(hass: HomeAssistant) -> None: """Test we set up domains in config.""" await bootstrap._async_set_up_integrations( hass, {"group hello": {}, "homeassistant": {}} @@ -120,7 +121,7 @@ async def test_setting_up_config(hass): @pytest.mark.parametrize("load_registries", [False]) -async def test_setup_after_deps_all_present(hass): +async def test_setup_after_deps_all_present(hass: HomeAssistant) -> None: """Test after_dependencies when all present.""" order = [] @@ -165,7 +166,7 @@ async def test_setup_after_deps_all_present(hass): @pytest.mark.parametrize("load_registries", [False]) -async def test_setup_after_deps_in_stage_1_ignored(hass): +async def test_setup_after_deps_in_stage_1_ignored(hass: HomeAssistant) -> None: """Test after_dependencies are ignored in stage 1.""" # This test relies on this assert "cloud" in bootstrap.STAGE_1_INTEGRATIONS @@ -212,7 +213,7 @@ async def test_setup_after_deps_in_stage_1_ignored(hass): @pytest.mark.parametrize("load_registries", [False]) -async def test_setup_frontend_before_recorder(hass): +async def test_setup_frontend_before_recorder(hass: HomeAssistant) -> None: """Test frontend is setup before recorder.""" order = [] @@ -288,7 +289,7 @@ async def test_setup_frontend_before_recorder(hass): @pytest.mark.parametrize("load_registries", [False]) -async def test_setup_after_deps_via_platform(hass): +async def test_setup_after_deps_via_platform(hass: HomeAssistant) -> None: """Test after_dependencies set up via platform.""" order = [] after_dep_event = asyncio.Event() @@ -320,7 +321,7 @@ async def test_setup_after_deps_via_platform(hass): ) mock_entity_platform(hass, "light.platform_int", MockPlatform()) - @core.callback + @callback def continue_loading(_): """When light component loaded, continue other loading.""" after_dep_event.set() @@ -338,7 +339,7 @@ async def test_setup_after_deps_via_platform(hass): @pytest.mark.parametrize("load_registries", [False]) -async def test_setup_after_deps_not_trigger_load(hass): +async def test_setup_after_deps_not_trigger_load(hass: HomeAssistant) -> None: """Test after_dependencies does not trigger loading it.""" order = [] @@ -377,7 +378,7 @@ async def test_setup_after_deps_not_trigger_load(hass): @pytest.mark.parametrize("load_registries", [False]) -async def test_setup_after_deps_not_present(hass): +async def test_setup_after_deps_not_present(hass: HomeAssistant) -> None: """Test after_dependencies when referenced integration doesn't exist.""" order = [] @@ -501,7 +502,7 @@ async def test_setup_hass( assert len(mock_ensure_config_exists.mock_calls) == 1 assert len(mock_process_ha_config_upgrade.mock_calls) == 1 - assert hass == core.async_get_hass() + assert hass == async_get_hass() async def test_setup_hass_takes_longer_than_log_slow_startup( @@ -708,7 +709,9 @@ async def test_setup_safe_mode_if_no_frontend( @pytest.mark.parametrize("load_registries", [False]) -async def test_empty_integrations_list_is_only_sent_at_the_end_of_bootstrap(hass): +async def test_empty_integrations_list_is_only_sent_at_the_end_of_bootstrap( + hass: HomeAssistant, +) -> None: """Test empty integrations list is only sent at the end of bootstrap.""" order = [] @@ -743,7 +746,7 @@ async def test_empty_integrations_list_is_only_sent_at_the_end_of_bootstrap(hass integrations = [] - @core.callback + @callback def _bootstrap_integrations(data): integrations.append(data) diff --git a/tests/test_config.py b/tests/test_config.py index a39c3f9602d..ee017bcbcee 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -81,7 +81,7 @@ def teardown(): os.remove(SCENES_PATH) -async def test_create_default_config(hass): +async def test_create_default_config(hass: HomeAssistant) -> None: """Test creation of default config.""" assert not os.path.isfile(YAML_PATH) assert not os.path.isfile(SECRET_PATH) @@ -96,7 +96,7 @@ async def test_create_default_config(hass): assert os.path.isfile(AUTOMATIONS_PATH) -async def test_ensure_config_exists_creates_config(hass): +async def test_ensure_config_exists_creates_config(hass: HomeAssistant) -> None: """Test that calling ensure_config_exists. If not creates a new config file. @@ -109,7 +109,7 @@ async def test_ensure_config_exists_creates_config(hass): assert mock_print.called -async def test_ensure_config_exists_uses_existing_config(hass): +async def test_ensure_config_exists_uses_existing_config(hass: HomeAssistant) -> None: """Test that calling ensure_config_exists uses existing config.""" create_file(YAML_PATH) await config_util.async_ensure_config_exists(hass) @@ -121,7 +121,7 @@ async def test_ensure_config_exists_uses_existing_config(hass): assert content == "" -async def test_ensure_existing_files_is_not_overwritten(hass): +async def test_ensure_existing_files_is_not_overwritten(hass: HomeAssistant) -> None: """Test that calling async_create_default_config does not overwrite existing files.""" create_file(SECRET_PATH) @@ -190,7 +190,9 @@ def test_load_yaml_config_preserves_key_order() -> None: ) -async def test_create_default_config_returns_none_if_write_error(hass): +async def test_create_default_config_returns_none_if_write_error( + hass: HomeAssistant, +) -> None: """Test the writing of a default configuration. Non existing folder returns None. @@ -281,7 +283,7 @@ async def _compute_state(hass, config): return hass.states.get("test.test") -async def test_entity_customization(hass): +async def test_entity_customization(hass: HomeAssistant) -> None: """Test entity customization through configuration.""" config = { CONF_LATITUDE: 50, @@ -524,7 +526,7 @@ async def test_override_stored_configuration(hass, hass_storage): assert hass.config.config_source is ConfigSource.YAML -async def test_loading_configuration(hass): +async def test_loading_configuration(hass: HomeAssistant) -> None: """Test loading core config onto hass object.""" await config_util.async_process_ha_core_config( hass, @@ -631,7 +633,9 @@ async def test_language_default( assert hass.config.language == default_language -async def test_loading_configuration_default_media_dirs_docker(hass): +async def test_loading_configuration_default_media_dirs_docker( + hass: HomeAssistant, +) -> None: """Test loading core config onto hass object.""" with patch("homeassistant.config.is_docker_env", return_value=True): await config_util.async_process_ha_core_config( @@ -647,7 +651,7 @@ async def test_loading_configuration_default_media_dirs_docker(hass): assert hass.config.media_dirs == {"local": "/media"} -async def test_loading_configuration_from_packages(hass): +async def test_loading_configuration_from_packages(hass: HomeAssistant) -> None: """Test loading packages config onto hass object config.""" await config_util.async_process_ha_core_config( hass, @@ -882,7 +886,7 @@ async def test_merge_once_only_keys(merge_log_err, hass): assert merge_log_err.call_count == 1 -async def test_merge_once_only_lists(hass): +async def test_merge_once_only_lists(hass: HomeAssistant) -> None: """Test if we have a merge for a comp that may occur only once. Lists.""" packages = { "pack_2": { @@ -901,7 +905,7 @@ async def test_merge_once_only_lists(hass): } -async def test_merge_once_only_dictionaries(hass): +async def test_merge_once_only_dictionaries(hass: HomeAssistant) -> None: """Test if we have a merge for a comp that may occur only once. Dicts.""" packages = { "pack_2": { @@ -927,7 +931,7 @@ async def test_merge_once_only_dictionaries(hass): } -async def test_merge_id_schema(hass): +async def test_merge_id_schema(hass: HomeAssistant) -> None: """Test if we identify the config schemas correctly.""" types = { "panel_custom": "list", @@ -957,7 +961,7 @@ async def test_merge_duplicate_keys(merge_log_err, hass): assert len(config["input_select"]) == 1 -async def test_merge_customize(hass): +async def test_merge_customize(hass: HomeAssistant) -> None: """Test loading core config onto hass object.""" core_config = { "latitude": 60, @@ -976,7 +980,7 @@ async def test_merge_customize(hass): assert hass.data[config_util.DATA_CUSTOMIZE].get("b.b") == {"friendly_name": "BB"} -async def test_auth_provider_config(hass): +async def test_auth_provider_config(hass: HomeAssistant) -> None: """Test loading auth provider config onto hass object.""" core_config = { "latitude": 60, @@ -1003,7 +1007,7 @@ async def test_auth_provider_config(hass): assert hass.auth.auth_mfa_modules[1].id == "second" -async def test_auth_provider_config_default(hass): +async def test_auth_provider_config_default(hass: HomeAssistant) -> None: """Test loading default auth provider config.""" core_config = { "latitude": 60, @@ -1023,7 +1027,7 @@ async def test_auth_provider_config_default(hass): assert hass.auth.auth_mfa_modules[0].id == "totp" -async def test_disallowed_auth_provider_config(hass): +async def test_disallowed_auth_provider_config(hass: HomeAssistant) -> None: """Test loading insecure example auth provider is disallowed.""" core_config = { "latitude": 60, @@ -1049,7 +1053,7 @@ async def test_disallowed_auth_provider_config(hass): await config_util.async_process_ha_core_config(hass, core_config) -async def test_disallowed_duplicated_auth_provider_config(hass): +async def test_disallowed_duplicated_auth_provider_config(hass: HomeAssistant) -> None: """Test loading insecure example auth provider is disallowed.""" core_config = { "latitude": 60, @@ -1064,7 +1068,7 @@ async def test_disallowed_duplicated_auth_provider_config(hass): await config_util.async_process_ha_core_config(hass, core_config) -async def test_disallowed_auth_mfa_module_config(hass): +async def test_disallowed_auth_mfa_module_config(hass: HomeAssistant) -> None: """Test loading insecure example auth mfa module is disallowed.""" core_config = { "latitude": 60, @@ -1084,7 +1088,9 @@ async def test_disallowed_auth_mfa_module_config(hass): await config_util.async_process_ha_core_config(hass, core_config) -async def test_disallowed_duplicated_auth_mfa_module_config(hass): +async def test_disallowed_duplicated_auth_mfa_module_config( + hass: HomeAssistant, +) -> None: """Test loading insecure example auth mfa module is disallowed.""" core_config = { "latitude": 60, @@ -1099,7 +1105,7 @@ async def test_disallowed_duplicated_auth_mfa_module_config(hass): await config_util.async_process_ha_core_config(hass, core_config) -async def test_merge_split_component_definition(hass): +async def test_merge_split_component_definition(hass: HomeAssistant) -> None: """Test components with trailing description in packages are merged.""" packages = { "pack_1": {"light one": {"l1": None}}, @@ -1293,7 +1299,7 @@ def test_identify_config_schema(domain, schema, expected): ) -async def test_core_config_schema_historic_currency(hass): +async def test_core_config_schema_historic_currency(hass: HomeAssistant) -> None: """Test core config schema.""" await config_util.async_process_ha_core_config(hass, {"currency": "LTT"}) @@ -1327,7 +1333,7 @@ async def test_core_store_historic_currency(hass, hass_storage): assert not issue -async def test_core_config_schema_no_country(hass): +async def test_core_config_schema_no_country(hass: HomeAssistant) -> None: """Test core config schema.""" await config_util.async_process_ha_core_config(hass, {}) diff --git a/tests/test_config_entries.py b/tests/test_config_entries.py index 353bfa64ece..1619a19d079 100644 --- a/tests/test_config_entries.py +++ b/tests/test_config_entries.py @@ -69,7 +69,7 @@ def manager(hass): return manager -async def test_call_setup_entry(hass): +async def test_call_setup_entry(hass: HomeAssistant) -> None: """Test we call .setup_entry.""" entry = MockConfigEntry(domain="comp") entry.add_to_hass(hass) @@ -98,7 +98,7 @@ async def test_call_setup_entry(hass): assert entry.supports_unload -async def test_call_setup_entry_without_reload_support(hass): +async def test_call_setup_entry_without_reload_support(hass: HomeAssistant) -> None: """Test we call .setup_entry and the does not support unloading.""" entry = MockConfigEntry(domain="comp") entry.add_to_hass(hass) @@ -127,7 +127,7 @@ async def test_call_setup_entry_without_reload_support(hass): assert not entry.supports_unload -async def test_call_async_migrate_entry(hass): +async def test_call_async_migrate_entry(hass: HomeAssistant) -> None: """Test we call .async_migrate_entry when version mismatch.""" entry = MockConfigEntry(domain="comp") assert not entry.supports_unload @@ -157,7 +157,7 @@ async def test_call_async_migrate_entry(hass): assert entry.supports_unload -async def test_call_async_migrate_entry_failure_false(hass): +async def test_call_async_migrate_entry_failure_false(hass: HomeAssistant) -> None: """Test migration fails if returns false.""" entry = MockConfigEntry(domain="comp") entry.version = 2 @@ -185,7 +185,7 @@ async def test_call_async_migrate_entry_failure_false(hass): assert not entry.supports_unload -async def test_call_async_migrate_entry_failure_exception(hass): +async def test_call_async_migrate_entry_failure_exception(hass: HomeAssistant) -> None: """Test migration fails if exception raised.""" entry = MockConfigEntry(domain="comp") entry.version = 2 @@ -213,7 +213,7 @@ async def test_call_async_migrate_entry_failure_exception(hass): assert not entry.supports_unload -async def test_call_async_migrate_entry_failure_not_bool(hass): +async def test_call_async_migrate_entry_failure_not_bool(hass: HomeAssistant) -> None: """Test migration fails if boolean not returned.""" entry = MockConfigEntry(domain="comp") entry.version = 2 @@ -241,7 +241,9 @@ async def test_call_async_migrate_entry_failure_not_bool(hass): assert not entry.supports_unload -async def test_call_async_migrate_entry_failure_not_supported(hass): +async def test_call_async_migrate_entry_failure_not_supported( + hass: HomeAssistant, +) -> None: """Test migration fails if async_migrate_entry not implemented.""" entry = MockConfigEntry(domain="comp") entry.version = 2 @@ -567,7 +569,7 @@ async def test_domains_gets_domains_excludes_ignore_and_disabled(manager): ] -async def test_saving_and_loading(hass): +async def test_saving_and_loading(hass: HomeAssistant) -> None: """Test that we're saving and loading correctly.""" mock_integration( hass, MockModule("test", async_setup_entry=lambda *args: mock_coro(True)) @@ -639,7 +641,7 @@ async def test_saving_and_loading(hass): assert orig.pref_disable_polling == loaded.pref_disable_polling -async def test_forward_entry_sets_up_component(hass): +async def test_forward_entry_sets_up_component(hass: HomeAssistant) -> None: """Test we setup the component entry is forwarded to.""" entry = MockConfigEntry(domain="original") @@ -658,7 +660,9 @@ async def test_forward_entry_sets_up_component(hass): assert len(mock_forwarded_setup_entry.mock_calls) == 1 -async def test_forward_entry_does_not_setup_entry_if_setup_fails(hass): +async def test_forward_entry_does_not_setup_entry_if_setup_fails( + hass: HomeAssistant, +) -> None: """Test we do not set up entry if component setup fails.""" entry = MockConfigEntry(domain="original") @@ -676,7 +680,7 @@ async def test_forward_entry_does_not_setup_entry_if_setup_fails(hass): assert len(mock_setup_entry.mock_calls) == 0 -async def test_discovery_notification(hass): +async def test_discovery_notification(hass: HomeAssistant) -> None: """Test that we create/dismiss a notification when source is discovery.""" mock_integration(hass, MockModule("test")) mock_entity_platform(hass, "config_flow.test", None) @@ -728,7 +732,7 @@ async def test_discovery_notification(hass): assert state is None -async def test_reauth_notification(hass): +async def test_reauth_notification(hass: HomeAssistant) -> None: """Test that we create/dismiss a notification when source is reauth.""" mock_integration(hass, MockModule("test")) mock_entity_platform(hass, "config_flow.test", None) @@ -795,7 +799,7 @@ async def test_reauth_notification(hass): assert state is None -async def test_discovery_notification_not_created(hass): +async def test_discovery_notification_not_created(hass: HomeAssistant) -> None: """Test that we not create a notification when discovery is aborted.""" mock_integration(hass, MockModule("test")) mock_entity_platform(hass, "config_flow.test", None) @@ -819,7 +823,7 @@ async def test_discovery_notification_not_created(hass): assert state is None -async def test_loading_default_config(hass): +async def test_loading_default_config(hass: HomeAssistant) -> None: """Test loading the default config.""" manager = config_entries.ConfigEntries(hass, {}) @@ -938,7 +942,7 @@ async def test_setup_raise_not_ready_from_exception(hass, caplog): ) -async def test_setup_retrying_during_unload(hass): +async def test_setup_retrying_during_unload(hass: HomeAssistant) -> None: """Test if we unload an entry that is in retry mode.""" entry = MockConfigEntry(domain="test") @@ -958,7 +962,7 @@ async def test_setup_retrying_during_unload(hass): assert len(mock_call.return_value.mock_calls) == 1 -async def test_setup_retrying_during_unload_before_started(hass): +async def test_setup_retrying_during_unload_before_started(hass: HomeAssistant) -> None: """Test if we unload an entry that is in retry mode before started.""" entry = MockConfigEntry(domain="test") hass.state = CoreState.starting @@ -985,7 +989,7 @@ async def test_setup_retrying_during_unload_before_started(hass): ) -async def test_create_entry_options(hass): +async def test_create_entry_options(hass: HomeAssistant) -> None: """Test a config entry being created with options.""" async def mock_async_setup(hass, config): @@ -1417,7 +1421,7 @@ async def test_entry_enable_without_reload_support(hass, manager): assert entry.state is config_entries.ConfigEntryState.FAILED_UNLOAD -async def test_init_custom_integration(hass): +async def test_init_custom_integration(hass: HomeAssistant) -> None: """Test initializing flow for custom integration.""" integration = loader.Integration( hass, @@ -1432,13 +1436,15 @@ async def test_init_custom_integration(hass): await hass.config_entries.flow.async_init("bla", context={"source": "user"}) -async def test_support_entry_unload(hass): +async def test_support_entry_unload(hass: HomeAssistant) -> None: """Test unloading entry.""" assert await config_entries.support_entry_unload(hass, "light") assert not await config_entries.support_entry_unload(hass, "auth") -async def test_reload_entry_entity_registry_ignores_no_entry(hass): +async def test_reload_entry_entity_registry_ignores_no_entry( + hass: HomeAssistant, +) -> None: """Test reloading entry in entity registry skips if no config entry linked.""" handler = config_entries.EntityRegistryDisabledHandler(hass) registry = mock_registry(hass) @@ -1453,7 +1459,7 @@ async def test_reload_entry_entity_registry_ignores_no_entry(hass): assert handler._remove_call_later is None -async def test_reload_entry_entity_registry_works(hass): +async def test_reload_entry_entity_registry_works(hass: HomeAssistant) -> None: """Test we schedule an entry to be reloaded if disabled_by is updated.""" handler = config_entries.EntityRegistryDisabledHandler(hass) handler.async_setup() @@ -2334,7 +2340,7 @@ async def test_partial_flows_hidden(hass, manager): assert state is not None -async def test_async_setup_init_entry(hass): +async def test_async_setup_init_entry(hass: HomeAssistant) -> None: """Test a config entry being initialized during integration setup.""" async def mock_async_setup(hass, config): @@ -2378,7 +2384,9 @@ async def test_async_setup_init_entry(hass): assert entries[0].state is config_entries.ConfigEntryState.LOADED -async def test_async_setup_init_entry_completes_before_loaded_event_fires(hass): +async def test_async_setup_init_entry_completes_before_loaded_event_fires( + hass: HomeAssistant, +) -> None: """Test a config entry being initialized during integration setup before the loaded event fires.""" load_events: list[Event] = [] @@ -2444,7 +2452,7 @@ async def test_async_setup_init_entry_completes_before_loaded_event_fires(hass): listener() -async def test_async_setup_update_entry(hass): +async def test_async_setup_update_entry(hass: HomeAssistant) -> None: """Test a config entry being updated during integration setup.""" entry = MockConfigEntry(domain="comp", data={"value": "initial"}) entry.add_to_hass(hass) @@ -3090,7 +3098,7 @@ async def test_setup_raise_auth_failed_from_future_coordinator_update(hass, capl assert len(flows) == 1 -async def test_initialize_and_shutdown(hass): +async def test_initialize_and_shutdown(hass: HomeAssistant) -> None: """Test we call the shutdown function at stop.""" manager = config_entries.ConfigEntries(hass, {}) @@ -3102,7 +3110,7 @@ async def test_initialize_and_shutdown(hass): assert mock_async_shutdown.called -async def test_setup_retrying_during_shutdown(hass): +async def test_setup_retrying_during_shutdown(hass: HomeAssistant) -> None: """Test if we shutdown an entry that is in retry mode.""" entry = MockConfigEntry(domain="test") @@ -3376,7 +3384,7 @@ async def test_disallow_entry_reload_with_setup_in_progresss(hass, manager): assert entry.state is config_entries.ConfigEntryState.SETUP_IN_PROGRESS -async def test_reauth(hass): +async def test_reauth(hass: HomeAssistant) -> None: """Test the async_reauth_helper.""" entry = MockConfigEntry(title="test_title", domain="test") entry2 = MockConfigEntry(title="test_title", domain="test") @@ -3424,7 +3432,7 @@ async def test_reauth(hass): assert len(hass.config_entries.flow.async_progress()) == 2 -async def test_get_active_flows(hass): +async def test_get_active_flows(hass: HomeAssistant) -> None: """Test the async_get_active_flows helper.""" entry = MockConfigEntry(title="test_title", domain="test") mock_setup_entry = AsyncMock(return_value=True) diff --git a/tests/test_core.py b/tests/test_core.py index c6621fd00cb..db89bac36f6 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -32,7 +32,7 @@ from homeassistant.const import ( __version__, ) import homeassistant.core as ha -from homeassistant.core import State +from homeassistant.core import HomeAssistant, State from homeassistant.exceptions import ( InvalidEntityFormatError, InvalidStateError, @@ -166,7 +166,7 @@ def test_async_run_hass_job_delegates_non_async() -> None: assert len(hass.async_add_hass_job.mock_calls) == 1 -async def test_stage_shutdown(hass): +async def test_stage_shutdown(hass: HomeAssistant) -> None: """Simulate a shutdown, test calling stuff.""" test_stop = async_capture_events(hass, EVENT_HOMEASSISTANT_STOP) test_final_write = async_capture_events(hass, EVENT_HOMEASSISTANT_FINAL_WRITE) @@ -205,7 +205,7 @@ async def test_shutdown_calls_block_till_done_after_shutdown_run_callback_thread assert stop_calls[-1] == "async_block_till_done" -async def test_pending_sheduler(hass): +async def test_pending_sheduler(hass: HomeAssistant) -> None: """Add a coro to pending tasks.""" call_count = [] @@ -222,7 +222,7 @@ async def test_pending_sheduler(hass): assert len(call_count) == 3 -async def test_async_add_job_pending_tasks_coro(hass): +async def test_async_add_job_pending_tasks_coro(hass: HomeAssistant) -> None: """Add a coro to pending tasks.""" call_count = [] @@ -245,7 +245,7 @@ async def test_async_add_job_pending_tasks_coro(hass): assert len(call_count) == 2 -async def test_async_create_task_pending_tasks_coro(hass): +async def test_async_create_task_pending_tasks_coro(hass: HomeAssistant) -> None: """Add a coro to pending tasks.""" call_count = [] @@ -268,7 +268,7 @@ async def test_async_create_task_pending_tasks_coro(hass): assert len(call_count) == 2 -async def test_async_add_job_pending_tasks_executor(hass): +async def test_async_add_job_pending_tasks_executor(hass: HomeAssistant) -> None: """Run an executor in pending tasks.""" call_count = [] @@ -291,7 +291,7 @@ async def test_async_add_job_pending_tasks_executor(hass): assert len(call_count) == 2 -async def test_async_add_job_pending_tasks_callback(hass): +async def test_async_add_job_pending_tasks_callback(hass: HomeAssistant) -> None: """Run a callback in pending tasks.""" call_count = [] @@ -316,7 +316,7 @@ async def test_async_add_job_pending_tasks_callback(hass): assert len(call_count) == 2 -async def test_add_job_with_none(hass): +async def test_add_job_with_none(hass: HomeAssistant) -> None: """Try to add a job with None as function.""" with pytest.raises(ValueError): hass.async_add_job(None, "test_arg") @@ -451,7 +451,7 @@ def test_state_as_compressed_state_unique_last_updated() -> None: assert state.as_compressed_state() is as_compressed_state -async def test_eventbus_add_remove_listener(hass): +async def test_eventbus_add_remove_listener(hass: HomeAssistant) -> None: """Test remove_listener method.""" old_count = len(hass.bus.async_listeners()) @@ -470,7 +470,7 @@ async def test_eventbus_add_remove_listener(hass): unsub() -async def test_eventbus_filtered_listener(hass): +async def test_eventbus_filtered_listener(hass: HomeAssistant) -> None: """Test we can prefilter events.""" calls = [] @@ -499,7 +499,7 @@ async def test_eventbus_filtered_listener(hass): unsub() -async def test_eventbus_run_immediately(hass): +async def test_eventbus_run_immediately(hass: HomeAssistant) -> None: """Test we can call events immediately.""" calls = [] @@ -517,7 +517,7 @@ async def test_eventbus_run_immediately(hass): unsub() -async def test_eventbus_unsubscribe_listener(hass): +async def test_eventbus_unsubscribe_listener(hass: HomeAssistant) -> None: """Test unsubscribe listener from returned function.""" calls = [] @@ -541,7 +541,7 @@ async def test_eventbus_unsubscribe_listener(hass): assert len(calls) == 1 -async def test_eventbus_listen_once_event_with_callback(hass): +async def test_eventbus_listen_once_event_with_callback(hass: HomeAssistant) -> None: """Test listen_once_event method.""" runs = [] @@ -559,7 +559,7 @@ async def test_eventbus_listen_once_event_with_callback(hass): assert len(runs) == 1 -async def test_eventbus_listen_once_event_with_coroutine(hass): +async def test_eventbus_listen_once_event_with_coroutine(hass: HomeAssistant) -> None: """Test listen_once_event method.""" runs = [] @@ -576,7 +576,7 @@ async def test_eventbus_listen_once_event_with_coroutine(hass): assert len(runs) == 1 -async def test_eventbus_listen_once_event_with_thread(hass): +async def test_eventbus_listen_once_event_with_thread(hass: HomeAssistant) -> None: """Test listen_once_event method.""" runs = [] @@ -593,7 +593,7 @@ async def test_eventbus_listen_once_event_with_thread(hass): assert len(runs) == 1 -async def test_eventbus_thread_event_listener(hass): +async def test_eventbus_thread_event_listener(hass: HomeAssistant) -> None: """Test thread event listener.""" thread_calls = [] @@ -606,7 +606,7 @@ async def test_eventbus_thread_event_listener(hass): assert len(thread_calls) == 1 -async def test_eventbus_callback_event_listener(hass): +async def test_eventbus_callback_event_listener(hass: HomeAssistant) -> None: """Test callback event listener.""" callback_calls = [] @@ -620,7 +620,7 @@ async def test_eventbus_callback_event_listener(hass): assert len(callback_calls) == 1 -async def test_eventbus_coroutine_event_listener(hass): +async def test_eventbus_coroutine_event_listener(hass: HomeAssistant) -> None: """Test coroutine event listener.""" coroutine_calls = [] @@ -633,7 +633,7 @@ async def test_eventbus_coroutine_event_listener(hass): assert len(coroutine_calls) == 1 -async def test_eventbus_max_length_exceeded(hass): +async def test_eventbus_max_length_exceeded(hass: HomeAssistant) -> None: """Test that an exception is raised when the max character length is exceeded.""" long_evt_name = ( @@ -725,7 +725,7 @@ def test_state_repr() -> None: ) -async def test_statemachine_is_state(hass): +async def test_statemachine_is_state(hass: HomeAssistant) -> None: """Test is_state method.""" hass.states.async_set("light.bowl", "on", {}) assert hass.states.is_state("light.Bowl", "on") @@ -733,7 +733,7 @@ async def test_statemachine_is_state(hass): assert not hass.states.is_state("light.Non_existing", "on") -async def test_statemachine_entity_ids(hass): +async def test_statemachine_entity_ids(hass: HomeAssistant) -> None: """Test get_entity_ids method.""" hass.states.async_set("light.bowl", "on", {}) hass.states.async_set("SWITCH.AC", "off", {}) @@ -750,7 +750,7 @@ async def test_statemachine_entity_ids(hass): assert states == ["light.bowl", "switch.ac"] -async def test_statemachine_remove(hass): +async def test_statemachine_remove(hass: HomeAssistant) -> None: """Test remove method.""" hass.states.async_set("light.bowl", "on", {}) events = async_capture_events(hass, EVENT_STATE_CHANGED) @@ -772,7 +772,7 @@ async def test_statemachine_remove(hass): assert len(events) == 1 -async def test_statemachine_case_insensitivty(hass): +async def test_statemachine_case_insensitivty(hass: HomeAssistant) -> None: """Test insensitivty.""" events = async_capture_events(hass, EVENT_STATE_CHANGED) @@ -783,7 +783,9 @@ async def test_statemachine_case_insensitivty(hass): assert len(events) == 1 -async def test_statemachine_last_changed_not_updated_on_same_state(hass): +async def test_statemachine_last_changed_not_updated_on_same_state( + hass: HomeAssistant, +) -> None: """Test to not update the existing, same state.""" hass.states.async_set("light.bowl", "on", {}) state = hass.states.get("light.Bowl") @@ -799,7 +801,7 @@ async def test_statemachine_last_changed_not_updated_on_same_state(hass): assert state.last_changed == state2.last_changed -async def test_statemachine_force_update(hass): +async def test_statemachine_force_update(hass: HomeAssistant) -> None: """Test force update option.""" hass.states.async_set("light.bowl", "on", {}) events = async_capture_events(hass, EVENT_STATE_CHANGED) @@ -825,7 +827,7 @@ def test_service_call_repr() -> None: ) -async def test_serviceregistry_has_service(hass): +async def test_serviceregistry_has_service(hass: HomeAssistant) -> None: """Test has_service method.""" hass.services.async_register("test_domain", "test_service", lambda call: None) assert len(hass.services.async_services()) == 1 @@ -834,7 +836,9 @@ async def test_serviceregistry_has_service(hass): assert not hass.services.has_service("non_existing", "test_service") -async def test_serviceregistry_call_with_blocking_done_in_time(hass): +async def test_serviceregistry_call_with_blocking_done_in_time( + hass: HomeAssistant, +) -> None: """Test call with blocking.""" registered_events = async_capture_events(hass, EVENT_SERVICE_REGISTERED) calls = async_mock_service(hass, "test_domain", "register_calls") @@ -850,13 +854,15 @@ async def test_serviceregistry_call_with_blocking_done_in_time(hass): assert len(calls) == 1 -async def test_serviceregistry_call_non_existing_with_blocking(hass): +async def test_serviceregistry_call_non_existing_with_blocking( + hass: HomeAssistant, +) -> None: """Test non-existing with blocking.""" with pytest.raises(ha.ServiceNotFound): await hass.services.async_call("test_domain", "i_do_not_exist", blocking=True) -async def test_serviceregistry_async_service(hass): +async def test_serviceregistry_async_service(hass: HomeAssistant) -> None: """Test registering and calling an async service.""" calls = [] @@ -872,7 +878,7 @@ async def test_serviceregistry_async_service(hass): assert len(calls) == 1 -async def test_serviceregistry_async_service_partial(hass): +async def test_serviceregistry_async_service_partial(hass: HomeAssistant) -> None: """Test registering and calling an wrapped async service.""" calls = [] @@ -891,7 +897,7 @@ async def test_serviceregistry_async_service_partial(hass): assert len(calls) == 1 -async def test_serviceregistry_callback_service(hass): +async def test_serviceregistry_callback_service(hass: HomeAssistant) -> None: """Test registering and calling an async service.""" calls = [] @@ -908,7 +914,7 @@ async def test_serviceregistry_callback_service(hass): assert len(calls) == 1 -async def test_serviceregistry_remove_service(hass): +async def test_serviceregistry_remove_service(hass: HomeAssistant) -> None: """Test remove service.""" calls_remove = async_capture_events(hass, EVENT_SERVICE_REMOVED) @@ -924,7 +930,7 @@ async def test_serviceregistry_remove_service(hass): assert calls_remove[-1].data["service"] == "test_service" -async def test_serviceregistry_service_that_not_exists(hass): +async def test_serviceregistry_service_that_not_exists(hass: HomeAssistant) -> None: """Test remove service that not exists.""" calls_remove = async_capture_events(hass, EVENT_SERVICE_REMOVED) assert not hass.services.has_service("test_xxx", "test_yyy") @@ -936,7 +942,9 @@ async def test_serviceregistry_service_that_not_exists(hass): await hass.services.async_call("test_do_not", "exist", {}) -async def test_serviceregistry_async_service_raise_exception(hass): +async def test_serviceregistry_async_service_raise_exception( + hass: HomeAssistant, +) -> None: """Test registering and calling an async service raise exception.""" async def service_handler(_): @@ -955,7 +963,9 @@ async def test_serviceregistry_async_service_raise_exception(hass): await hass.async_block_till_done() -async def test_serviceregistry_callback_service_raise_exception(hass): +async def test_serviceregistry_callback_service_raise_exception( + hass: HomeAssistant, +) -> None: """Test registering and calling an callback service raise exception.""" @ha.callback @@ -1110,7 +1120,7 @@ async def test_config_is_allowed_external_url() -> None: assert not config.is_allowed_external_url(url) -async def test_event_on_update(hass): +async def test_event_on_update(hass: HomeAssistant) -> None: """Test that event is fired on update.""" events = async_capture_events(hass, EVENT_CORE_CONFIG_UPDATE) @@ -1124,7 +1134,7 @@ async def test_event_on_update(hass): assert events[0].data == {"latitude": 12} -async def test_bad_timezone_raises_value_error(hass): +async def test_bad_timezone_raises_value_error(hass: HomeAssistant) -> None: """Test bad timezone raises ValueError.""" with pytest.raises(ValueError): await hass.config.async_update(time_zone="not_a_timezone") @@ -1164,7 +1174,7 @@ async def test_track_task_functions(event_loop): await hass.async_stop() -async def test_service_executed_with_subservices(hass): +async def test_service_executed_with_subservices(hass: HomeAssistant) -> None: """Test we block correctly till all services done.""" calls = async_mock_service(hass, "test", "inner") context = ha.Context() @@ -1195,7 +1205,7 @@ async def test_service_executed_with_subservices(hass): assert all(call.context is context for call in calls) -async def test_service_call_event_contains_original_data(hass): +async def test_service_call_event_contains_original_data(hass: HomeAssistant) -> None: """Test that service call event contains original data.""" events = async_capture_events(hass, EVENT_CALL_SERVICE) @@ -1229,7 +1239,7 @@ def test_context() -> None: assert c.id is not None -async def test_async_functions_with_callback(hass): +async def test_async_functions_with_callback(hass: HomeAssistant) -> None: """Test we deal with async functions accidentally marked as callback.""" runs = [] @@ -1361,7 +1371,7 @@ async def test_incorrect_internal_external_url(hass, hass_storage, caplog): assert "Invalid internal_url set" in caplog.text -async def test_start_events(hass): +async def test_start_events(hass: HomeAssistant) -> None: """Test events fired when starting Home Assistant.""" hass.state = ha.CoreState.not_running @@ -1467,7 +1477,7 @@ async def test_chained_logging_misses_log_timeout(hass, caplog): assert "_task_chain_" not in caplog.text -async def test_async_all(hass): +async def test_async_all(hass: HomeAssistant) -> None: """Test async_all.""" hass.states.async_set("switch.link", "on") @@ -1490,7 +1500,7 @@ async def test_async_all(hass): } == {"light.bowl", "light.frog", "switch.link"} -async def test_async_entity_ids_count(hass): +async def test_async_entity_ids_count(hass: HomeAssistant) -> None: """Test async_entity_ids_count.""" hass.states.async_set("switch.link", "on") @@ -1522,7 +1532,7 @@ async def test_hassjob_forbid_coroutine() -> None: await coro -async def test_reserving_states(hass): +async def test_reserving_states(hass: HomeAssistant) -> None: """Test we can reserve a state in the state machine.""" hass.states.async_reserve("light.bedroom") @@ -1837,7 +1847,9 @@ def _ulid_timestamp(ulid: str) -> int: ) -async def test_state_change_events_context_id_match_state_time(hass): +async def test_state_change_events_context_id_match_state_time( + hass: HomeAssistant, +) -> None: """Test last_updated, timed_fired, and the ulid all have the same time.""" events = async_capture_events(hass, ha.EVENT_STATE_CHANGED) hass.states.async_set("light.bedroom", "on") @@ -1851,7 +1863,9 @@ async def test_state_change_events_context_id_match_state_time(hass): ) -async def test_state_firing_event_matches_context_id_ulid_time(hass): +async def test_state_firing_event_matches_context_id_ulid_time( + hass: HomeAssistant, +) -> None: """Test timed_fired and the ulid have the same time.""" events = async_capture_events(hass, EVENT_HOMEASSISTANT_STARTED) hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED) @@ -1865,7 +1879,7 @@ async def test_state_firing_event_matches_context_id_ulid_time(hass): ) -async def test_event_context(hass): +async def test_event_context(hass: HomeAssistant) -> None: """Test we can lookup the origin of a context from an event.""" events = [] @@ -1916,7 +1930,7 @@ def _get_by_type(full_name: str) -> list[Any]: reason="Takes too long on the CI", ) @patch.object(ha._LOGGER, "debug", lambda *args: None) -async def test_state_changed_events_to_not_leak_contexts(hass): +async def test_state_changed_events_to_not_leak_contexts(hass: HomeAssistant) -> None: """Test state changed events do not leak contexts.""" gc.collect() # Other tests can log Contexts which keep them in memory diff --git a/tests/test_data_entry_flow.py b/tests/test_data_entry_flow.py index f5871a95e7c..29bab8fbbcb 100644 --- a/tests/test_data_entry_flow.py +++ b/tests/test_data_entry_flow.py @@ -236,7 +236,7 @@ async def test_discovery_init_flow(manager): assert entry["source"] == config_entries.SOURCE_DISCOVERY -async def test_finish_callback_change_result_type(hass): +async def test_finish_callback_change_result_type(hass: HomeAssistant) -> None: """Test finish callback can change result type.""" class TestFlow(data_entry_flow.FlowHandler): diff --git a/tests/test_loader.py b/tests/test_loader.py index 1c39ae1e080..beb50e79bf9 100644 --- a/tests/test_loader.py +++ b/tests/test_loader.py @@ -11,7 +11,7 @@ from homeassistant.core import HomeAssistant, callback from .common import MockModule, mock_integration -async def test_component_dependencies(hass): +async def test_component_dependencies(hass: HomeAssistant) -> None: """Test if we can get the proper load order of components.""" mock_integration(hass, MockModule("mod1")) mock_integration(hass, MockModule("mod2", ["mod1"])) @@ -56,7 +56,7 @@ def test_component_loader_non_existing(hass: HomeAssistant) -> None: components.non_existing -async def test_component_wrapper(hass): +async def test_component_wrapper(hass: HomeAssistant) -> None: """Test component wrapper.""" components = loader.Components(hass) components.persistent_notification.async_create("message") @@ -64,7 +64,7 @@ async def test_component_wrapper(hass): assert len(hass.states.async_entity_ids("persistent_notification")) == 1 -async def test_helpers_wrapper(hass): +async def test_helpers_wrapper(hass: HomeAssistant) -> None: """Test helpers wrapper.""" helpers = loader.Helpers(hass) @@ -139,14 +139,14 @@ async def test_custom_integration_version_not_valid( ) in caplog.text -async def test_get_integration(hass): +async def test_get_integration(hass: HomeAssistant) -> None: """Test resolving integration.""" integration = await loader.async_get_integration(hass, "hue") assert hue == integration.get_component() assert hue_light == integration.get_platform("light") -async def test_get_integration_exceptions(hass): +async def test_get_integration_exceptions(hass: HomeAssistant) -> None: """Test resolving integration.""" integration = await loader.async_get_integration(hass, "hue") @@ -294,7 +294,7 @@ def test_integration_properties(hass: HomeAssistant) -> None: assert integration.ssdp is None -async def test_integrations_only_once(hass): +async def test_integrations_only_once(hass: HomeAssistant) -> None: """Test that we load integrations only once.""" int_1 = hass.async_create_task(loader.async_get_integration(hass, "hue")) int_2 = hass.async_create_task(loader.async_get_integration(hass, "hue")) @@ -479,7 +479,7 @@ async def test_get_custom_components(hass, enable_custom_integrations): mock_get.assert_called_once_with(hass) -async def test_get_config_flows(hass): +async def test_get_config_flows(hass: HomeAssistant) -> None: """Verify that custom components with config_flow are available.""" test_1_integration = _get_test_integration(hass, "test_1", False) test_2_integration = _get_test_integration(hass, "test_2", True) @@ -494,7 +494,7 @@ async def test_get_config_flows(hass): assert "test_1" not in flows -async def test_get_zeroconf(hass): +async def test_get_zeroconf(hass: HomeAssistant) -> None: """Verify that custom components with zeroconf are found.""" test_1_integration = _get_test_integration(hass, "test_1", True) test_2_integration = _get_test_integration_with_zeroconf_matcher( @@ -513,7 +513,7 @@ async def test_get_zeroconf(hass): ] -async def test_get_application_credentials(hass): +async def test_get_application_credentials(hass: HomeAssistant) -> None: """Verify that custom components with application_credentials are found.""" test_1_integration = _get_test_integration(hass, "test_1", True) test_2_integration = _get_test_integration_with_application_credentials( @@ -530,7 +530,7 @@ async def test_get_application_credentials(hass): assert "test_1" not in application_credentials -async def test_get_zeroconf_back_compat(hass): +async def test_get_zeroconf_back_compat(hass: HomeAssistant) -> None: """Verify that custom components with zeroconf are found and legacy matchers are converted.""" test_1_integration = _get_test_integration(hass, "test_1", True) test_2_integration = _get_test_integration_with_legacy_zeroconf_matcher( @@ -557,7 +557,7 @@ async def test_get_zeroconf_back_compat(hass): ] -async def test_get_bluetooth(hass): +async def test_get_bluetooth(hass: HomeAssistant) -> None: """Verify that custom components with bluetooth are found.""" test_1_integration = _get_test_integration_with_bluetooth_matcher( hass, "test_1", True @@ -577,7 +577,7 @@ async def test_get_bluetooth(hass): ] -async def test_get_dhcp(hass): +async def test_get_dhcp(hass: HomeAssistant) -> None: """Verify that custom components with dhcp are found.""" test_1_integration = _get_test_integration_with_dhcp_matcher(hass, "test_1", True) @@ -594,7 +594,7 @@ async def test_get_dhcp(hass): ] -async def test_get_usb(hass): +async def test_get_usb(hass: HomeAssistant) -> None: """Verify that custom components with usb matchers are found.""" test_1_integration = _get_test_integration_with_usb_matcher(hass, "test_1", True) @@ -612,7 +612,7 @@ async def test_get_usb(hass): ] -async def test_get_homekit(hass): +async def test_get_homekit(hass: HomeAssistant) -> None: """Verify that custom components with homekit are found.""" test_1_integration = _get_test_integration(hass, "test_1", True) test_2_integration = _get_test_integration(hass, "test_2", True) @@ -627,7 +627,7 @@ async def test_get_homekit(hass): assert homekit["test_2"] == "test_2" -async def test_get_ssdp(hass): +async def test_get_ssdp(hass: HomeAssistant) -> None: """Verify that custom components with ssdp are found.""" test_1_integration = _get_test_integration(hass, "test_1", True) test_2_integration = _get_test_integration(hass, "test_2", True) @@ -642,7 +642,7 @@ async def test_get_ssdp(hass): assert ssdp["test_2"] == [{"manufacturer": "test_2", "modelName": "test_2"}] -async def test_get_mqtt(hass): +async def test_get_mqtt(hass: HomeAssistant) -> None: """Verify that custom components with MQTT are found.""" test_1_integration = _get_test_integration(hass, "test_1", True) test_2_integration = _get_test_integration(hass, "test_2", True) @@ -657,7 +657,7 @@ async def test_get_mqtt(hass): assert mqtt["test_2"] == ["test_2/discovery"] -async def test_get_custom_components_safe_mode(hass): +async def test_get_custom_components_safe_mode(hass: HomeAssistant) -> None: """Test that we get empty custom components in safe mode.""" hass.config.safe_mode = True assert await loader.async_get_custom_components(hass) == {} @@ -684,13 +684,13 @@ async def test_custom_integration_missing(hass, caplog): await loader.async_get_integration(hass, "test1") -async def test_validation(hass): +async def test_validation(hass: HomeAssistant) -> None: """Test we raise if invalid domain passed in.""" with pytest.raises(ValueError): await loader.async_get_integration(hass, "some.thing") -async def test_loggers(hass): +async def test_loggers(hass: HomeAssistant) -> None: """Test we can fetch the loggers from the integration.""" name = "dummy" integration = loader.Integration( diff --git a/tests/test_requirements.py b/tests/test_requirements.py index daf2c0902df..5fd54959ef4 100644 --- a/tests/test_requirements.py +++ b/tests/test_requirements.py @@ -6,6 +6,7 @@ from unittest.mock import call, patch import pytest from homeassistant import loader, setup +from homeassistant.core import HomeAssistant from homeassistant.requirements import ( CONSTRAINT_FILE, RequirementsNotFound, @@ -24,7 +25,7 @@ def env_without_wheel_links(): return env -async def test_requirement_installed_in_venv(hass): +async def test_requirement_installed_in_venv(hass: HomeAssistant) -> None: """Test requirement installed in virtual environment.""" with patch("os.path.dirname", return_value="ha_package_path"), patch( "homeassistant.util.package.is_virtual_env", return_value=True @@ -45,7 +46,7 @@ async def test_requirement_installed_in_venv(hass): ) -async def test_requirement_installed_in_deps(hass): +async def test_requirement_installed_in_deps(hass: HomeAssistant) -> None: """Test requirement installed in deps directory.""" with patch("os.path.dirname", return_value="ha_package_path"), patch( "homeassistant.util.package.is_virtual_env", return_value=False @@ -67,7 +68,7 @@ async def test_requirement_installed_in_deps(hass): ) -async def test_install_existing_package(hass): +async def test_install_existing_package(hass: HomeAssistant) -> None: """Test an install attempt on an existing package.""" with patch( "homeassistant.util.package.install_package", return_value=True @@ -84,7 +85,7 @@ async def test_install_existing_package(hass): assert len(mock_inst.mock_calls) == 0 -async def test_install_missing_package(hass): +async def test_install_missing_package(hass: HomeAssistant) -> None: """Test an install attempt on an existing package.""" with patch( "homeassistant.util.package.install_package", return_value=False @@ -111,7 +112,7 @@ async def test_install_skipped_package(hass, caplog): assert mock_inst.mock_calls[0].args[0] == "not_skipped==1.2.3" -async def test_get_integration_with_requirements(hass): +async def test_get_integration_with_requirements(hass: HomeAssistant) -> None: """Check getting an integration with loaded requirements.""" hass.config.skip_pip = False mock_integration( @@ -159,7 +160,9 @@ async def test_get_integration_with_requirements(hass): ] -async def test_get_integration_with_requirements_pip_install_fails_two_passes(hass): +async def test_get_integration_with_requirements_pip_install_fails_two_passes( + hass: HomeAssistant, +) -> None: """Check getting an integration with loaded requirements and the pip install fails two passes.""" hass.config.skip_pip = False mock_integration( @@ -289,7 +292,7 @@ async def test_get_integration_with_requirements_pip_install_fails_two_passes(ha ] -async def test_get_integration_with_missing_dependencies(hass): +async def test_get_integration_with_missing_dependencies(hass: HomeAssistant) -> None: """Check getting an integration with missing dependencies.""" hass.config.skip_pip = False mock_integration( @@ -319,7 +322,9 @@ async def test_get_integration_with_missing_dependencies(hass): await async_get_integration_with_requirements(hass, "test_custom_component") -async def test_get_built_in_integration_with_missing_after_dependencies(hass): +async def test_get_built_in_integration_with_missing_after_dependencies( + hass: HomeAssistant, +) -> None: """Check getting a built_in integration with missing after_dependencies results in exception.""" hass.config.skip_pip = False mock_integration( @@ -334,7 +339,9 @@ async def test_get_built_in_integration_with_missing_after_dependencies(hass): await async_get_integration_with_requirements(hass, "test_component") -async def test_get_custom_integration_with_missing_after_dependencies(hass): +async def test_get_custom_integration_with_missing_after_dependencies( + hass: HomeAssistant, +) -> None: """Check getting a custom integration with missing after_dependencies.""" hass.config.skip_pip = False mock_integration( @@ -352,7 +359,7 @@ async def test_get_custom_integration_with_missing_after_dependencies(hass): assert integration.domain == "test_custom_component" -async def test_install_with_wheels_index(hass): +async def test_install_with_wheels_index(hass: HomeAssistant) -> None: """Test an install attempt with wheels index URL.""" hass.config.skip_pip = False mock_integration(hass, MockModule("comp", requirements=["hello==1.0.0"])) @@ -377,7 +384,7 @@ async def test_install_with_wheels_index(hass): ) -async def test_install_on_docker(hass): +async def test_install_on_docker(hass: HomeAssistant) -> None: """Test an install attempt on an docker system env.""" hass.config.skip_pip = False mock_integration(hass, MockModule("comp", requirements=["hello==1.0.0"])) @@ -401,7 +408,7 @@ async def test_install_on_docker(hass): ) -async def test_discovery_requirements_mqtt(hass): +async def test_discovery_requirements_mqtt(hass: HomeAssistant) -> None: """Test that we load discovery requirements.""" hass.config.skip_pip = False mqtt = await loader.async_get_integration(hass, "mqtt") @@ -418,7 +425,7 @@ async def test_discovery_requirements_mqtt(hass): assert mock_process.mock_calls[0][1][1] == mqtt.requirements -async def test_discovery_requirements_ssdp(hass): +async def test_discovery_requirements_ssdp(hass: HomeAssistant) -> None: """Test that we load discovery requirements.""" hass.config.skip_pip = False ssdp = await loader.async_get_integration(hass, "ssdp") @@ -465,7 +472,7 @@ async def test_discovery_requirements_zeroconf(hass, partial_manifest): assert mock_process.mock_calls[0][1][1] == zeroconf.requirements -async def test_discovery_requirements_dhcp(hass): +async def test_discovery_requirements_dhcp(hass: HomeAssistant) -> None: """Test that we load dhcp discovery requirements.""" hass.config.skip_pip = False dhcp = await loader.async_get_integration(hass, "dhcp") diff --git a/tests/test_setup.py b/tests/test_setup.py index db6717dad99..29794bb1100 100644 --- a/tests/test_setup.py +++ b/tests/test_setup.py @@ -10,7 +10,7 @@ import voluptuous as vol from homeassistant import config_entries, setup from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START -from homeassistant.core import callback +from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( @@ -41,7 +41,7 @@ def mock_handlers(): yield -async def test_validate_component_config(hass): +async def test_validate_component_config(hass: HomeAssistant) -> None: """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration(hass, MockModule("comp_conf", config_schema=config_schema)) @@ -198,7 +198,7 @@ async def test_validate_platform_config_3(hass, caplog): ) -async def test_validate_platform_config_4(hass): +async def test_validate_platform_config_4(hass: HomeAssistant) -> None: """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA @@ -230,12 +230,12 @@ async def test_validate_platform_config_4(hass): hass.config.components.remove("platform_conf") -async def test_component_not_found(hass): +async def test_component_not_found(hass: HomeAssistant) -> None: """setup_component should not crash if component doesn't exist.""" assert await setup.async_setup_component(hass, "non_existing", {}) is False -async def test_component_not_double_initialized(hass): +async def test_component_not_double_initialized(hass: HomeAssistant) -> None: """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) @@ -250,7 +250,9 @@ async def test_component_not_double_initialized(hass): assert not mock_setup.called -async def test_component_not_installed_if_requirement_fails(hass): +async def test_component_not_installed_if_requirement_fails( + hass: HomeAssistant, +) -> None: """Component setup should fail if requirement can't install.""" hass.config.skip_pip = False mock_integration(hass, MockModule("comp", requirements=["package==0.0.1"])) @@ -261,7 +263,9 @@ async def test_component_not_installed_if_requirement_fails(hass): assert "comp" not in hass.config.components -async def test_component_not_setup_twice_if_loaded_during_other_setup(hass): +async def test_component_not_setup_twice_if_loaded_during_other_setup( + hass: HomeAssistant, +) -> None: """Test component setup while waiting for lock is not set up twice.""" result = [] @@ -284,7 +288,7 @@ async def test_component_not_setup_twice_if_loaded_during_other_setup(hass): assert len(result) == 1 -async def test_component_not_setup_missing_dependencies(hass): +async def test_component_not_setup_missing_dependencies(hass: HomeAssistant) -> None: """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(hass, MockModule("comp", dependencies=deps)) @@ -300,7 +304,7 @@ async def test_component_not_setup_missing_dependencies(hass): assert await setup.async_setup_component(hass, "comp2", {}) -async def test_component_failing_setup(hass): +async def test_component_failing_setup(hass: HomeAssistant) -> None: """Test component that fails setup.""" mock_integration(hass, MockModule("comp", setup=lambda hass, config: False)) @@ -308,7 +312,7 @@ async def test_component_failing_setup(hass): assert "comp" not in hass.config.components -async def test_component_exception_setup(hass): +async def test_component_exception_setup(hass: HomeAssistant) -> None: """Test component that raises exception during setup.""" def exception_setup(hass, config): @@ -321,7 +325,9 @@ async def test_component_exception_setup(hass): assert "comp" not in hass.config.components -async def test_component_setup_with_validation_and_dependency(hass): +async def test_component_setup_with_validation_and_dependency( + hass: HomeAssistant, +) -> None: """Test all config is passed to dependencies.""" def config_check_setup(hass, config): @@ -349,7 +355,7 @@ async def test_component_setup_with_validation_and_dependency(hass): assert "comp_a" in hass.config.components -async def test_platform_specific_config_validation(hass): +async def test_platform_specific_config_validation(hass: HomeAssistant) -> None: """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend({"valid": True}, extra=vol.PREVENT_EXTRA) @@ -401,7 +407,7 @@ async def test_platform_specific_config_validation(hass): assert mock_setup.call_count == 1 -async def test_disable_component_if_invalid_return(hass): +async def test_disable_component_if_invalid_return(hass: HomeAssistant) -> None: """Test disabling component if invalid return.""" mock_integration( hass, MockModule("disabled_component", setup=lambda hass, config: None) @@ -428,7 +434,7 @@ async def test_disable_component_if_invalid_return(hass): assert "disabled_component" in hass.config.components -async def test_all_work_done_before_start(hass): +async def test_all_work_done_before_start(hass: HomeAssistant) -> None: """Test all init work done till start.""" call_order = [] @@ -466,7 +472,7 @@ async def test_all_work_done_before_start(hass): assert call_order == [1, 1, 2] -async def test_component_warn_slow_setup(hass): +async def test_component_warn_slow_setup(hass: HomeAssistant) -> None: """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: @@ -483,7 +489,7 @@ async def test_component_warn_slow_setup(hass): assert mock_call().cancel.called -async def test_platform_no_warn_slow(hass): +async def test_platform_no_warn_slow(hass: HomeAssistant) -> None: """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) @@ -512,7 +518,7 @@ async def test_platform_error_slow_setup(hass, caplog): assert "test_component1 is taking longer than 0.1 seconds" in caplog.text -async def test_when_setup_already_loaded(hass): +async def test_when_setup_already_loaded(hass: HomeAssistant) -> None: """Test when setup.""" calls = [] @@ -540,7 +546,7 @@ async def test_when_setup_already_loaded(hass): assert calls == ["test", "test"] -async def test_async_when_setup_or_start_already_loaded(hass): +async def test_async_when_setup_or_start_already_loaded(hass: HomeAssistant) -> None: """Test when setup or start.""" calls = [] @@ -575,7 +581,7 @@ async def test_async_when_setup_or_start_already_loaded(hass): assert calls == ["test", "test", "not_loaded"] -async def test_setup_import_blows_up(hass): +async def test_setup_import_blows_up(hass: HomeAssistant) -> None: """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ImportError @@ -638,7 +644,7 @@ async def test_integration_logs_is_custom(hass, caplog): assert "Setup failed for custom integration test_component1: Boom" in caplog.text -async def test_async_get_loaded_integrations(hass): +async def test_async_get_loaded_integrations(hass: HomeAssistant) -> None: """Test we can enumerate loaded integrations.""" hass.config.components.add("notbase") hass.config.components.add("switch") @@ -669,7 +675,7 @@ async def test_integration_no_setup(hass, caplog): assert "No setup or config entry setup function defined" in caplog.text -async def test_integration_only_setup_entry(hass): +async def test_integration_only_setup_entry(hass: HomeAssistant) -> None: """Test we have an integration with only a setup entry method.""" mock_integration( hass, @@ -682,7 +688,7 @@ async def test_integration_only_setup_entry(hass): assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) -async def test_async_start_setup(hass): +async def test_async_start_setup(hass: HomeAssistant) -> None: """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( @@ -698,7 +704,7 @@ async def test_async_start_setup(hass): assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] -async def test_async_start_setup_platforms(hass): +async def test_async_start_setup_platforms(hass: HomeAssistant) -> None: """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( diff --git a/tests/test_test_fixtures.py b/tests/test_test_fixtures.py index 936e2c9a7f2..7b07e8472bf 100644 --- a/tests/test_test_fixtures.py +++ b/tests/test_test_fixtures.py @@ -4,7 +4,7 @@ import socket import pytest import pytest_socket -from homeassistant.core import async_get_hass +from homeassistant.core import HomeAssistant, async_get_hass def test_sockets_disabled() -> None: @@ -20,7 +20,7 @@ def test_sockets_enabled(socket_enabled): mysocket.connect(("127.0.0.2", 1234)) -async def test_hass_cv(hass): +async def test_hass_cv(hass: HomeAssistant) -> None: """Test hass context variable. When tests are using the `hass`, this tests that the hass context variable was set diff --git a/tests/util/test_async.py b/tests/util/test_async.py index d731b3951c3..37abd87c2a1 100644 --- a/tests/util/test_async.py +++ b/tests/util/test_async.py @@ -6,6 +6,7 @@ from unittest.mock import MagicMock, Mock, patch import pytest from homeassistant import block_async_io +from homeassistant.core import HomeAssistant from homeassistant.util import async_ as hasync @@ -239,7 +240,7 @@ async def test_gather_with_concurrency() -> None: assert results == [2, 2, -1, -1] -async def test_shutdown_run_callback_threadsafe(hass): +async def test_shutdown_run_callback_threadsafe(hass: HomeAssistant) -> None: """Test we can shutdown run_callback_threadsafe.""" hasync.shutdown_run_callback_threadsafe(hass.loop) callback = MagicMock() @@ -248,7 +249,7 @@ async def test_shutdown_run_callback_threadsafe(hass): hasync.run_callback_threadsafe(hass.loop, callback) -async def test_run_callback_threadsafe(hass): +async def test_run_callback_threadsafe(hass: HomeAssistant) -> None: """Test run_callback_threadsafe runs code in the event loop.""" it_ran = False @@ -265,7 +266,7 @@ async def test_run_callback_threadsafe(hass): assert it_ran is True -async def test_callback_is_always_scheduled(hass): +async def test_callback_is_always_scheduled(hass: HomeAssistant) -> None: """Test run_callback_threadsafe always calls call_soon_threadsafe before checking for shutdown.""" # We have to check the shutdown state AFTER the callback is scheduled otherwise # the function could continue on and the caller call `future.result()` after diff --git a/tests/util/test_logging.py b/tests/util/test_logging.py index a3e5a472663..2a2e0107a83 100644 --- a/tests/util/test_logging.py +++ b/tests/util/test_logging.py @@ -7,7 +7,7 @@ from unittest.mock import patch import pytest -from homeassistant.core import callback, is_callback +from homeassistant.core import HomeAssistant, callback, is_callback import homeassistant.util.logging as logging_util @@ -62,7 +62,7 @@ async def test_logging_with_queue_handler() -> None: assert simple_queue.empty() -async def test_migrate_log_handler(hass): +async def test_migrate_log_handler(hass: HomeAssistant) -> None: """Test migrating log handlers.""" logging_util.async_activate_log_queue_handler(hass) diff --git a/tests/util/test_thread.py b/tests/util/test_thread.py index 9717935afc4..0c04919c31f 100644 --- a/tests/util/test_thread.py +++ b/tests/util/test_thread.py @@ -5,12 +5,13 @@ from unittest.mock import Mock, patch import pytest +from homeassistant.core import HomeAssistant from homeassistant.util import thread from homeassistant.util.async_ import run_callback_threadsafe from homeassistant.util.thread import ThreadWithException -async def test_thread_with_exception_invalid(hass): +async def test_thread_with_exception_invalid(hass: HomeAssistant) -> None: """Test throwing an invalid thread exception.""" finish_event = asyncio.Event() @@ -27,7 +28,7 @@ async def test_thread_with_exception_invalid(hass): test_thread.join() -async def test_thread_not_started(hass): +async def test_thread_not_started(hass: HomeAssistant) -> None: """Test throwing when the thread is not started.""" test_thread = ThreadWithException(target=lambda *_: None) @@ -36,7 +37,7 @@ async def test_thread_not_started(hass): test_thread.raise_exc(TimeoutError) -async def test_thread_fails_raise(hass): +async def test_thread_fails_raise(hass: HomeAssistant) -> None: """Test throwing after already ended.""" finish_event = asyncio.Event() diff --git a/tests/util/test_timeout.py b/tests/util/test_timeout.py index 6fbf8a1ea84..74a20c0c100 100644 --- a/tests/util/test_timeout.py +++ b/tests/util/test_timeout.py @@ -5,6 +5,7 @@ import time import pytest +from homeassistant.core import HomeAssistant from homeassistant.util.timeout import TimeoutManager @@ -17,7 +18,7 @@ async def test_simple_global_timeout() -> None: await asyncio.sleep(0.3) -async def test_simple_global_timeout_with_executor_job(hass): +async def test_simple_global_timeout_with_executor_job(hass: HomeAssistant) -> None: """Test a simple global timeout with executor job.""" timeout = TimeoutManager() @@ -35,7 +36,9 @@ async def test_simple_global_timeout_freeze() -> None: await asyncio.sleep(0.3) -async def test_simple_zone_timeout_freeze_inside_executor_job(hass): +async def test_simple_zone_timeout_freeze_inside_executor_job( + hass: HomeAssistant, +) -> None: """Test a simple zone timeout freeze inside an executor job.""" timeout = TimeoutManager() @@ -48,7 +51,9 @@ async def test_simple_zone_timeout_freeze_inside_executor_job(hass): await hass.async_add_executor_job(_some_sync_work) -async def test_simple_global_timeout_freeze_inside_executor_job(hass): +async def test_simple_global_timeout_freeze_inside_executor_job( + hass: HomeAssistant, +) -> None: """Test a simple global timeout freeze inside an executor job.""" timeout = TimeoutManager() @@ -60,7 +65,9 @@ async def test_simple_global_timeout_freeze_inside_executor_job(hass): await hass.async_add_executor_job(_some_sync_work) -async def test_mix_global_timeout_freeze_and_zone_freeze_inside_executor_job(hass): +async def test_mix_global_timeout_freeze_and_zone_freeze_inside_executor_job( + hass: HomeAssistant, +) -> None: """Test a simple global timeout freeze inside an executor job.""" timeout = TimeoutManager() @@ -73,7 +80,9 @@ async def test_mix_global_timeout_freeze_and_zone_freeze_inside_executor_job(has await hass.async_add_executor_job(_some_sync_work) -async def test_mix_global_timeout_freeze_and_zone_freeze_different_order(hass): +async def test_mix_global_timeout_freeze_and_zone_freeze_different_order( + hass: HomeAssistant, +) -> None: """Test a simple global timeout freeze inside an executor job before timeout was set.""" timeout = TimeoutManager() @@ -121,7 +130,9 @@ async def test_mix_global_timeout_freeze_and_zone_freeze_inside_executor_job_sec await hass.async_add_executor_job(lambda: time.sleep(0.2)) -async def test_simple_global_timeout_freeze_with_executor_job(hass): +async def test_simple_global_timeout_freeze_with_executor_job( + hass: HomeAssistant, +) -> None: """Test a simple global timeout freeze with executor job.""" timeout = TimeoutManager() @@ -263,7 +274,9 @@ async def test_mix_zone_timeout_trigger_global_cool_down() -> None: await asyncio.sleep(0.2) -async def test_simple_zone_timeout_freeze_without_timeout_cleanup(hass): +async def test_simple_zone_timeout_freeze_without_timeout_cleanup( + hass: HomeAssistant, +) -> None: """Test a simple zone timeout freeze on a zone that does not have a timeout set.""" timeout = TimeoutManager() @@ -276,7 +289,9 @@ async def test_simple_zone_timeout_freeze_without_timeout_cleanup(hass): await asyncio.sleep(0.2) -async def test_simple_zone_timeout_freeze_without_timeout_cleanup2(hass): +async def test_simple_zone_timeout_freeze_without_timeout_cleanup2( + hass: HomeAssistant, +) -> None: """Test a simple zone timeout freeze on a zone that does not have a timeout set.""" timeout = TimeoutManager()