diff --git a/tests/auth/test_auth_store.py b/tests/auth/test_auth_store.py index 8250d94f6de..860abe76577 100644 --- a/tests/auth/test_auth_store.py +++ b/tests/auth/test_auth_store.py @@ -1,12 +1,15 @@ """Tests for the auth store.""" import asyncio +from typing import Any 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): +async def test_loading_no_group_data_format( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test we correctly load old data without any groups.""" hass_storage[auth_store.STORAGE_KEY] = { "version": 1, @@ -99,7 +102,9 @@ async def test_loading_no_group_data_format(hass, hass_storage): assert system_token.version is None -async def test_loading_all_access_group_data_format(hass, hass_storage): +async def test_loading_all_access_group_data_format( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test we correctly load old data with single group.""" hass_storage[auth_store.STORAGE_KEY] = { "version": 1, @@ -195,7 +200,9 @@ async def test_loading_all_access_group_data_format(hass, hass_storage): assert system_token.version is None -async def test_loading_empty_data(hass, hass_storage): +async def test_loading_empty_data( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test we correctly load with no existing data.""" store = auth_store.AuthStore(hass) groups = await store.async_get_groups() @@ -217,7 +224,9 @@ async def test_loading_empty_data(hass, hass_storage): assert len(users) == 0 -async def test_system_groups_store_id_and_name(hass, hass_storage): +async def test_system_groups_store_id_and_name( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test that for system groups we store the ID and name. Name is stored so that we remain backwards compat with < 0.82. diff --git a/tests/auth/test_init.py b/tests/auth/test_init.py index 0f602a0e547..3d3674e1373 100644 --- a/tests/auth/test_init.py +++ b/tests/auth/test_init.py @@ -1,5 +1,6 @@ """Tests for the Home Assistant auth module.""" from datetime import timedelta +from typing import Any from unittest.mock import Mock, patch import jwt @@ -15,6 +16,7 @@ from homeassistant.auth import ( models as auth_models, ) from homeassistant.auth.const import GROUP_ID_ADMIN, MFA_SESSION_EXPIRATION +from homeassistant.auth.models import Credentials from homeassistant.core import HomeAssistant, callback from homeassistant.util import dt as dt_util @@ -35,7 +37,7 @@ def mock_hass(event_loop): return hass -async def test_auth_manager_from_config_validates_config(mock_hass): +async def test_auth_manager_from_config_validates_config(mock_hass) -> None: """Test get auth providers.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( @@ -76,7 +78,7 @@ async def test_auth_manager_from_config_validates_config(mock_hass): ] -async def test_auth_manager_from_config_auth_modules(mock_hass): +async def test_auth_manager_from_config_auth_modules(mock_hass) -> None: """Test get auth modules.""" with pytest.raises(vol.Invalid): manager = await auth.auth_manager_from_config( @@ -187,7 +189,7 @@ async def test_create_new_user(hass: HomeAssistant) -> None: assert events[0].data["user_id"] == user.id -async def test_login_as_existing_user(mock_hass): +async def test_login_as_existing_user(mock_hass) -> None: """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, @@ -253,7 +255,9 @@ async def test_login_as_existing_user(mock_hass): assert user.name == "Paulus" -async def test_linking_user_to_two_auth_providers(hass, hass_storage): +async def test_linking_user_to_two_auth_providers( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test linking user to two auth providers.""" manager = await auth.auth_manager_from_config( hass, @@ -300,7 +304,9 @@ async def test_linking_user_to_two_auth_providers(hass, hass_storage): assert len(user_2.credentials) == 0 -async def test_saving_loading(hass, hass_storage): +async def test_saving_loading( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test storing and saving data. Creates one of each type that we store to test we restore correctly. @@ -506,7 +512,7 @@ async def test_refresh_token_type_long_lived_access_token(hass: HomeAssistant) - assert token.token_type == auth_models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN -async def test_refresh_token_provider_validation(mock_hass): +async def test_refresh_token_provider_validation(mock_hass) -> None: """Test that creating access token from refresh token checks with provider.""" manager = await auth.auth_manager_from_config( mock_hass, @@ -545,7 +551,7 @@ async def test_refresh_token_provider_validation(mock_hass): call.assert_called_with(refresh_token, ip) -async def test_cannot_deactive_owner(mock_hass): +async def test_cannot_deactive_owner(mock_hass) -> None: """Test that we cannot deactivate the owner.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) owner = MockUser(is_owner=True).add_to_auth_manager(manager) @@ -554,7 +560,7 @@ async def test_cannot_deactive_owner(mock_hass): await manager.async_deactivate_user(owner) -async def test_remove_refresh_token(mock_hass): +async def test_remove_refresh_token(mock_hass) -> None: """Test that we can remove a refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) @@ -567,7 +573,7 @@ async def test_remove_refresh_token(mock_hass): assert await manager.async_validate_access_token(access_token) is None -async def test_register_revoke_token_callback(mock_hass): +async def test_register_revoke_token_callback(mock_hass) -> None: """Test that a registered revoke token callback is called.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) @@ -584,7 +590,7 @@ async def test_register_revoke_token_callback(mock_hass): assert called -async def test_unregister_revoke_token_callback(mock_hass): +async def test_unregister_revoke_token_callback(mock_hass) -> None: """Test that a revoke token callback can be unregistered.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) @@ -603,7 +609,7 @@ async def test_unregister_revoke_token_callback(mock_hass): assert not called -async def test_create_access_token(mock_hass): +async def test_create_access_token(mock_hass) -> None: """Test normal refresh_token's jwt_key keep same after used.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) @@ -620,7 +626,7 @@ async def test_create_access_token(mock_hass): ) -async def test_create_long_lived_access_token(mock_hass): +async def test_create_long_lived_access_token(mock_hass) -> None: """Test refresh_token's jwt_key changed for long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) @@ -639,7 +645,7 @@ async def test_create_long_lived_access_token(mock_hass): ) -async def test_one_long_lived_access_token_per_refresh_token(mock_hass): +async def test_one_long_lived_access_token_per_refresh_token(mock_hass) -> None: """Test one refresh_token can only have one long-lived access token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) @@ -691,7 +697,7 @@ async def test_one_long_lived_access_token_per_refresh_token(mock_hass): ) -async def test_login_with_auth_module(mock_hass): +async def test_login_with_auth_module(mock_hass) -> None: """Test login as existing user with auth module.""" manager = await auth.auth_manager_from_config( mock_hass, @@ -761,7 +767,7 @@ async def test_login_with_auth_module(mock_hass): assert step["result"].id == "mock-id" -async def test_login_with_multi_auth_module(mock_hass): +async def test_login_with_multi_auth_module(mock_hass) -> None: """Test login as existing user with multiple auth modules.""" manager = await auth.auth_manager_from_config( mock_hass, @@ -834,7 +840,7 @@ async def test_login_with_multi_auth_module(mock_hass): assert step["result"].id == "mock-id" -async def test_auth_module_expired_session(mock_hass): +async def test_auth_module_expired_session(mock_hass) -> None: """Test login as existing user.""" manager = await auth.auth_manager_from_config( mock_hass, @@ -896,7 +902,9 @@ async def test_auth_module_expired_session(mock_hass): assert step["reason"] == "login_expired" -async def test_enable_mfa_for_user(hass, hass_storage): +async def test_enable_mfa_for_user( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test enable mfa module for user.""" manager = await auth.auth_manager_from_config( hass, @@ -1015,8 +1023,8 @@ async def test_async_remove_user(hass: HomeAssistant) -> None: async def test_async_remove_user_fail_if_remove_credential_fails( - hass, hass_admin_user, hass_admin_credential -): + hass: HomeAssistant, hass_admin_user: MockUser, hass_admin_credential: Credentials +) -> None: """Test removing a user.""" await hass.auth.async_link_user(hass_admin_user, hass_admin_credential) @@ -1026,7 +1034,7 @@ async def test_async_remove_user_fail_if_remove_credential_fails( await hass.auth.async_remove_user(hass_admin_user) -async def test_new_users(mock_hass): +async def test_new_users(mock_hass) -> None: """Test newly created users.""" manager = await auth.auth_manager_from_config( mock_hass, @@ -1086,7 +1094,7 @@ async def test_new_users(mock_hass): assert user_cred.is_admin -async def test_rename_does_not_change_refresh_token(mock_hass): +async def test_rename_does_not_change_refresh_token(mock_hass) -> None: """Test that we can rename without changing refresh token.""" manager = await auth.auth_manager_from_config(mock_hass, [], []) user = MockUser().add_to_auth_manager(manager) diff --git a/tests/hassfest/test_dependencies.py b/tests/hassfest/test_dependencies.py index dcef6d34844..98ccbe4eae6 100644 --- a/tests/hassfest/test_dependencies.py +++ b/tests/hassfest/test_dependencies.py @@ -15,7 +15,7 @@ def mock_collector(): return collector -def test_child_import(mock_collector): +def test_child_import(mock_collector) -> None: """Test detecting a child_import reference.""" mock_collector.visit( ast.parse( @@ -27,7 +27,7 @@ from homeassistant.components import child_import assert mock_collector.unfiltered_referenced == {"child_import"} -def test_subimport(mock_collector): +def test_subimport(mock_collector) -> None: """Test detecting a subimport reference.""" mock_collector.visit( ast.parse( @@ -39,7 +39,7 @@ from homeassistant.components.subimport.smart_home import EVENT_ALEXA_SMART_HOME assert mock_collector.unfiltered_referenced == {"subimport"} -def test_child_import_field(mock_collector): +def test_child_import_field(mock_collector) -> None: """Test detecting a child_import_field reference.""" mock_collector.visit( ast.parse( @@ -51,7 +51,7 @@ from homeassistant.components.child_import_field import bla assert mock_collector.unfiltered_referenced == {"child_import_field"} -def test_renamed_absolute(mock_collector): +def test_renamed_absolute(mock_collector) -> None: """Test detecting a renamed_absolute reference.""" mock_collector.visit( ast.parse( @@ -63,7 +63,7 @@ import homeassistant.components.renamed_absolute as hue assert mock_collector.unfiltered_referenced == {"renamed_absolute"} -def test_hass_components_var(mock_collector): +def test_hass_components_var(mock_collector) -> None: """Test detecting a hass_components_var reference.""" mock_collector.visit( ast.parse( @@ -76,7 +76,7 @@ def bla(hass): assert mock_collector.unfiltered_referenced == {"hass_components_var"} -def test_hass_components_class(mock_collector): +def test_hass_components_class(mock_collector) -> None: """Test detecting a hass_components_class reference.""" mock_collector.visit( ast.parse( @@ -90,7 +90,7 @@ class Hello: assert mock_collector.unfiltered_referenced == {"hass_components_class"} -def test_all_imports(mock_collector): +def test_all_imports(mock_collector) -> None: """Test all imports together.""" mock_collector.visit( ast.parse( diff --git a/tests/hassfest/test_requirements.py b/tests/hassfest/test_requirements.py index 174bf841788..e6b247047e2 100644 --- a/tests/hassfest/test_requirements.py +++ b/tests/hassfest/test_requirements.py @@ -23,7 +23,7 @@ def integration(): return integration -def test_validate_requirements_format_with_space(integration: Integration): +def test_validate_requirements_format_with_space(integration: Integration) -> None: """Test validate requirement with space around separator.""" integration.manifest["requirements"] = ["test_package == 1"] assert not validate_requirements_format(integration) @@ -33,7 +33,7 @@ def test_validate_requirements_format_with_space(integration: Integration): ] -def test_validate_requirements_format_wrongly_pinned(integration: Integration): +def test_validate_requirements_format_wrongly_pinned(integration: Integration) -> None: """Test requirement with loose pin.""" integration.manifest["requirements"] = ["test_package>=1"] assert not validate_requirements_format(integration) @@ -43,7 +43,9 @@ def test_validate_requirements_format_wrongly_pinned(integration: Integration): ] -def test_validate_requirements_format_ignore_pin_for_custom(integration: Integration): +def test_validate_requirements_format_ignore_pin_for_custom( + integration: Integration, +) -> None: """Test requirement ignore pinning for custom.""" integration.manifest["requirements"] = [ "test_package>=1", @@ -59,7 +61,7 @@ def test_validate_requirements_format_ignore_pin_for_custom(integration: Integra assert len(integration.errors) == 0 -def test_validate_requirements_format_invalid_version(integration: Integration): +def test_validate_requirements_format_invalid_version(integration: Integration) -> None: """Test requirement with invalid version.""" integration.manifest["requirements"] = ["test_package==invalid"] assert not validate_requirements_format(integration) @@ -69,7 +71,7 @@ def test_validate_requirements_format_invalid_version(integration: Integration): ] -def test_validate_requirements_format_successful(integration: Integration): +def test_validate_requirements_format_successful(integration: Integration) -> None: """Test requirement with successful result.""" integration.manifest["requirements"] = [ "test_package==1.2.3", diff --git a/tests/hassfest/test_version.py b/tests/hassfest/test_version.py index eee184404b8..f473e988027 100644 --- a/tests/hassfest/test_version.py +++ b/tests/hassfest/test_version.py @@ -22,7 +22,7 @@ def integration(): return integration -def test_validate_version_no_key(integration: Integration): +def test_validate_version_no_key(integration: Integration) -> None: """Test validate version with no key.""" validate_version(integration) assert "No 'version' key in the manifest file." in [ @@ -30,7 +30,7 @@ def test_validate_version_no_key(integration: Integration): ] -def test_validate_custom_integration_manifest(integration: Integration): +def test_validate_custom_integration_manifest(integration: Integration) -> None: """Test validate custom integration manifest.""" with pytest.raises(vol.Invalid): diff --git a/tests/helpers/test_aiohttp_client.py b/tests/helpers/test_aiohttp_client.py index 23ef8878c21..fe7ffca9a47 100644 --- a/tests/helpers/test_aiohttp_client.py +++ b/tests/helpers/test_aiohttp_client.py @@ -22,6 +22,7 @@ import homeassistant.helpers.aiohttp_client as client from homeassistant.util.color import RGBColor from tests.common import MockConfigEntry +from tests.test_util.aiohttp import AiohttpClientMocker @pytest.fixture(name="camera_client") @@ -127,7 +128,9 @@ async def test_get_clientsession_patched_close(hass: HomeAssistant) -> None: @patch("homeassistant.helpers.frame._REPORTED_INTEGRATIONS", set()) -async def test_warning_close_session_integration(hass, caplog): +async def test_warning_close_session_integration( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test log warning message when closing the session from integration context.""" with patch( "homeassistant.helpers.frame.extract_stack", @@ -159,7 +162,9 @@ async def test_warning_close_session_integration(hass, caplog): @patch("homeassistant.helpers.frame._REPORTED_INTEGRATIONS", set()) -async def test_warning_close_session_custom(hass, caplog): +async def test_warning_close_session_custom( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test log warning message when closing the session from custom context.""" with patch( "homeassistant.helpers.frame.extract_stack", @@ -190,7 +195,9 @@ async def test_warning_close_session_custom(hass, caplog): ) -async def test_async_aiohttp_proxy_stream(aioclient_mock, camera_client): +async def test_async_aiohttp_proxy_stream( + aioclient_mock: AiohttpClientMocker, camera_client +) -> None: """Test that it fetches the given url.""" aioclient_mock.get("http://example.com/mjpeg_stream", content=b"Frame1Frame2Frame3") @@ -202,7 +209,9 @@ async def test_async_aiohttp_proxy_stream(aioclient_mock, camera_client): assert body == "Frame1Frame2Frame3" -async def test_async_aiohttp_proxy_stream_timeout(aioclient_mock, camera_client): +async def test_async_aiohttp_proxy_stream_timeout( + aioclient_mock: AiohttpClientMocker, camera_client +) -> None: """Test that it fetches the given url.""" aioclient_mock.get("http://example.com/mjpeg_stream", exc=asyncio.TimeoutError()) @@ -210,7 +219,9 @@ async def test_async_aiohttp_proxy_stream_timeout(aioclient_mock, camera_client) assert resp.status == 504 -async def test_async_aiohttp_proxy_stream_client_err(aioclient_mock, camera_client): +async def test_async_aiohttp_proxy_stream_client_err( + aioclient_mock: AiohttpClientMocker, camera_client +) -> None: """Test that it fetches the given url.""" aioclient_mock.get("http://example.com/mjpeg_stream", exc=aiohttp.ClientError()) @@ -218,7 +229,9 @@ async def test_async_aiohttp_proxy_stream_client_err(aioclient_mock, camera_clie assert resp.status == 502 -async def test_sending_named_tuple(hass, aioclient_mock): +async def test_sending_named_tuple( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: """Test sending a named tuple in json.""" resp = aioclient_mock.post("http://127.0.0.1/rgb", json={"rgb": RGBColor(4, 3, 2)}) session = client.async_create_clientsession(hass) diff --git a/tests/helpers/test_area_registry.py b/tests/helpers/test_area_registry.py index 3128e5b80b0..fd74da547d4 100644 --- a/tests/helpers/test_area_registry.py +++ b/tests/helpers/test_area_registry.py @@ -1,7 +1,9 @@ """Tests for the Area Registry.""" +from typing import Any + import pytest -from homeassistant.core import callback +from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import area_registry as ar from tests.common import ANY, flush_store @@ -21,7 +23,7 @@ def update_events(hass): return events -async def test_list_areas(area_registry): +async def test_list_areas(area_registry: ar.AreaRegistry) -> None: """Make sure that we can read areas.""" area_registry.async_create("mock") @@ -30,7 +32,9 @@ async def test_list_areas(area_registry): assert len(areas) == len(area_registry.areas) -async def test_create_area(hass, area_registry, update_events): +async def test_create_area( + hass: HomeAssistant, area_registry: ar.AreaRegistry, update_events +) -> None: """Make sure that we can create an area.""" # Create area with only mandatory parameters area = area_registry.async_create("mock") @@ -67,7 +71,9 @@ async def test_create_area(hass, area_registry, update_events): assert update_events[-1]["area_id"] == area.id -async def test_create_area_with_name_already_in_use(hass, area_registry, update_events): +async def test_create_area_with_name_already_in_use( + hass: HomeAssistant, area_registry: ar.AreaRegistry, update_events +) -> None: """Make sure that we can't create an area with a name already in use.""" area1 = area_registry.async_create("mock") @@ -82,7 +88,9 @@ async def test_create_area_with_name_already_in_use(hass, area_registry, update_ assert len(update_events) == 1 -async def test_create_area_with_id_already_in_use(area_registry): +async def test_create_area_with_id_already_in_use( + area_registry: ar.AreaRegistry, +) -> None: """Make sure that we can't create an area with a name already in use.""" area1 = area_registry.async_create("mock") @@ -93,7 +101,9 @@ async def test_create_area_with_id_already_in_use(area_registry): assert area2.id == "mock_2" -async def test_delete_area(hass, area_registry, update_events): +async def test_delete_area( + hass: HomeAssistant, area_registry: ar.AreaRegistry, update_events +) -> None: """Make sure that we can delete an area.""" area = area_registry.async_create("mock") @@ -110,7 +120,7 @@ async def test_delete_area(hass, area_registry, update_events): assert update_events[1]["area_id"] == area.id -async def test_delete_non_existing_area(area_registry): +async def test_delete_non_existing_area(area_registry: ar.AreaRegistry) -> None: """Make sure that we can't delete an area that doesn't exist.""" area_registry.async_create("mock") @@ -120,7 +130,9 @@ async def test_delete_non_existing_area(area_registry): assert len(area_registry.areas) == 1 -async def test_update_area(hass, area_registry, update_events): +async def test_update_area( + hass: HomeAssistant, area_registry: ar.AreaRegistry, update_events +) -> None: """Make sure that we can read areas.""" area = area_registry.async_create("mock") @@ -150,7 +162,7 @@ async def test_update_area(hass, area_registry, update_events): assert update_events[1]["area_id"] == area.id -async def test_update_area_with_same_name(area_registry): +async def test_update_area_with_same_name(area_registry: ar.AreaRegistry) -> None: """Make sure that we can reapply the same name to the area.""" area = area_registry.async_create("mock") @@ -160,7 +172,9 @@ async def test_update_area_with_same_name(area_registry): assert len(area_registry.areas) == 1 -async def test_update_area_with_same_name_change_case(area_registry): +async def test_update_area_with_same_name_change_case( + area_registry: ar.AreaRegistry, +) -> None: """Make sure that we can reapply the same name with a different case to the area.""" area = area_registry.async_create("mock") @@ -172,7 +186,9 @@ async def test_update_area_with_same_name_change_case(area_registry): assert len(area_registry.areas) == 1 -async def test_update_area_with_name_already_in_use(area_registry): +async def test_update_area_with_name_already_in_use( + area_registry: ar.AreaRegistry, +) -> None: """Make sure that we can't update an area with a name already in use.""" area1 = area_registry.async_create("mock1") area2 = area_registry.async_create("mock2") @@ -186,7 +202,9 @@ async def test_update_area_with_name_already_in_use(area_registry): assert len(area_registry.areas) == 2 -async def test_update_area_with_normalized_name_already_in_use(area_registry): +async def test_update_area_with_normalized_name_already_in_use( + area_registry: ar.AreaRegistry, +) -> None: """Make sure that we can't update an area with a normalized name already in use.""" area1 = area_registry.async_create("mock1") area2 = area_registry.async_create("Moc k2") @@ -200,7 +218,7 @@ async def test_update_area_with_normalized_name_already_in_use(area_registry): assert len(area_registry.areas) == 2 -async def test_load_area(hass, area_registry): +async def test_load_area(hass: HomeAssistant, area_registry: ar.AreaRegistry) -> None: """Make sure that we can load/save data correctly.""" area1 = area_registry.async_create("mock1") area2 = area_registry.async_create("mock2") @@ -220,7 +238,9 @@ async def test_load_area(hass, area_registry): @pytest.mark.parametrize("load_registries", [False]) -async def test_loading_area_from_storage(hass, hass_storage): +async def test_loading_area_from_storage( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test loading stored areas on start.""" hass_storage[ar.STORAGE_KEY] = { "version": ar.STORAGE_VERSION_MAJOR, @@ -244,7 +264,9 @@ async def test_loading_area_from_storage(hass, hass_storage): @pytest.mark.parametrize("load_registries", [False]) -async def test_migration_from_1_1(hass, hass_storage): +async def test_migration_from_1_1( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test migration from version 1.1.""" hass_storage[ar.STORAGE_KEY] = { "version": 1, @@ -270,7 +292,7 @@ async def test_migration_from_1_1(hass, hass_storage): } -async def test_async_get_or_create(area_registry): +async def test_async_get_or_create(area_registry: ar.AreaRegistry) -> None: """Make sure we can get the area by name.""" area = area_registry.async_get_or_create("Mock1") area2 = area_registry.async_get_or_create("mock1") @@ -281,7 +303,7 @@ async def test_async_get_or_create(area_registry): assert area2 == area3 -async def test_async_get_area_by_name(area_registry): +async def test_async_get_area_by_name(area_registry: ar.AreaRegistry) -> None: """Make sure we can get the area by name.""" area_registry.async_create("Mock1") @@ -290,7 +312,7 @@ async def test_async_get_area_by_name(area_registry): assert area_registry.async_get_area_by_name("M o c k 1").normalized_name == "mock1" -async def test_async_get_area_by_name_not_found(area_registry): +async def test_async_get_area_by_name_not_found(area_registry: ar.AreaRegistry) -> None: """Make sure we return None for non-existent areas.""" area_registry.async_create("Mock1") @@ -299,7 +321,7 @@ async def test_async_get_area_by_name_not_found(area_registry): assert area_registry.async_get_area_by_name("non_exist") is None -async def test_async_get_area(area_registry): +async def test_async_get_area(area_registry: ar.AreaRegistry) -> None: """Make sure we can get the area by id.""" area = area_registry.async_create("Mock1") diff --git a/tests/helpers/test_collection.py b/tests/helpers/test_collection.py index 9e5526ff32c..fe403f8db1b 100644 --- a/tests/helpers/test_collection.py +++ b/tests/helpers/test_collection.py @@ -16,6 +16,7 @@ from homeassistant.helpers import ( from homeassistant.helpers.typing import ConfigType from tests.common import flush_store +from tests.typing import WebSocketGenerator _LOGGER = logging.getLogger(__name__) @@ -425,7 +426,9 @@ async def test_entity_component_collection_entity_removed(hass: HomeAssistant) - assert len(async_remove_calls) == 1 -async def test_storage_collection_websocket(hass, hass_ws_client): +async def test_storage_collection_websocket( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator +) -> None: """Test exposing a storage collection via websockets.""" store = storage.Store(hass, 1, "test-data") coll = MockStorageCollection(store, _LOGGER) diff --git a/tests/helpers/test_condition.py b/tests/helpers/test_condition.py index 80b40baae04..364e4c9fb95 100644 --- a/tests/helpers/test_condition.py +++ b/tests/helpers/test_condition.py @@ -29,6 +29,7 @@ from homeassistant.setup import async_setup_component import homeassistant.util.dt as dt_util from tests.common import async_mock_service +from tests.typing import WebSocketGenerator @pytest.fixture @@ -2140,7 +2141,9 @@ async def assert_automation_condition_trace(hass_ws_client, automation_id, expec assert condition_trace == expected -async def test_if_action_before_sunrise_no_offset(hass, hass_ws_client, calls): +async def test_if_action_before_sunrise_no_offset( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator, calls +) -> None: """Test if action was before sunrise. Before sunrise is true from midnight until sunset, local time. @@ -2209,7 +2212,9 @@ async def test_if_action_before_sunrise_no_offset(hass, hass_ws_client, calls): ) -async def test_if_action_after_sunrise_no_offset(hass, hass_ws_client, calls): +async def test_if_action_after_sunrise_no_offset( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator, calls +) -> None: """Test if action was after sunrise. After sunrise is true from sunrise until midnight, local time. @@ -2278,7 +2283,9 @@ async def test_if_action_after_sunrise_no_offset(hass, hass_ws_client, calls): ) -async def test_if_action_before_sunrise_with_offset(hass, hass_ws_client, calls): +async def test_if_action_before_sunrise_with_offset( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator, calls +) -> None: """Test if action was before sunrise with offset. Before sunrise is true from midnight until sunset, local time. @@ -2399,7 +2406,9 @@ async def test_if_action_before_sunrise_with_offset(hass, hass_ws_client, calls) ) -async def test_if_action_before_sunset_with_offset(hass, hass_ws_client, calls): +async def test_if_action_before_sunset_with_offset( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator, calls +) -> None: """Test if action was before sunset with offset. Before sunset is true from midnight until sunset, local time. @@ -2520,7 +2529,9 @@ async def test_if_action_before_sunset_with_offset(hass, hass_ws_client, calls): ) -async def test_if_action_after_sunrise_with_offset(hass, hass_ws_client, calls): +async def test_if_action_after_sunrise_with_offset( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator, calls +) -> None: """Test if action was after sunrise with offset. After sunrise is true from sunrise until midnight, local time. @@ -2665,7 +2676,9 @@ async def test_if_action_after_sunrise_with_offset(hass, hass_ws_client, calls): ) -async def test_if_action_after_sunset_with_offset(hass, hass_ws_client, calls): +async def test_if_action_after_sunset_with_offset( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator, calls +) -> None: """Test if action was after sunset with offset. After sunset is true from sunset until midnight, local time. @@ -2738,7 +2751,9 @@ async def test_if_action_after_sunset_with_offset(hass, hass_ws_client, calls): ) -async def test_if_action_after_and_before_during(hass, hass_ws_client, calls): +async def test_if_action_after_and_before_during( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator, calls +) -> None: """Test if action was after sunrise and before sunset. This is true from sunrise until sunset. @@ -2839,7 +2854,9 @@ async def test_if_action_after_and_before_during(hass, hass_ws_client, calls): ) -async def test_if_action_before_or_after_during(hass, hass_ws_client, calls): +async def test_if_action_before_or_after_during( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator, calls +) -> None: """Test if action was before sunrise or after sunset. This is true from midnight until sunrise and from sunset until midnight @@ -2960,7 +2977,9 @@ async def test_if_action_before_or_after_during(hass, hass_ws_client, calls): ) -async def test_if_action_before_sunrise_no_offset_kotzebue(hass, hass_ws_client, calls): +async def test_if_action_before_sunrise_no_offset_kotzebue( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator, calls +) -> None: """Test if action was before sunrise. Local timezone: Alaska time @@ -3035,7 +3054,9 @@ async def test_if_action_before_sunrise_no_offset_kotzebue(hass, hass_ws_client, ) -async def test_if_action_after_sunrise_no_offset_kotzebue(hass, hass_ws_client, calls): +async def test_if_action_after_sunrise_no_offset_kotzebue( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator, calls +) -> None: """Test if action was after sunrise. Local timezone: Alaska time @@ -3110,7 +3131,9 @@ async def test_if_action_after_sunrise_no_offset_kotzebue(hass, hass_ws_client, ) -async def test_if_action_before_sunset_no_offset_kotzebue(hass, hass_ws_client, calls): +async def test_if_action_before_sunset_no_offset_kotzebue( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator, calls +) -> None: """Test if action was before sunrise. Local timezone: Alaska time @@ -3185,7 +3208,9 @@ async def test_if_action_before_sunset_no_offset_kotzebue(hass, hass_ws_client, ) -async def test_if_action_after_sunset_no_offset_kotzebue(hass, hass_ws_client, calls): +async def test_if_action_after_sunset_no_offset_kotzebue( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator, calls +) -> None: """Test if action was after sunrise. Local timezone: Alaska time diff --git a/tests/helpers/test_config_entry_flow.py b/tests/helpers/test_config_entry_flow.py index bc545a647cf..8909f18e544 100644 --- a/tests/helpers/test_config_entry_flow.py +++ b/tests/helpers/test_config_entry_flow.py @@ -5,6 +5,7 @@ import pytest from homeassistant import config_entries, data_entry_flow, setup from homeassistant.config import async_process_ha_core_config +from homeassistant.core import HomeAssistant from homeassistant.helpers import config_entry_flow from tests.common import ( @@ -42,7 +43,7 @@ def webhook_flow_conf(hass): yield {} -async def test_single_entry_allowed(hass, discovery_flow_conf): +async def test_single_entry_allowed(hass: HomeAssistant, discovery_flow_conf) -> None: """Test only a single entry is allowed.""" flow = config_entries.HANDLERS["test"]() flow.hass = hass @@ -55,7 +56,7 @@ async def test_single_entry_allowed(hass, discovery_flow_conf): assert result["reason"] == "single_instance_allowed" -async def test_user_no_devices_found(hass, discovery_flow_conf): +async def test_user_no_devices_found(hass: HomeAssistant, discovery_flow_conf) -> None: """Test if no devices found.""" flow = config_entries.HANDLERS["test"]() flow.hass = hass @@ -66,7 +67,7 @@ async def test_user_no_devices_found(hass, discovery_flow_conf): assert result["reason"] == "no_devices_found" -async def test_user_has_confirmation(hass, discovery_flow_conf): +async def test_user_has_confirmation(hass: HomeAssistant, discovery_flow_conf) -> None: """Test user requires confirmation to setup.""" discovery_flow_conf["discovered"] = True mock_entity_platform(hass, "config_flow.test", None) @@ -102,7 +103,9 @@ async def test_user_has_confirmation(hass, discovery_flow_conf): config_entries.SOURCE_DHCP, ], ) -async def test_discovery_single_instance(hass, discovery_flow_conf, source): +async def test_discovery_single_instance( + hass: HomeAssistant, discovery_flow_conf, source +) -> None: """Test we not allow duplicates.""" flow = config_entries.HANDLERS["test"]() flow.hass = hass @@ -126,7 +129,9 @@ async def test_discovery_single_instance(hass, discovery_flow_conf, source): config_entries.SOURCE_DHCP, ], ) -async def test_discovery_confirmation(hass, discovery_flow_conf, source): +async def test_discovery_confirmation( + hass: HomeAssistant, discovery_flow_conf, source +) -> None: """Test we ask for confirmation via discovery.""" flow = config_entries.HANDLERS["test"]() flow.hass = hass @@ -152,7 +157,9 @@ async def test_discovery_confirmation(hass, discovery_flow_conf, source): config_entries.SOURCE_DHCP, ], ) -async def test_discovery_during_onboarding(hass, discovery_flow_conf, source): +async def test_discovery_during_onboarding( + hass: HomeAssistant, discovery_flow_conf, source +) -> None: """Test we create config entry via discovery during onboarding.""" flow = config_entries.HANDLERS["test"]() flow.hass = hass @@ -166,7 +173,7 @@ async def test_discovery_during_onboarding(hass, discovery_flow_conf, source): assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY -async def test_multiple_discoveries(hass, discovery_flow_conf): +async def test_multiple_discoveries(hass: HomeAssistant, discovery_flow_conf) -> None: """Test we only create one instance for multiple discoveries.""" mock_entity_platform(hass, "config_flow.test", None) @@ -182,7 +189,7 @@ async def test_multiple_discoveries(hass, discovery_flow_conf): assert result["type"] == data_entry_flow.FlowResultType.ABORT -async def test_only_one_in_progress(hass, discovery_flow_conf): +async def test_only_one_in_progress(hass: HomeAssistant, discovery_flow_conf) -> None: """Test a user initialized one will finish and cancel discovered one.""" mock_entity_platform(hass, "config_flow.test", None) @@ -208,7 +215,7 @@ async def test_only_one_in_progress(hass, discovery_flow_conf): assert len(hass.config_entries.flow.async_progress()) == 0 -async def test_import_abort_discovery(hass, discovery_flow_conf): +async def test_import_abort_discovery(hass: HomeAssistant, discovery_flow_conf) -> None: """Test import will finish and cancel discovered one.""" mock_entity_platform(hass, "config_flow.test", None) @@ -229,7 +236,7 @@ async def test_import_abort_discovery(hass, discovery_flow_conf): assert len(hass.config_entries.flow.async_progress()) == 0 -async def test_import_no_confirmation(hass, discovery_flow_conf): +async def test_import_no_confirmation(hass: HomeAssistant, discovery_flow_conf) -> None: """Test import requires no confirmation to set up.""" flow = config_entries.HANDLERS["test"]() flow.hass = hass @@ -240,7 +247,7 @@ async def test_import_no_confirmation(hass, discovery_flow_conf): assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY -async def test_import_single_instance(hass, discovery_flow_conf): +async def test_import_single_instance(hass: HomeAssistant, discovery_flow_conf) -> None: """Test import doesn't create second instance.""" flow = config_entries.HANDLERS["test"]() flow.hass = hass @@ -252,7 +259,7 @@ async def test_import_single_instance(hass, discovery_flow_conf): assert result["type"] == data_entry_flow.FlowResultType.ABORT -async def test_ignored_discoveries(hass, discovery_flow_conf): +async def test_ignored_discoveries(hass: HomeAssistant, discovery_flow_conf) -> None: """Test we can ignore discovered entries.""" mock_entity_platform(hass, "config_flow.test", None) @@ -284,7 +291,9 @@ async def test_ignored_discoveries(hass, discovery_flow_conf): assert result["type"] == data_entry_flow.FlowResultType.ABORT -async def test_webhook_single_entry_allowed(hass, webhook_flow_conf): +async def test_webhook_single_entry_allowed( + hass: HomeAssistant, webhook_flow_conf +) -> None: """Test only a single entry is allowed.""" flow = config_entries.HANDLERS["test_single"]() flow.hass = hass @@ -296,7 +305,9 @@ async def test_webhook_single_entry_allowed(hass, webhook_flow_conf): assert result["reason"] == "single_instance_allowed" -async def test_webhook_multiple_entries_allowed(hass, webhook_flow_conf): +async def test_webhook_multiple_entries_allowed( + hass: HomeAssistant, webhook_flow_conf +) -> None: """Test multiple entries are allowed when specified.""" flow = config_entries.HANDLERS["test_multiple"]() flow.hass = hass @@ -308,7 +319,9 @@ async def test_webhook_multiple_entries_allowed(hass, webhook_flow_conf): assert result["type"] == data_entry_flow.FlowResultType.FORM -async def test_webhook_config_flow_registers_webhook(hass, webhook_flow_conf): +async def test_webhook_config_flow_registers_webhook( + hass: HomeAssistant, webhook_flow_conf +) -> None: """Test setting up an entry creates a webhook.""" flow = config_entries.HANDLERS["test_single"]() flow.hass = hass @@ -323,7 +336,7 @@ async def test_webhook_config_flow_registers_webhook(hass, webhook_flow_conf): assert result["data"]["webhook_id"] is not None -async def test_webhook_create_cloudhook(hass, webhook_flow_conf): +async def test_webhook_create_cloudhook(hass: HomeAssistant, webhook_flow_conf) -> None: """Test cloudhook will be created if subscribed.""" assert await setup.async_setup_component(hass, "cloud", {}) @@ -376,7 +389,9 @@ async def test_webhook_create_cloudhook(hass, webhook_flow_conf): assert result["require_restart"] is False -async def test_webhook_create_cloudhook_aborts_not_connected(hass, webhook_flow_conf): +async def test_webhook_create_cloudhook_aborts_not_connected( + hass: HomeAssistant, webhook_flow_conf +) -> None: """Test cloudhook aborts if subscribed but not connected.""" assert await setup.async_setup_component(hass, "cloud", {}) diff --git a/tests/helpers/test_config_entry_oauth2_flow.py b/tests/helpers/test_config_entry_oauth2_flow.py index 6dc353723d7..3baaf7e7333 100644 --- a/tests/helpers/test_config_entry_oauth2_flow.py +++ b/tests/helpers/test_config_entry_oauth2_flow.py @@ -8,10 +8,13 @@ import aiohttp import pytest from homeassistant import config_entries, data_entry_flow, setup +from homeassistant.core import HomeAssistant from homeassistant.helpers import config_entry_oauth2_flow from homeassistant.helpers.network import NoURLAvailableError from tests.common import MockConfigEntry, mock_platform +from tests.test_util.aiohttp import AiohttpClientMocker +from tests.typing import ClientSessionGenerator TEST_DOMAIN = "oauth2_test" CLIENT_SECRET = "5678" @@ -105,7 +108,7 @@ def test_inherit_enforces_domain_set() -> None: TestFlowHandler() -async def test_abort_if_no_implementation(hass, flow_handler): +async def test_abort_if_no_implementation(hass: HomeAssistant, flow_handler) -> None: """Check flow abort when no implementations.""" flow = flow_handler() flow.hass = hass @@ -114,7 +117,9 @@ async def test_abort_if_no_implementation(hass, flow_handler): assert result["reason"] == "missing_configuration" -async def test_missing_credentials_for_domain(hass, flow_handler): +async def test_missing_credentials_for_domain( + hass: HomeAssistant, flow_handler +) -> None: """Check flow abort for integration supporting application credentials.""" flow = flow_handler() flow.hass = hass @@ -126,8 +131,8 @@ async def test_missing_credentials_for_domain(hass, flow_handler): async def test_abort_if_authorization_timeout( - hass, flow_handler, local_impl, current_request_with_host -): + hass: HomeAssistant, flow_handler, local_impl, current_request_with_host: None +) -> None: """Check timeout generating authorization url.""" flow_handler.async_register_implementation(hass, local_impl) @@ -145,8 +150,8 @@ async def test_abort_if_authorization_timeout( async def test_abort_if_no_url_available( - hass, flow_handler, local_impl, current_request_with_host -): + hass: HomeAssistant, flow_handler, local_impl, current_request_with_host: None +) -> None: """Check no_url_available generating authorization url.""" flow_handler.async_register_implementation(hass, local_impl) @@ -163,13 +168,13 @@ async def test_abort_if_no_url_available( async def test_abort_if_oauth_error( - hass, + hass: HomeAssistant, flow_handler, local_impl, - hass_client_no_auth, - aioclient_mock, - current_request_with_host, -): + hass_client_no_auth: ClientSessionGenerator, + aioclient_mock: AiohttpClientMocker, + current_request_with_host: None, +) -> None: """Check bad oauth token.""" flow_handler.async_register_implementation(hass, local_impl) config_entry_oauth2_flow.async_register_implementation( @@ -225,13 +230,13 @@ async def test_abort_if_oauth_error( async def test_abort_if_oauth_rejected( - hass, + hass: HomeAssistant, flow_handler, local_impl, - hass_client_no_auth, - aioclient_mock, - current_request_with_host, -): + hass_client_no_auth: ClientSessionGenerator, + aioclient_mock: AiohttpClientMocker, + current_request_with_host: None, +) -> None: """Check bad oauth token.""" flow_handler.async_register_implementation(hass, local_impl) config_entry_oauth2_flow.async_register_implementation( @@ -280,13 +285,13 @@ async def test_abort_if_oauth_rejected( async def test_abort_on_oauth_timeout_error( - hass, + hass: HomeAssistant, flow_handler, local_impl, - hass_client_no_auth, - aioclient_mock, - current_request_with_host, -): + hass_client_no_auth: ClientSessionGenerator, + aioclient_mock: AiohttpClientMocker, + current_request_with_host: None, +) -> None: """Check timeout during oauth token exchange.""" flow_handler.async_register_implementation(hass, local_impl) config_entry_oauth2_flow.async_register_implementation( @@ -335,7 +340,7 @@ async def test_abort_on_oauth_timeout_error( assert result["reason"] == "oauth2_timeout" -async def test_step_discovery(hass, flow_handler, local_impl): +async def test_step_discovery(hass: HomeAssistant, flow_handler, local_impl) -> None: """Check flow triggers from discovery.""" flow_handler.async_register_implementation(hass, local_impl) config_entry_oauth2_flow.async_register_implementation( @@ -352,7 +357,9 @@ async def test_step_discovery(hass, flow_handler, local_impl): assert result["step_id"] == "pick_implementation" -async def test_abort_discovered_multiple(hass, flow_handler, local_impl): +async def test_abort_discovered_multiple( + hass: HomeAssistant, flow_handler, local_impl +) -> None: """Test if aborts when discovered multiple times.""" flow_handler.async_register_implementation(hass, local_impl) config_entry_oauth2_flow.async_register_implementation( @@ -378,7 +385,9 @@ async def test_abort_discovered_multiple(hass, flow_handler, local_impl): assert result["reason"] == "already_in_progress" -async def test_abort_discovered_existing_entries(hass, flow_handler, local_impl): +async def test_abort_discovered_existing_entries( + hass: HomeAssistant, flow_handler, local_impl +) -> None: """Test if abort discovery when entries exists.""" flow_handler.async_register_implementation(hass, local_impl) config_entry_oauth2_flow.async_register_implementation( @@ -402,13 +411,13 @@ async def test_abort_discovered_existing_entries(hass, flow_handler, local_impl) async def test_full_flow( - hass, + hass: HomeAssistant, flow_handler, local_impl, - hass_client_no_auth, - aioclient_mock, - current_request_with_host, -): + hass_client_no_auth: ClientSessionGenerator, + aioclient_mock: AiohttpClientMocker, + current_request_with_host: None, +) -> None: """Check full flow.""" flow_handler.async_register_implementation(hass, local_impl) config_entry_oauth2_flow.async_register_implementation( @@ -479,7 +488,9 @@ async def test_full_flow( ) -async def test_local_refresh_token(hass, local_impl, aioclient_mock): +async def test_local_refresh_token( + hass: HomeAssistant, local_impl, aioclient_mock: AiohttpClientMocker +) -> None: """Test we can refresh token.""" aioclient_mock.post( TOKEN_URL, json={"access_token": ACCESS_TOKEN_2, "expires_in": 100} @@ -511,7 +522,9 @@ async def test_local_refresh_token(hass, local_impl, aioclient_mock): } -async def test_oauth_session(hass, flow_handler, local_impl, aioclient_mock): +async def test_oauth_session( + hass: HomeAssistant, flow_handler, local_impl, aioclient_mock: AiohttpClientMocker +) -> None: """Test the OAuth2 session helper.""" flow_handler.async_register_implementation(hass, local_impl) @@ -556,8 +569,8 @@ async def test_oauth_session(hass, flow_handler, local_impl, aioclient_mock): async def test_oauth_session_with_clock_slightly_out_of_sync( - hass, flow_handler, local_impl, aioclient_mock -): + hass: HomeAssistant, flow_handler, local_impl, aioclient_mock: AiohttpClientMocker +) -> None: """Test the OAuth2 session helper when the remote clock is slightly out of sync.""" flow_handler.async_register_implementation(hass, local_impl) @@ -602,8 +615,8 @@ async def test_oauth_session_with_clock_slightly_out_of_sync( async def test_oauth_session_no_token_refresh_needed( - hass, flow_handler, local_impl, aioclient_mock -): + hass: HomeAssistant, flow_handler, local_impl, aioclient_mock: AiohttpClientMocker +) -> None: """Test the OAuth2 session helper when no refresh is needed.""" flow_handler.async_register_implementation(hass, local_impl) @@ -643,7 +656,7 @@ async def test_oauth_session_no_token_refresh_needed( assert round(config_entry.data["token"]["expires_at"] - now) == 500 -async def test_implementation_provider(hass, local_impl): +async def test_implementation_provider(hass: HomeAssistant, local_impl) -> None: """Test providing an implementation provider.""" assert ( await config_entry_oauth2_flow.async_get_implementations(hass, TEST_DOMAIN) @@ -700,8 +713,8 @@ async def test_implementation_provider(hass, local_impl): async def test_oauth_session_refresh_failure( - hass, flow_handler, local_impl, aioclient_mock -): + hass: HomeAssistant, flow_handler, local_impl, aioclient_mock: AiohttpClientMocker +) -> None: """Test the OAuth2 session helper when no refresh is needed.""" flow_handler.async_register_implementation(hass, local_impl) @@ -728,7 +741,9 @@ async def test_oauth_session_refresh_failure( await session.async_request("post", "https://example.com") -async def test_oauth2_without_secret_init(local_impl, hass_client_no_auth): +async def test_oauth2_without_secret_init( + local_impl, hass_client_no_auth: ClientSessionGenerator +) -> None: """Check authorize callback without secret initalizated.""" client = await hass_client_no_auth() resp = await client.get("/auth/external/callback?code=abcd&state=qwer") diff --git a/tests/helpers/test_config_validation.py b/tests/helpers/test_config_validation.py index 5d97ff9b5d5..9e1c84151c2 100644 --- a/tests/helpers/test_config_validation.py +++ b/tests/helpers/test_config_validation.py @@ -174,7 +174,7 @@ def test_entity_id() -> None: @pytest.mark.parametrize("validator", [cv.entity_ids, cv.entity_ids_or_uuids]) -def test_entity_ids(validator): +def test_entity_ids(validator) -> None: """Test entity ID validation.""" schema = vol.Schema(validator) @@ -751,7 +751,7 @@ def version(monkeypatch): monkeypatch.setattr(homeassistant.const, "__version__", "0.5.0") -def test_deprecated_with_no_optionals(caplog, schema): +def test_deprecated_with_no_optionals(caplog: pytest.LogCaptureFixture, schema) -> None: """Test deprecation behaves correctly when optional params are None. Expected behavior: @@ -782,7 +782,9 @@ def test_deprecated_with_no_optionals(caplog, schema): assert test_data == output -def test_deprecated_or_removed_param_and_raise(caplog, schema): +def test_deprecated_or_removed_param_and_raise( + caplog: pytest.LogCaptureFixture, schema +) -> None: """Test removed or deprecation options and fail the config validation by raising an exception. Expected behavior: @@ -821,7 +823,9 @@ def test_deprecated_or_removed_param_and_raise(caplog, schema): assert test_data == output -def test_deprecated_with_replacement_key(caplog, schema): +def test_deprecated_with_replacement_key( + caplog: pytest.LogCaptureFixture, schema +) -> None: """Test deprecation behaves correctly when only a replacement key is provided. Expected behavior: @@ -858,7 +862,7 @@ def test_deprecated_with_replacement_key(caplog, schema): assert test_data == output -def test_deprecated_with_default(caplog, schema): +def test_deprecated_with_default(caplog: pytest.LogCaptureFixture, schema) -> None: """Test deprecation behaves correctly with a default value. This is likely a scenario that would never occur. @@ -886,7 +890,9 @@ def test_deprecated_with_default(caplog, schema): assert test_data == output -def test_deprecated_with_replacement_key_and_default(caplog, schema): +def test_deprecated_with_replacement_key_and_default( + caplog: pytest.LogCaptureFixture, schema +) -> None: """Test deprecation with a replacement key and default. Expected behavior: @@ -960,7 +966,9 @@ def test_deprecated_cant_find_module() -> None: ) -def test_deprecated_or_removed_logger_with_config_attributes(caplog): +def test_deprecated_or_removed_logger_with_config_attributes( + caplog: pytest.LogCaptureFixture, +) -> None: """Test if the logger outputs the correct message if the line and file attribute is available in config.""" file: str = "configuration.yaml" line: int = 54 @@ -997,7 +1005,9 @@ def test_deprecated_or_removed_logger_with_config_attributes(caplog): assert len(caplog.records) == 0 -def test_deprecated_logger_with_one_config_attribute(caplog): +def test_deprecated_logger_with_one_config_attribute( + caplog: pytest.LogCaptureFixture, +) -> None: """Test if the logger outputs the correct message if only one of line and file attribute is available in config.""" file: str = "configuration.yaml" line: int = 54 @@ -1031,7 +1041,9 @@ def test_deprecated_logger_with_one_config_attribute(caplog): assert len(caplog.records) == 0 -def test_deprecated_logger_without_config_attributes(caplog): +def test_deprecated_logger_without_config_attributes( + caplog: pytest.LogCaptureFixture, +) -> None: """Test if the logger outputs the correct message if the line and file attribute is not available in config.""" file: str = "configuration.yaml" line: int = 54 @@ -1166,7 +1178,7 @@ def test_comp_entity_ids() -> None: schema(invalid) -def test_uuid4_hex(caplog): +def test_uuid4_hex(caplog: pytest.LogCaptureFixture) -> None: """Test uuid validation.""" schema = vol.Schema(cv.uuid4_hex) @@ -1262,7 +1274,7 @@ def test_key_value_schemas_with_default() -> None: schema({"mode": "{{ 1 + 1}}"}) -def test_script(caplog): +def test_script(caplog: pytest.LogCaptureFixture) -> None: """Test script validation is user friendly.""" for data, msg in ( ({"delay": "{{ invalid"}, "should be format 'HH:MM'"), diff --git a/tests/helpers/test_deprecation.py b/tests/helpers/test_deprecation.py index ebabe12c1ad..380801123b0 100644 --- a/tests/helpers/test_deprecation.py +++ b/tests/helpers/test_deprecation.py @@ -1,6 +1,8 @@ """Test deprecation helpers.""" from unittest.mock import MagicMock, patch +import pytest + from homeassistant.helpers.deprecation import ( deprecated_function, deprecated_substitute, @@ -37,7 +39,7 @@ class MockUpdatedClass(MockBaseClass): @patch("logging.getLogger") -def test_deprecated_substitute_old_class(mock_get_logger): +def test_deprecated_substitute_old_class(mock_get_logger) -> None: """Test deprecated class object.""" mock_logger = MagicMock() mock_get_logger.return_value = mock_logger @@ -50,7 +52,7 @@ def test_deprecated_substitute_old_class(mock_get_logger): @patch("logging.getLogger") -def test_deprecated_substitute_new_class(mock_get_logger): +def test_deprecated_substitute_new_class(mock_get_logger) -> None: """Test deprecated class object.""" mock_logger = MagicMock() mock_get_logger.return_value = mock_logger @@ -62,7 +64,7 @@ def test_deprecated_substitute_new_class(mock_get_logger): @patch("logging.getLogger") -def test_config_get_deprecated_old(mock_get_logger): +def test_config_get_deprecated_old(mock_get_logger) -> None: """Test deprecated class object.""" mock_logger = MagicMock() mock_get_logger.return_value = mock_logger @@ -74,7 +76,7 @@ def test_config_get_deprecated_old(mock_get_logger): @patch("logging.getLogger") -def test_config_get_deprecated_new(mock_get_logger): +def test_config_get_deprecated_new(mock_get_logger) -> None: """Test deprecated class object.""" mock_logger = MagicMock() mock_get_logger.return_value = mock_logger @@ -84,7 +86,7 @@ def test_config_get_deprecated_new(mock_get_logger): assert not mock_logger.warning.called -def test_deprecated_function(caplog): +def test_deprecated_function(caplog: pytest.LogCaptureFixture) -> None: """Test deprecated_function decorator.""" @deprecated_function("new_function") diff --git a/tests/helpers/test_device_registry.py b/tests/helpers/test_device_registry.py index b0116a158ea..e183bd4c380 100644 --- a/tests/helpers/test_device_registry.py +++ b/tests/helpers/test_device_registry.py @@ -1,5 +1,6 @@ """Tests for the Device Registry.""" import time +from typing import Any from unittest.mock import patch import pytest @@ -8,7 +9,11 @@ from homeassistant import config_entries from homeassistant.const import EVENT_HOMEASSISTANT_STARTED from homeassistant.core import CoreState, HomeAssistant, callback from homeassistant.exceptions import RequiredParameterMissing -from homeassistant.helpers import device_registry as dr, entity_registry as er +from homeassistant.helpers import ( + area_registry as ar, + device_registry as dr, + entity_registry as er, +) from tests.common import MockConfigEntry, flush_store @@ -28,8 +33,11 @@ def update_events(hass): async def test_get_or_create_returns_same_entry( - hass, device_registry, area_registry, update_events -): + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + area_registry: ar.AreaRegistry, + update_events, +) -> None: """Make sure we do not duplicate entries.""" entry = device_registry.async_get_or_create( config_entry_id="1234", @@ -87,7 +95,9 @@ async def test_get_or_create_returns_same_entry( } -async def test_requirement_for_identifier_or_connection(device_registry): +async def test_requirement_for_identifier_or_connection( + device_registry: dr.DeviceRegistry, +) -> None: """Make sure we do require some descriptor of device.""" entry = device_registry.async_get_or_create( config_entry_id="1234", @@ -120,7 +130,7 @@ async def test_requirement_for_identifier_or_connection(device_registry): assert exc_info.value.parameter_names == ["identifiers", "connections"] -async def test_multiple_config_entries(device_registry): +async def test_multiple_config_entries(device_registry: dr.DeviceRegistry) -> None: """Make sure we do not get duplicate entries.""" entry = device_registry.async_get_or_create( config_entry_id="123", @@ -151,7 +161,9 @@ async def test_multiple_config_entries(device_registry): @pytest.mark.parametrize("load_registries", [False]) -async def test_loading_from_storage(hass, hass_storage): +async def test_loading_from_storage( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test loading stored devices on start.""" hass_storage[dr.STORAGE_KEY] = { "version": dr.STORAGE_VERSION_MAJOR, @@ -244,7 +256,9 @@ async def test_loading_from_storage(hass, hass_storage): @pytest.mark.parametrize("load_registries", [False]) -async def test_migration_1_1_to_1_3(hass, hass_storage): +async def test_migration_1_1_to_1_3( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test migration from version 1.1 to 1.3.""" hass_storage[dr.STORAGE_KEY] = { "version": 1, @@ -368,7 +382,9 @@ async def test_migration_1_1_to_1_3(hass, hass_storage): @pytest.mark.parametrize("load_registries", [False]) -async def test_migration_1_2_to_1_3(hass, hass_storage): +async def test_migration_1_2_to_1_3( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test migration from version 1.2 to 1.3.""" hass_storage[dr.STORAGE_KEY] = { "version": 1, @@ -482,7 +498,9 @@ async def test_migration_1_2_to_1_3(hass, hass_storage): } -async def test_removing_config_entries(hass, device_registry, update_events): +async def test_removing_config_entries( + hass: HomeAssistant, device_registry: dr.DeviceRegistry, update_events +) -> None: """Make sure we do not get duplicate entries.""" entry = device_registry.async_get_or_create( config_entry_id="123", @@ -539,8 +557,8 @@ async def test_removing_config_entries(hass, device_registry, update_events): async def test_deleted_device_removing_config_entries( - hass, device_registry, update_events -): + hass: HomeAssistant, device_registry: dr.DeviceRegistry, update_events +) -> None: """Make sure we do not get duplicate entries.""" entry = device_registry.async_get_or_create( config_entry_id="123", @@ -633,7 +651,7 @@ async def test_deleted_device_removing_config_entries( assert entry3.id != entry4.id -async def test_removing_area_id(device_registry): +async def test_removing_area_id(device_registry: dr.DeviceRegistry) -> None: """Make sure we can clear area id.""" entry = device_registry.async_get_or_create( config_entry_id="123", @@ -652,7 +670,7 @@ async def test_removing_area_id(device_registry): assert entry_w_area != entry_wo_area -async def test_specifying_via_device_create(device_registry): +async def test_specifying_via_device_create(device_registry: dr.DeviceRegistry) -> None: """Test specifying a via_device and removal of the hub device.""" via = device_registry.async_get_or_create( config_entry_id="123", @@ -678,7 +696,7 @@ async def test_specifying_via_device_create(device_registry): assert light.via_device_id is None -async def test_specifying_via_device_update(device_registry): +async def test_specifying_via_device_update(device_registry: dr.DeviceRegistry) -> None: """Test specifying a via_device and updating.""" light = device_registry.async_get_or_create( config_entry_id="456", @@ -711,7 +729,9 @@ async def test_specifying_via_device_update(device_registry): assert light.via_device_id == via.id -async def test_loading_saving_data(hass, device_registry): +async def test_loading_saving_data( + hass: HomeAssistant, device_registry: dr.DeviceRegistry +) -> None: """Test that we load/save data correctly.""" orig_via = device_registry.async_get_or_create( config_entry_id="123", @@ -829,7 +849,7 @@ async def test_loading_saving_data(hass, device_registry): assert orig_kitchen_light_witout_suggested_area == new_kitchen_light -async def test_no_unnecessary_changes(device_registry): +async def test_no_unnecessary_changes(device_registry: dr.DeviceRegistry) -> None: """Make sure we do not consider devices changes.""" entry = device_registry.async_get_or_create( config_entry_id="1234", @@ -847,7 +867,7 @@ async def test_no_unnecessary_changes(device_registry): assert len(mock_save.mock_calls) == 0 -async def test_format_mac(device_registry): +async def test_format_mac(device_registry: dr.DeviceRegistry) -> None: """Make sure we normalize mac addresses.""" entry = device_registry.async_get_or_create( config_entry_id="1234", @@ -879,7 +899,9 @@ async def test_format_mac(device_registry): assert list(invalid_mac_entry.connections)[0][1] == invalid -async def test_update(hass, device_registry, update_events): +async def test_update( + hass: HomeAssistant, device_registry: dr.DeviceRegistry, update_events +) -> None: """Verify that we can update some attributes of a device.""" entry = device_registry.async_get_or_create( config_entry_id="1234", @@ -969,7 +991,9 @@ async def test_update(hass, device_registry, update_events): } -async def test_update_remove_config_entries(hass, device_registry, update_events): +async def test_update_remove_config_entries( + hass: HomeAssistant, device_registry: dr.DeviceRegistry, update_events +) -> None: """Make sure we do not get duplicate entries.""" entry = device_registry.async_get_or_create( config_entry_id="123", @@ -1033,8 +1057,11 @@ async def test_update_remove_config_entries(hass, device_registry, update_events async def test_update_suggested_area( - hass, device_registry, area_registry, update_events -): + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + area_registry: ar.AreaRegistry, + update_events, +) -> None: """Verify that we can update the suggested area version of a device.""" entry = device_registry.async_get_or_create( config_entry_id="1234", @@ -1083,7 +1110,9 @@ async def test_update_suggested_area( assert updated_entry.suggested_area == "Other" -async def test_cleanup_device_registry(hass, device_registry): +async def test_cleanup_device_registry( + hass: HomeAssistant, device_registry: dr.DeviceRegistry +) -> None: """Test cleanup works.""" config_entry = MockConfigEntry(domain="hue") config_entry.add_to_hass(hass) @@ -1115,8 +1144,8 @@ async def test_cleanup_device_registry(hass, device_registry): async def test_cleanup_device_registry_removes_expired_orphaned_devices( - hass, device_registry -): + hass: HomeAssistant, device_registry: dr.DeviceRegistry +) -> None: """Test cleanup removes expired orphaned devices.""" config_entry = MockConfigEntry(domain="hue") config_entry.add_to_hass(hass) @@ -1197,7 +1226,9 @@ async def test_cleanup_entity_registry_change(hass: HomeAssistant) -> None: assert len(mock_call.mock_calls) == 2 -async def test_restore_device(hass, device_registry, update_events): +async def test_restore_device( + hass: HomeAssistant, device_registry: dr.DeviceRegistry, update_events +) -> None: """Make sure device id is stable.""" entry = device_registry.async_get_or_create( config_entry_id="123", @@ -1256,7 +1287,9 @@ async def test_restore_device(hass, device_registry, update_events): assert "changes" not in update_events[3] -async def test_restore_simple_device(hass, device_registry, update_events): +async def test_restore_simple_device( + hass: HomeAssistant, device_registry: dr.DeviceRegistry, update_events +) -> None: """Make sure device id is stable.""" entry = device_registry.async_get_or_create( config_entry_id="123", @@ -1305,7 +1338,9 @@ async def test_restore_simple_device(hass, device_registry, update_events): assert "changes" not in update_events[3] -async def test_restore_shared_device(hass, device_registry, update_events): +async def test_restore_shared_device( + hass: HomeAssistant, device_registry: dr.DeviceRegistry, update_events +) -> None: """Make sure device id is stable for shared devices.""" entry = device_registry.async_get_or_create( config_entry_id="123", @@ -1416,7 +1451,9 @@ async def test_restore_shared_device(hass, device_registry, update_events): } -async def test_get_or_create_empty_then_set_default_values(device_registry): +async def test_get_or_create_empty_then_set_default_values( + device_registry: dr.DeviceRegistry, +) -> None: """Test creating an entry, then setting default name, model, manufacturer.""" entry = device_registry.async_get_or_create( identifiers={("bridgeid", "0123")}, config_entry_id="1234" @@ -1448,7 +1485,9 @@ async def test_get_or_create_empty_then_set_default_values(device_registry): assert entry.manufacturer == "default manufacturer 1" -async def test_get_or_create_empty_then_update(device_registry): +async def test_get_or_create_empty_then_update( + device_registry: dr.DeviceRegistry, +) -> None: """Test creating an entry, then setting name, model, manufacturer.""" entry = device_registry.async_get_or_create( identifiers={("bridgeid", "0123")}, config_entry_id="1234" @@ -1480,7 +1519,9 @@ async def test_get_or_create_empty_then_update(device_registry): assert entry.manufacturer == "manufacturer 1" -async def test_get_or_create_sets_default_values(device_registry): +async def test_get_or_create_sets_default_values( + device_registry: dr.DeviceRegistry, +) -> None: """Test creating an entry, then setting default name, model, manufacturer.""" entry = device_registry.async_get_or_create( config_entry_id="1234", @@ -1506,8 +1547,8 @@ async def test_get_or_create_sets_default_values(device_registry): async def test_verify_suggested_area_does_not_overwrite_area_id( - device_registry, area_registry -): + device_registry: dr.DeviceRegistry, area_registry: ar.AreaRegistry +) -> None: """Make sure suggested area does not override a set area id.""" game_room_area = area_registry.async_create("Game Room") @@ -1539,7 +1580,9 @@ async def test_verify_suggested_area_does_not_overwrite_area_id( assert entry2.area_id == game_room_area.id -async def test_disable_config_entry_disables_devices(hass, device_registry): +async def test_disable_config_entry_disables_devices( + hass: HomeAssistant, device_registry: dr.DeviceRegistry +) -> None: """Test that we disable entities tied to a config entry.""" config_entry = MockConfigEntry(domain="light") config_entry.add_to_hass(hass) @@ -1580,8 +1623,8 @@ async def test_disable_config_entry_disables_devices(hass, device_registry): async def test_only_disable_device_if_all_config_entries_are_disabled( - hass, device_registry -): + hass: HomeAssistant, device_registry: dr.DeviceRegistry +) -> None: """Test that we only disable device if all related config entries are disabled.""" config_entry1 = MockConfigEntry(domain="light") config_entry1.add_to_hass(hass) diff --git a/tests/helpers/test_discovery.py b/tests/helpers/test_discovery.py index a3913fd9599..2900cb2c09e 100644 --- a/tests/helpers/test_discovery.py +++ b/tests/helpers/test_discovery.py @@ -24,7 +24,7 @@ def mock_setup_component(): yield mock -async def test_listen(hass, mock_setup_component): +async def test_listen(hass: HomeAssistant, mock_setup_component) -> None: """Test discovery listen/discover combo.""" calls_single = [] @@ -50,7 +50,7 @@ async def test_listen(hass, mock_setup_component): assert calls_single[0] == ("test service", "discovery info") -async def test_platform(hass, mock_setup_component): +async def test_platform(hass: HomeAssistant, mock_setup_component) -> None: """Test discover platform method.""" calls = [] diff --git a/tests/helpers/test_discovery_flow.py b/tests/helpers/test_discovery_flow.py index 4019be80315..3b20782f5b4 100644 --- a/tests/helpers/test_discovery_flow.py +++ b/tests/helpers/test_discovery_flow.py @@ -1,11 +1,10 @@ """Test the discovery flow helper.""" - from unittest.mock import AsyncMock, call, patch import pytest from homeassistant import config_entries -from homeassistant.core import EVENT_HOMEASSISTANT_STARTED, CoreState +from homeassistant.core import EVENT_HOMEASSISTANT_STARTED, CoreState, HomeAssistant from homeassistant.helpers import discovery_flow @@ -18,7 +17,7 @@ def mock_flow_init(hass): yield mock_init -async def test_async_create_flow(hass, mock_flow_init): +async def test_async_create_flow(hass: HomeAssistant, mock_flow_init) -> None: """Test we can create a flow.""" discovery_flow.async_create_flow( hass, @@ -35,7 +34,9 @@ async def test_async_create_flow(hass, mock_flow_init): ] -async def test_async_create_flow_deferred_until_started(hass, mock_flow_init): +async def test_async_create_flow_deferred_until_started( + hass: HomeAssistant, mock_flow_init +) -> None: """Test flows are deferred until started.""" hass.state = CoreState.stopped discovery_flow.async_create_flow( @@ -57,8 +58,8 @@ async def test_async_create_flow_deferred_until_started(hass, mock_flow_init): async def test_async_create_flow_checks_existing_flows_after_startup( - hass, mock_flow_init -): + hass: HomeAssistant, mock_flow_init +) -> None: """Test existing flows prevent an identical ones from being after startup.""" hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED) with patch( @@ -75,8 +76,8 @@ async def test_async_create_flow_checks_existing_flows_after_startup( async def test_async_create_flow_checks_existing_flows_before_startup( - hass, mock_flow_init -): + hass: HomeAssistant, mock_flow_init +) -> None: """Test existing flows prevent an identical ones from being created before startup.""" hass.state = CoreState.stopped for _ in range(2): diff --git a/tests/helpers/test_dispatcher.py b/tests/helpers/test_dispatcher.py index 639157607b3..e30aaa6e0d9 100644 --- a/tests/helpers/test_dispatcher.py +++ b/tests/helpers/test_dispatcher.py @@ -131,7 +131,9 @@ async def test_simple_function_multiargs(hass: HomeAssistant) -> None: @pytest.mark.no_fail_on_log_exception -async def test_callback_exception_gets_logged(hass, caplog): +async def test_callback_exception_gets_logged( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test exception raised by signal handler.""" @callback diff --git a/tests/helpers/test_entity.py b/tests/helpers/test_entity.py index 546565d744d..4b505c894b5 100644 --- a/tests/helpers/test_entity.py +++ b/tests/helpers/test_entity.py @@ -1,5 +1,4 @@ """Test the entity helper.""" - import asyncio import dataclasses from datetime import timedelta @@ -123,7 +122,9 @@ class TestHelpersEntity: assert state.attributes.get(ATTR_DEVICE_CLASS) == "test_class" -async def test_warn_slow_update(hass, caplog): +async def test_warn_slow_update( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Warn we log when entity update takes a long time.""" update_call = False @@ -147,7 +148,9 @@ async def test_warn_slow_update(hass, caplog): assert update_call -async def test_warn_slow_update_with_exception(hass, caplog): +async def test_warn_slow_update_with_exception( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Warn we log when entity update takes a long time and trow exception.""" update_call = False @@ -172,7 +175,9 @@ async def test_warn_slow_update_with_exception(hass, caplog): assert update_call -async def test_warn_slow_device_update_disabled(hass, caplog): +async def test_warn_slow_device_update_disabled( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Disable slow update warning with async_device_update.""" update_call = False @@ -595,7 +600,9 @@ async def test_set_context_expired(hass: HomeAssistant) -> None: assert ent._context_set is None -async def test_warn_disabled(hass, caplog): +async def test_warn_disabled( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test we warn once if we write to a disabled entity.""" entry = er.RegistryEntry( entity_id="hello.world", @@ -678,7 +685,9 @@ async def test_capability_attrs(hass: HomeAssistant) -> None: assert state.attributes["always"] == "there" -async def test_warn_slow_write_state(hass, caplog): +async def test_warn_slow_write_state( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Check that we log a warning if reading properties takes too long.""" mock_entity = entity.Entity() mock_entity.hass = hass @@ -697,7 +706,9 @@ async def test_warn_slow_write_state(hass, caplog): ) in caplog.text -async def test_warn_slow_write_state_custom_component(hass, caplog): +async def test_warn_slow_write_state_custom_component( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Check that we log a warning if reading properties takes too long.""" class CustomComponentEntity(entity.Entity): @@ -861,7 +872,7 @@ async def test_entity_category_property(hass: HomeAssistant) -> None: ("diagnostic", entity.EntityCategory.DIAGNOSTIC), ), ) -def test_entity_category_schema(value, expected): +def test_entity_category_schema(value, expected) -> None: """Test entity category schema.""" schema = vol.Schema(entity.ENTITY_CATEGORIES_SCHEMA) result = schema(value) @@ -870,7 +881,7 @@ def test_entity_category_schema(value, expected): @pytest.mark.parametrize("value", (None, "non_existing")) -def test_entity_category_schema_error(value): +def test_entity_category_schema_error(value) -> None: """Test entity category schema.""" schema = vol.Schema(entity.ENTITY_CATEGORIES_SCHEMA) with pytest.raises( @@ -903,8 +914,8 @@ async def test_entity_description_fallback() -> None: ), ) async def test_friendly_name( - hass, has_entity_name, entity_name, expected_friendly_name -): + hass: HomeAssistant, has_entity_name, entity_name, expected_friendly_name +) -> None: """Test entity_id is influenced by entity name.""" async def async_setup_entry(hass, config_entry, async_add_entities): diff --git a/tests/helpers/test_entity_component.py b/tests/helpers/test_entity_component.py index 3104da02df5..ac5108cb28f 100644 --- a/tests/helpers/test_entity_component.py +++ b/tests/helpers/test_entity_component.py @@ -89,7 +89,9 @@ async def test_setup_recovers_when_setup_raises(hass: HomeAssistant) -> None: "homeassistant.helpers.entity_component.EntityComponent.async_setup_platform", ) @patch("homeassistant.setup.async_setup_component", return_value=True) -async def test_setup_does_discovery(mock_setup_component, mock_setup, hass): +async def test_setup_does_discovery( + mock_setup_component, mock_setup, hass: HomeAssistant +) -> None: """Test setup for discovery.""" component = EntityComponent(_LOGGER, DOMAIN, hass) @@ -106,7 +108,7 @@ async def test_setup_does_discovery(mock_setup_component, mock_setup, hass): @patch("homeassistant.helpers.entity_platform.async_track_time_interval") -async def test_set_scan_interval_via_config(mock_track, hass): +async def test_set_scan_interval_via_config(mock_track, hass: HomeAssistant) -> None: """Test the setting of the scan interval via configuration.""" def platform_setup(hass, config, add_entities, discovery_info=None): @@ -414,7 +416,9 @@ async def test_set_service_race(hass: HomeAssistant) -> None: assert not exception -async def test_extract_all_omit_entity_id(hass, caplog): +async def test_extract_all_omit_entity_id( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test extract all with None and *.""" component = EntityComponent(_LOGGER, DOMAIN, hass) await component.async_add_entities( @@ -428,7 +432,9 @@ async def test_extract_all_omit_entity_id(hass, caplog): ) -async def test_extract_all_use_match_all(hass, caplog): +async def test_extract_all_use_match_all( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test extract all with None and *.""" component = EntityComponent(_LOGGER, DOMAIN, hass) await component.async_add_entities( diff --git a/tests/helpers/test_entity_platform.py b/tests/helpers/test_entity_platform.py index 26e948fc5d2..441f47ff126 100644 --- a/tests/helpers/test_entity_platform.py +++ b/tests/helpers/test_entity_platform.py @@ -161,7 +161,7 @@ async def test_update_state_adds_entities_with_update_before_add_false( @patch("homeassistant.helpers.entity_platform.async_track_time_interval") -async def test_set_scan_interval_via_platform(mock_track, hass): +async def test_set_scan_interval_via_platform(mock_track, hass: HomeAssistant) -> None: """Test the setting of the scan interval via platform.""" def platform_setup(hass, config, add_entities, discovery_info=None): @@ -224,7 +224,9 @@ async def test_platform_warn_slow_setup(hass: HomeAssistant) -> None: assert mock_call().cancel.called -async def test_platform_error_slow_setup(hass, caplog): +async def test_platform_error_slow_setup( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(entity_platform, "SLOW_SETUP_MAX_WAIT", 0): called = [] @@ -449,7 +451,9 @@ async def test_async_remove_with_platform_update_finishes(hass: HomeAssistant) - assert len(hass.states.async_entity_ids()) == 0 -async def test_not_adding_duplicate_entities_with_unique_id(hass, caplog): +async def test_not_adding_duplicate_entities_with_unique_id( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test for not adding duplicate entities. Also test that the entity registry is not updated for duplicates. @@ -605,7 +609,9 @@ async def test_registry_respect_entity_disabled(hass: HomeAssistant) -> None: assert hass.states.async_entity_ids() == [] -async def test_unique_id_conflict_has_priority_over_disabled_entity(hass, caplog): +async def test_unique_id_conflict_has_priority_over_disabled_entity( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test that an entity that is not unique has priority over a disabled entity.""" component = EntityComponent(_LOGGER, DOMAIN, hass) entity1 = MockEntity( @@ -684,7 +690,9 @@ async def test_setup_entry( ) -async def test_setup_entry_platform_not_ready(hass, caplog): +async def test_setup_entry_platform_not_ready( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test when an entry is not ready yet.""" async_setup_entry = Mock(side_effect=PlatformNotReady) platform = MockPlatform(async_setup_entry=async_setup_entry) @@ -703,7 +711,9 @@ async def test_setup_entry_platform_not_ready(hass, caplog): assert len(mock_call_later.mock_calls) == 1 -async def test_setup_entry_platform_not_ready_with_message(hass, caplog): +async def test_setup_entry_platform_not_ready_with_message( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test when an entry is not ready yet that includes a message.""" async_setup_entry = Mock(side_effect=PlatformNotReady("lp0 on fire")) platform = MockPlatform(async_setup_entry=async_setup_entry) @@ -724,7 +734,9 @@ async def test_setup_entry_platform_not_ready_with_message(hass, caplog): assert len(mock_call_later.mock_calls) == 1 -async def test_setup_entry_platform_not_ready_from_exception(hass, caplog): +async def test_setup_entry_platform_not_ready_from_exception( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test when an entry is not ready yet that includes the causing exception string.""" original_exception = HomeAssistantError("The device dropped the connection") platform_exception = PlatformNotReady() @@ -1022,7 +1034,9 @@ async def test_device_info_not_overrides(hass: HomeAssistant) -> None: assert device2.model == "test-model" -async def test_device_info_invalid_url(hass, caplog): +async def test_device_info_invalid_url( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test device info is forwarded correctly.""" registry = dr.async_get(hass) registry.async_get_or_create( @@ -1071,7 +1085,9 @@ async def test_device_info_invalid_url(hass, caplog): ) -async def test_device_info_homeassistant_url(hass, caplog): +async def test_device_info_homeassistant_url( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test device info with homeassistant URL.""" registry = dr.async_get(hass) registry.async_get_or_create( @@ -1115,7 +1131,9 @@ async def test_device_info_homeassistant_url(hass, caplog): assert device.configuration_url == "homeassistant://config/mqtt" -async def test_device_info_change_to_no_url(hass, caplog): +async def test_device_info_change_to_no_url( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test device info changes to no URL.""" registry = dr.async_get(hass) registry.async_get_or_create( @@ -1184,7 +1202,7 @@ async def test_entity_disabled_by_integration(hass: HomeAssistant) -> None: assert entry_disabled.disabled_by is er.RegistryEntryDisabler.INTEGRATION -async def test_entity_disabled_by_device(hass: HomeAssistant): +async def test_entity_disabled_by_device(hass: HomeAssistant) -> None: """Test entity disabled by device.""" connections = {(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")} @@ -1303,7 +1321,9 @@ async def test_override_restored_entities( assert state.state == "on" -async def test_platform_with_no_setup(hass, caplog): +async def test_platform_with_no_setup( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test setting up a platform that does not support setup.""" entity_platform = MockEntityPlatform( hass, domain="mock-integration", platform_name="mock-platform", platform=None @@ -1379,8 +1399,10 @@ class MockBlockingEntity(MockEntity): async def test_setup_entry_with_entities_that_block_forever( - hass, caplog, entity_registry -): + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + entity_registry: er.EntityRegistry, +) -> None: """Test we cancel adding entities when we reach the timeout.""" async def async_setup_entry(hass, config_entry, async_add_entities): @@ -1465,8 +1487,8 @@ class SlowEntity(MockEntity): ), ) async def test_entity_name_influences_entity_id( - hass, has_entity_name, entity_name, expected_entity_id -): + hass: HomeAssistant, has_entity_name, entity_name, expected_entity_id +) -> None: """Test entity_id is influenced by entity name.""" registry = er.async_get(hass) diff --git a/tests/helpers/test_entity_registry.py b/tests/helpers/test_entity_registry.py index 3a4f983a474..79d6de32904 100644 --- a/tests/helpers/test_entity_registry.py +++ b/tests/helpers/test_entity_registry.py @@ -1,4 +1,5 @@ """Tests for the Entity Registry.""" +from typing import Any from unittest.mock import patch import pytest @@ -33,7 +34,9 @@ def update_events(hass): return events -async def test_get_or_create_returns_same_entry(hass, entity_registry, update_events): +async def test_get_or_create_returns_same_entry( + hass: HomeAssistant, entity_registry: er.EntityRegistry, update_events +) -> None: """Make sure we do not duplicate entries.""" entry = entity_registry.async_get_or_create("light", "hue", "1234") entry2 = entity_registry.async_get_or_create("light", "hue", "1234") @@ -48,7 +51,7 @@ async def test_get_or_create_returns_same_entry(hass, entity_registry, update_ev assert update_events[0]["entity_id"] == entry.entity_id -def test_get_or_create_suggested_object_id(entity_registry): +def test_get_or_create_suggested_object_id(entity_registry: er.EntityRegistry) -> None: """Test that suggested_object_id works.""" entry = entity_registry.async_get_or_create( "light", "hue", "1234", suggested_object_id="beer" @@ -57,7 +60,7 @@ def test_get_or_create_suggested_object_id(entity_registry): assert entry.entity_id == "light.beer" -def test_get_or_create_updates_data(entity_registry): +def test_get_or_create_updates_data(entity_registry: er.EntityRegistry) -> None: """Test that we update data in get_or_create.""" orig_config_entry = MockConfigEntry(domain="light") @@ -194,7 +197,9 @@ def test_get_or_create_updates_data(entity_registry): ) -def test_get_or_create_suggested_object_id_conflict_register(entity_registry): +def test_get_or_create_suggested_object_id_conflict_register( + entity_registry: er.EntityRegistry, +) -> None: """Test that we don't generate an entity id that is already registered.""" entry = entity_registry.async_get_or_create( "light", "hue", "1234", suggested_object_id="beer" @@ -207,14 +212,16 @@ def test_get_or_create_suggested_object_id_conflict_register(entity_registry): assert entry2.entity_id == "light.beer_2" -def test_get_or_create_suggested_object_id_conflict_existing(hass, entity_registry): +def test_get_or_create_suggested_object_id_conflict_existing( + hass: HomeAssistant, entity_registry: er.EntityRegistry +) -> None: """Test that we don't generate an entity id that currently exists.""" hass.states.async_set("light.hue_1234", "on") entry = entity_registry.async_get_or_create("light", "hue", "1234") assert entry.entity_id == "light.hue_1234_2" -def test_create_triggers_save(entity_registry): +def test_create_triggers_save(entity_registry: er.EntityRegistry) -> None: """Test that registering entry triggers a save.""" with patch.object(entity_registry, "async_schedule_save") as mock_schedule_save: entity_registry.async_get_or_create("light", "hue", "1234") @@ -222,7 +229,9 @@ def test_create_triggers_save(entity_registry): assert len(mock_schedule_save.mock_calls) == 1 -async def test_loading_saving_data(hass, entity_registry): +async def test_loading_saving_data( + hass: HomeAssistant, entity_registry: er.EntityRegistry +) -> None: """Test that we load/save data correctly.""" mock_config = MockConfigEntry(domain="light") @@ -293,7 +302,9 @@ async def test_loading_saving_data(hass, entity_registry): assert new_entry2.unit_of_measurement == "initial-unit_of_measurement" -def test_generate_entity_considers_registered_entities(entity_registry): +def test_generate_entity_considers_registered_entities( + entity_registry: er.EntityRegistry, +) -> None: """Test that we don't create entity id that are already registered.""" entry = entity_registry.async_get_or_create("light", "hue", "1234") assert entry.entity_id == "light.hue_1234" @@ -303,7 +314,9 @@ def test_generate_entity_considers_registered_entities(entity_registry): ) -def test_generate_entity_considers_existing_entities(hass, entity_registry): +def test_generate_entity_considers_existing_entities( + hass: HomeAssistant, entity_registry: er.EntityRegistry +) -> None: """Test that we don't create entity id that currently exists.""" hass.states.async_set("light.kitchen", "on") assert ( @@ -312,7 +325,7 @@ def test_generate_entity_considers_existing_entities(hass, entity_registry): ) -def test_is_registered(entity_registry): +def test_is_registered(entity_registry: er.EntityRegistry) -> None: """Test that is_registered works.""" entry = entity_registry.async_get_or_create("light", "hue", "1234") assert entity_registry.async_is_registered(entry.entity_id) @@ -320,7 +333,9 @@ def test_is_registered(entity_registry): @pytest.mark.parametrize("load_registries", [False]) -async def test_filter_on_load(hass, hass_storage): +async def test_filter_on_load( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test we transform some data when loading from storage.""" hass_storage[er.STORAGE_KEY] = { "version": er.STORAGE_VERSION_MAJOR, @@ -401,7 +416,7 @@ async def test_filter_on_load(hass, hass_storage): assert entry_system_category.entity_category is None -def test_async_get_entity_id(entity_registry): +def test_async_get_entity_id(entity_registry: er.EntityRegistry) -> None: """Test that entity_id is returned.""" entry = entity_registry.async_get_or_create("light", "hue", "1234") assert entry.entity_id == "light.hue_1234" @@ -411,7 +426,9 @@ def test_async_get_entity_id(entity_registry): assert entity_registry.async_get_entity_id("light", "hue", "123") is None -async def test_updating_config_entry_id(hass, entity_registry, update_events): +async def test_updating_config_entry_id( + hass: HomeAssistant, entity_registry: er.EntityRegistry, update_events +) -> None: """Test that we update config entry id in registry.""" mock_config_1 = MockConfigEntry(domain="light", entry_id="mock-id-1") entry = entity_registry.async_get_or_create( @@ -435,7 +452,9 @@ async def test_updating_config_entry_id(hass, entity_registry, update_events): assert update_events[1]["changes"] == {"config_entry_id": "mock-id-1"} -async def test_removing_config_entry_id(hass, entity_registry, update_events): +async def test_removing_config_entry_id( + hass: HomeAssistant, entity_registry: er.EntityRegistry, update_events +) -> None: """Test that we update config entry id in registry.""" mock_config = MockConfigEntry(domain="light", entry_id="mock-id-1") @@ -456,7 +475,7 @@ async def test_removing_config_entry_id(hass, entity_registry, update_events): assert update_events[1]["entity_id"] == entry.entity_id -async def test_removing_area_id(entity_registry): +async def test_removing_area_id(entity_registry: er.EntityRegistry) -> None: """Make sure we can clear area id.""" entry = entity_registry.async_get_or_create("light", "hue", "5678") @@ -472,7 +491,7 @@ async def test_removing_area_id(entity_registry): @pytest.mark.parametrize("load_registries", [False]) -async def test_migration_1_1(hass, hass_storage): +async def test_migration_1_1(hass: HomeAssistant, hass_storage: dict[str, Any]) -> None: """Test migration from version 1.1.""" hass_storage[er.STORAGE_KEY] = { "version": 1, @@ -499,7 +518,7 @@ async def test_migration_1_1(hass, hass_storage): @pytest.mark.parametrize("load_registries", [False]) -async def test_migration_1_7(hass, hass_storage): +async def test_migration_1_7(hass: HomeAssistant, hass_storage: dict[str, Any]) -> None: """Test migration from version 1.7. This tests cleanup after frontend bug which incorrectly updated device_class @@ -570,7 +589,7 @@ async def test_migration_1_7(hass, hass_storage): assert entry.original_device_class == "class_by_integration" -async def test_update_entity_unique_id(entity_registry): +async def test_update_entity_unique_id(entity_registry: er.EntityRegistry) -> None: """Test entity's unique_id is updated.""" mock_config = MockConfigEntry(domain="light", entry_id="mock-id-1") @@ -596,7 +615,9 @@ async def test_update_entity_unique_id(entity_registry): ) -async def test_update_entity_unique_id_conflict(entity_registry): +async def test_update_entity_unique_id_conflict( + entity_registry: er.EntityRegistry, +) -> None: """Test migration raises when unique_id already in use.""" mock_config = MockConfigEntry(domain="light", entry_id="mock-id-1") entry = entity_registry.async_get_or_create( @@ -620,7 +641,7 @@ async def test_update_entity_unique_id_conflict(entity_registry): ) -async def test_update_entity_entity_id(entity_registry): +async def test_update_entity_entity_id(entity_registry: er.EntityRegistry) -> None: """Test entity's entity_id is updated.""" entry = entity_registry.async_get_or_create("light", "hue", "5678") assert ( @@ -641,7 +662,9 @@ async def test_update_entity_entity_id(entity_registry): assert entity_registry.async_get(new_entity_id) is not None -async def test_update_entity_entity_id_entity_id(hass: HomeAssistant, entity_registry): +async def test_update_entity_entity_id_entity_id( + hass: HomeAssistant, entity_registry: er.EntityRegistry +) -> None: """Test update raises when entity_id already in use.""" entry = entity_registry.async_get_or_create("light", "hue", "5678") entry2 = entity_registry.async_get_or_create("light", "hue", "1234") @@ -682,7 +705,7 @@ async def test_update_entity_entity_id_entity_id(hass: HomeAssistant, entity_reg assert entity_registry.async_get(state_entity_id) is None -async def test_update_entity(entity_registry): +async def test_update_entity(entity_registry: er.EntityRegistry) -> None: """Test updating entity.""" mock_config = MockConfigEntry(domain="light", entry_id="mock-id-1") entry = entity_registry.async_get_or_create( @@ -709,7 +732,7 @@ async def test_update_entity(entity_registry): entry = updated_entry -async def test_update_entity_options(entity_registry): +async def test_update_entity_options(entity_registry: er.EntityRegistry) -> None: """Test updating entity.""" mock_config = MockConfigEntry(domain="light", entry_id="mock-id-1") entry = entity_registry.async_get_or_create( @@ -734,7 +757,7 @@ async def test_update_entity_options(entity_registry): assert new_entry_2.options == {"light": {"minimum_brightness": 30}} -async def test_disabled_by(entity_registry): +async def test_disabled_by(entity_registry: er.EntityRegistry) -> None: """Test that we can disable an entry when we create it.""" entry = entity_registry.async_get_or_create( "light", "hue", "5678", disabled_by=er.RegistryEntryDisabler.HASS @@ -750,7 +773,9 @@ async def test_disabled_by(entity_registry): assert entry2.disabled_by is None -async def test_disabled_by_config_entry_pref(entity_registry): +async def test_disabled_by_config_entry_pref( + entity_registry: er.EntityRegistry, +) -> None: """Test config entry preference setting disabled_by.""" mock_config = MockConfigEntry( domain="light", @@ -917,7 +942,11 @@ async def test_async_get_device_class_lookup(hass: HomeAssistant) -> None: } -async def test_remove_device_removes_entities(hass, entity_registry, device_registry): +async def test_remove_device_removes_entities( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + device_registry: dr.DeviceRegistry, +) -> None: """Test that we remove entities tied to a device.""" config_entry = MockConfigEntry(domain="light") @@ -943,8 +972,10 @@ async def test_remove_device_removes_entities(hass, entity_registry, device_regi async def test_remove_config_entry_from_device_removes_entities( - hass, device_registry, entity_registry -): + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, +) -> None: """Test that we remove entities tied to a device when config entry is removed.""" config_entry_1 = MockConfigEntry(domain="hue") config_entry_2 = MockConfigEntry(domain="device_tracker") @@ -1007,8 +1038,10 @@ async def test_remove_config_entry_from_device_removes_entities( async def test_remove_config_entry_from_device_removes_entities_2( - hass, device_registry, entity_registry -): + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, +) -> None: """Test that we don't remove entities with no config entry when device is modified.""" config_entry_1 = MockConfigEntry(domain="hue") config_entry_2 = MockConfigEntry(domain="device_tracker") @@ -1047,7 +1080,11 @@ async def test_remove_config_entry_from_device_removes_entities_2( assert entity_registry.async_is_registered(entry_1.entity_id) -async def test_update_device_race(hass, device_registry, entity_registry): +async def test_update_device_race( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, +) -> None: """Test race when a device is created, updated and removed.""" config_entry = MockConfigEntry(domain="light") @@ -1079,7 +1116,11 @@ async def test_update_device_race(hass, device_registry, entity_registry): assert not entity_registry.async_is_registered(entry.entity_id) -async def test_disable_device_disables_entities(hass, device_registry, entity_registry): +async def test_disable_device_disables_entities( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, +) -> None: """Test that we disable entities tied to a device.""" config_entry = MockConfigEntry(domain="light") config_entry.add_to_hass(hass) @@ -1146,8 +1187,10 @@ async def test_disable_device_disables_entities(hass, device_registry, entity_re async def test_disable_config_entry_disables_entities( - hass, device_registry, entity_registry -): + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, +) -> None: """Test that we disable entities tied to a config entry.""" config_entry = MockConfigEntry(domain="light") config_entry.add_to_hass(hass) @@ -1214,8 +1257,10 @@ async def test_disable_config_entry_disables_entities( async def test_disabled_entities_excluded_from_entity_list( - hass, device_registry, entity_registry -): + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, +) -> None: """Test that disabled entities are excluded from async_entries_for_device.""" config_entry = MockConfigEntry(domain="light") @@ -1250,7 +1295,7 @@ async def test_disabled_entities_excluded_from_entity_list( assert entries == [entry1, entry2] -async def test_entity_max_length_exceeded(entity_registry): +async def test_entity_max_length_exceeded(entity_registry: er.EntityRegistry) -> None: """Test that an exception is raised when the max character length is exceeded.""" long_domain_name = ( @@ -1292,7 +1337,7 @@ async def test_entity_max_length_exceeded(entity_registry): assert new_id == "sensor." + long_entity_id_name[: 255 - 7 - 2] + "_3" -async def test_resolve_entity_ids(entity_registry): +async def test_resolve_entity_ids(entity_registry: er.EntityRegistry) -> None: """Test resolving entity IDs.""" entry1 = entity_registry.async_get_or_create( @@ -1401,7 +1446,9 @@ async def test_hidden_by_str_not_allowed(hass: HomeAssistant) -> None: reg.async_update_entity(entity_id, hidden_by=er.RegistryEntryHider.USER.value) -def test_migrate_entity_to_new_platform(hass, entity_registry): +def test_migrate_entity_to_new_platform( + hass: HomeAssistant, entity_registry: er.EntityRegistry +) -> None: """Test migrate_entity_to_new_platform.""" orig_config_entry = MockConfigEntry(domain="light") orig_unique_id = "5678" diff --git a/tests/helpers/test_event.py b/tests/helpers/test_event.py index 4a90c0638bc..fb0925c15d2 100644 --- a/tests/helpers/test_event.py +++ b/tests/helpers/test_event.py @@ -857,7 +857,9 @@ async def test_track_template(hass: HomeAssistant) -> None: assert iterate_calls[0][2].state == "on" -async def test_track_template_error(hass, caplog): +async def test_track_template_error( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test tracking template with error.""" template_error = Template("{{ (states.switch | lunch) > 0 }}", hass) error_calls = [] @@ -888,7 +890,9 @@ async def test_track_template_error(hass, caplog): assert "TemplateAssertionError" not in caplog.text -async def test_track_template_error_can_recover(hass, caplog): +async def test_track_template_error_can_recover( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test tracking template with error.""" hass.states.async_set("switch.data_system", "cow", {"opmode": 0}) template_error = Template( @@ -915,7 +919,9 @@ async def test_track_template_error_can_recover(hass, caplog): assert "UndefinedError" not in caplog.text -async def test_track_template_time_change(hass, caplog): +async def test_track_template_time_change( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test tracking template with time change.""" template_error = Template("{{ utcnow().minute % 2 == 0 }}", hass) calls = [] @@ -1399,7 +1405,9 @@ async def test_track_template_result_super_template_initially_false( "{% if states('sensor.test2') != 'unavailable' -%} {{'a' + 5}} {%- else -%} false {%- endif %}", ], ) -async def test_track_template_result_super_template_2(hass, availability_template): +async def test_track_template_result_super_template_2( + hass: HomeAssistant, availability_template +) -> None: """Test tracking template with super template listening to different entities.""" specific_runs = [] specific_runs_availability = [] @@ -1537,8 +1545,8 @@ async def test_track_template_result_super_template_2(hass, availability_templat ], ) async def test_track_template_result_super_template_2_initially_false( - hass, availability_template -): + hass: HomeAssistant, availability_template +) -> None: """Test tracking template with super template listening to different entities.""" specific_runs = [] specific_runs_availability = [] @@ -2136,7 +2144,9 @@ async def test_track_template_result_iterator(hass: HomeAssistant) -> None: assert filter_runs == ["", "sensor.new"] -async def test_track_template_result_errors(hass, caplog): +async def test_track_template_result_errors( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test tracking template with errors in the template.""" template_syntax_error = Template("{{states.switch", hass) @@ -3838,7 +3848,7 @@ async def test_periodic_task_duplicate_time(hass: HomeAssistant) -> None: # DST starts early morning March 28th 2021 @pytest.mark.freeze_time("2021-03-28 01:28:00+01:00") -async def test_periodic_task_entering_dst(hass, freezer): +async def test_periodic_task_entering_dst(hass: HomeAssistant, freezer) -> None: """Test periodic task behavior when entering dst.""" hass.config.set_time_zone("Europe/Vienna") specific_runs = [] @@ -3884,7 +3894,7 @@ async def test_periodic_task_entering_dst(hass, freezer): # DST starts early morning March 28th 2021 @pytest.mark.freeze_time("2021-03-28 01:59:59+01:00") -async def test_periodic_task_entering_dst_2(hass, freezer): +async def test_periodic_task_entering_dst_2(hass: HomeAssistant, freezer) -> None: """Test periodic task behavior when entering dst. This tests a task firing every second in the range 0..58 (not *:*:59) @@ -3935,7 +3945,7 @@ async def test_periodic_task_entering_dst_2(hass, freezer): # DST ends early morning October 31st 2021 @pytest.mark.freeze_time("2021-10-31 02:28:00+02:00") -async def test_periodic_task_leaving_dst(hass, freezer): +async def test_periodic_task_leaving_dst(hass: HomeAssistant, freezer) -> None: """Test periodic task behavior when leaving dst.""" hass.config.set_time_zone("Europe/Vienna") specific_runs = [] @@ -4009,7 +4019,7 @@ async def test_periodic_task_leaving_dst(hass, freezer): # DST ends early morning October 31st 2021 @pytest.mark.freeze_time("2021-10-31 02:28:00+02:00") -async def test_periodic_task_leaving_dst_2(hass, freezer): +async def test_periodic_task_leaving_dst_2(hass: HomeAssistant, freezer) -> None: """Test periodic task behavior when leaving dst.""" hass.config.set_time_zone("Europe/Vienna") specific_runs = [] @@ -4391,8 +4401,8 @@ async def test_async_track_entity_registry_updated_event(hass: HomeAssistant) -> async def test_async_track_entity_registry_updated_event_with_a_callback_that_throws( - hass, -): + hass: HomeAssistant, +) -> None: """Test tracking entity registry updates for an entity_id when one callback throws.""" entity_id = "switch.puppy_feeder" diff --git a/tests/helpers/test_frame.py b/tests/helpers/test_frame.py index 320b2c51c66..3086bebe09d 100644 --- a/tests/helpers/test_frame.py +++ b/tests/helpers/test_frame.py @@ -18,7 +18,9 @@ async def test_extract_frame_integration( assert found_frame == mock_integration_frame -async def test_extract_frame_integration_with_excluded_integration(caplog): +async def test_extract_frame_integration_with_excluded_integration( + caplog: pytest.LogCaptureFixture, +) -> None: """Test extracting the current frame from integration context.""" correct_frame = Mock( filename="/home/dev/homeassistant/components/mdns/light.py", @@ -55,7 +57,7 @@ async def test_extract_frame_integration_with_excluded_integration(caplog): assert found_frame == correct_frame -async def test_extract_frame_no_integration(caplog): +async def test_extract_frame_no_integration(caplog: pytest.LogCaptureFixture) -> None: """Test extracting the current frame without integration context.""" with patch( "homeassistant.helpers.frame.extract_stack", @@ -77,7 +79,7 @@ async def test_extract_frame_no_integration(caplog): @pytest.mark.usefixtures("mock_integration_frame") @patch.object(frame, "_REPORTED_INTEGRATIONS", set()) -async def test_prevent_flooding(caplog): +async def test_prevent_flooding(caplog: pytest.LogCaptureFixture) -> None: """Test to ensure a report is only written once to the log.""" what = "accessed hi instead of hello" @@ -96,7 +98,9 @@ async def test_prevent_flooding(caplog): assert len(frame._REPORTED_INTEGRATIONS) == 1 -async def test_report_missing_integration_frame(caplog): +async def test_report_missing_integration_frame( + caplog: pytest.LogCaptureFixture, +) -> None: """Test reporting when no integration is detected.""" what = "teststring" diff --git a/tests/helpers/test_httpx_client.py b/tests/helpers/test_httpx_client.py index eb6b971f132..f9473ffaf87 100644 --- a/tests/helpers/test_httpx_client.py +++ b/tests/helpers/test_httpx_client.py @@ -1,5 +1,4 @@ """Test the httpx client helper.""" - from unittest.mock import Mock, patch import httpx @@ -98,7 +97,9 @@ async def test_get_async_client_context_manager(hass: HomeAssistant) -> None: @patch("homeassistant.helpers.frame._REPORTED_INTEGRATIONS", set()) -async def test_warning_close_session_integration(hass, caplog): +async def test_warning_close_session_integration( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test log warning message when closing the session from integration context.""" with patch( "homeassistant.helpers.frame.extract_stack", @@ -131,7 +132,9 @@ async def test_warning_close_session_integration(hass, caplog): @patch("homeassistant.helpers.frame._REPORTED_INTEGRATIONS", set()) -async def test_warning_close_session_custom(hass, caplog): +async def test_warning_close_session_custom( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test log warning message when closing the session from custom context.""" with patch( "homeassistant.helpers.frame.extract_stack", diff --git a/tests/helpers/test_instance_id.py b/tests/helpers/test_instance_id.py index a8c040f48ba..453d18b1d2a 100644 --- a/tests/helpers/test_instance_id.py +++ b/tests/helpers/test_instance_id.py @@ -1,10 +1,12 @@ """Tests for instance ID helper.""" +from typing import Any from unittest.mock import patch +from homeassistant.core import HomeAssistant from homeassistant.helpers import instance_id -async def test_get_id_empty(hass, hass_storage): +async def test_get_id_empty(hass: HomeAssistant, hass_storage: dict[str, Any]) -> None: """Get unique ID.""" uuid = await instance_id.async_get(hass) assert uuid is not None @@ -12,7 +14,9 @@ async def test_get_id_empty(hass, hass_storage): assert hass_storage["core.uuid"]["data"]["uuid"] == uuid -async def test_get_id_migrate(hass, hass_storage): +async def test_get_id_migrate( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Migrate existing file.""" with patch( "homeassistant.util.json.load_json", return_value={"uuid": "1234"} diff --git a/tests/helpers/test_intent.py b/tests/helpers/test_intent.py index b706a8c7551..17c513fabb6 100644 --- a/tests/helpers/test_intent.py +++ b/tests/helpers/test_intent.py @@ -1,5 +1,4 @@ """Tests for the intent helpers.""" - import pytest import voluptuous as vol diff --git a/tests/helpers/test_issue_registry.py b/tests/helpers/test_issue_registry.py index 01c2d83fb46..21600b776c1 100644 --- a/tests/helpers/test_issue_registry.py +++ b/tests/helpers/test_issue_registry.py @@ -1,4 +1,6 @@ """Test the repairs websocket API.""" +from typing import Any + import pytest from homeassistant.core import HomeAssistant @@ -172,7 +174,9 @@ async def test_load_issues(hass: HomeAssistant) -> None: @pytest.mark.parametrize("load_registries", [False]) -async def test_loading_issues_from_storage(hass: HomeAssistant, hass_storage) -> None: +async def test_loading_issues_from_storage( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test loading stored issues on start.""" hass_storage[issue_registry.STORAGE_KEY] = { "version": issue_registry.STORAGE_VERSION_MAJOR, @@ -219,7 +223,7 @@ async def test_loading_issues_from_storage(hass: HomeAssistant, hass_storage) -> @pytest.mark.parametrize("load_registries", [False]) -async def test_migration_1_1(hass: HomeAssistant, hass_storage) -> None: +async def test_migration_1_1(hass: HomeAssistant, hass_storage: dict[str, Any]) -> None: """Test migration from version 1.1.""" hass_storage[issue_registry.STORAGE_KEY] = { "version": 1, diff --git a/tests/helpers/test_network.py b/tests/helpers/test_network.py index 1606842b752..b8fbfc9346b 100644 --- a/tests/helpers/test_network.py +++ b/tests/helpers/test_network.py @@ -32,7 +32,7 @@ def mock_current_request_mock(): yield mock_current_request -async def test_get_url_internal(hass: HomeAssistant): +async def test_get_url_internal(hass: HomeAssistant) -> None: """Test getting an instance URL when the user has set an internal URL.""" assert hass.config.internal_url is None @@ -174,7 +174,7 @@ async def test_get_url_internal(hass: HomeAssistant): _get_internal_url(hass, require_current_request=True, require_ssl=True) -async def test_get_url_internal_fallback(hass: HomeAssistant): +async def test_get_url_internal_fallback(hass: HomeAssistant) -> None: """Test getting an instance URL when the user has not set an internal URL.""" assert hass.config.internal_url is None @@ -230,7 +230,7 @@ async def test_get_url_internal_fallback(hass: HomeAssistant): _get_internal_url(hass, require_ssl=True) -async def test_get_url_external(hass: HomeAssistant): +async def test_get_url_external(hass: HomeAssistant) -> None: """Test getting an instance URL when the user has set an external URL.""" assert hass.config.external_url is None @@ -356,7 +356,7 @@ async def test_get_url_external(hass: HomeAssistant): _get_external_url(hass, require_current_request=True, require_ssl=True) -async def test_get_cloud_url(hass: HomeAssistant): +async def test_get_cloud_url(hass: HomeAssistant) -> None: """Test getting an instance URL when the user has set an external URL.""" assert hass.config.external_url is None hass.config.components.add("cloud") @@ -394,7 +394,7 @@ async def test_get_cloud_url(hass: HomeAssistant): _get_cloud_url(hass) -async def test_get_external_url_cloud_fallback(hass: HomeAssistant): +async def test_get_external_url_cloud_fallback(hass: HomeAssistant) -> None: """Test getting an external instance URL with cloud fallback.""" assert hass.config.external_url is None @@ -454,7 +454,7 @@ async def test_get_external_url_cloud_fallback(hass: HomeAssistant): ) -async def test_get_url(hass: HomeAssistant): +async def test_get_url(hass: HomeAssistant) -> None: """Test getting an instance URL.""" assert hass.config.external_url is None assert hass.config.internal_url is None @@ -552,7 +552,7 @@ async def test_get_url(hass: HomeAssistant): assert get_url(hass, allow_internal=False) -async def test_get_request_host(hass: HomeAssistant): +async def test_get_request_host(hass: HomeAssistant) -> None: """Test getting the host of the current web request from the request context.""" with pytest.raises(NoURLAvailableError): _get_request_host() @@ -567,7 +567,7 @@ async def test_get_request_host(hass: HomeAssistant): async def test_get_current_request_url_with_known_host( hass: HomeAssistant, current_request -): +) -> None: """Test getting current request URL with known hosts addresses.""" hass.config.api = Mock(use_ssl=False, port=8123, local_ip="127.0.0.1") assert hass.config.internal_url is None @@ -623,7 +623,7 @@ async def test_get_current_request_url_with_known_host( get_url(hass, require_current_request=True) -async def test_is_internal_request(hass: HomeAssistant, mock_current_request): +async def test_is_internal_request(hass: HomeAssistant, mock_current_request) -> None: """Test if accessing an instance on its internal URL.""" # Test with internal URL: http://example.local:8123 await async_process_ha_core_config( diff --git a/tests/helpers/test_reload.py b/tests/helpers/test_reload.py index fdc8ef31e1b..ad3b7ccb243 100644 --- a/tests/helpers/test_reload.py +++ b/tests/helpers/test_reload.py @@ -153,8 +153,8 @@ async def test_setup_reload_service_when_async_process_component_config_fails( async def test_setup_reload_service_with_platform_that_provides_async_reset_platform( - hass, -): + hass: HomeAssistant, +) -> None: """Test setting up a reload service using a platform that has its own async_reset_platform.""" component_setup = AsyncMock(return_value=True) diff --git a/tests/helpers/test_restore_state.py b/tests/helpers/test_restore_state.py index fdd3e4b8e18..1e8fa8b7fb4 100644 --- a/tests/helpers/test_restore_state.py +++ b/tests/helpers/test_restore_state.py @@ -1,5 +1,6 @@ """The tests for the Restore component.""" from datetime import datetime, timedelta +from typing import Any from unittest.mock import patch from homeassistant.const import EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP @@ -348,7 +349,9 @@ async def test_state_saved_on_remove(hass: HomeAssistant) -> None: assert set(state.attributes["complicated"]["value"]) == {1, 2, now.isoformat()} -async def test_restoring_invalid_entity_id(hass, hass_storage): +async def test_restoring_invalid_entity_id( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test restoring invalid entity IDs.""" entity = RestoreEntity() entity.hass = hass diff --git a/tests/helpers/test_schema_config_entry_flow.py b/tests/helpers/test_schema_config_entry_flow.py index 05e8b8c467c..9919a53839e 100644 --- a/tests/helpers/test_schema_config_entry_flow.py +++ b/tests/helpers/test_schema_config_entry_flow.py @@ -107,7 +107,7 @@ async def test_name(hass: HomeAssistant) -> None: @pytest.mark.parametrize("marker", (vol.Required, vol.Optional)) async def test_config_flow_advanced_option( hass: HomeAssistant, manager: data_entry_flow.FlowManager, marker -): +) -> None: """Test handling of advanced options in config flow.""" manager.hass = hass @@ -202,7 +202,7 @@ async def test_config_flow_advanced_option( @pytest.mark.parametrize("marker", (vol.Required, vol.Optional)) async def test_options_flow_advanced_option( hass: HomeAssistant, manager: data_entry_flow.FlowManager, marker -): +) -> None: """Test handling of advanced options in options flow.""" manager.hass = hass diff --git a/tests/helpers/test_script.py b/tests/helpers/test_script.py index 350672acce7..5328a1d38ed 100644 --- a/tests/helpers/test_script.py +++ b/tests/helpers/test_script.py @@ -1,5 +1,4 @@ """The tests for the Script component.""" - import asyncio from contextlib import contextmanager from datetime import timedelta @@ -139,7 +138,9 @@ def async_watch_for_action(script_obj, message): return flag -async def test_firing_event_basic(hass, caplog): +async def test_firing_event_basic( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test the firing of events.""" event = "test_event" context = Context() @@ -237,7 +238,9 @@ async def test_firing_event_template(hass: HomeAssistant) -> None: ) -async def test_calling_service_basic(hass, caplog): +async def test_calling_service_basic( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test the calling of a service.""" context = Context() calls = async_mock_service(hass, "test", "script") @@ -441,7 +444,9 @@ async def test_multiple_runs_no_wait(hass: HomeAssistant) -> None: assert len(calls) == 4 -async def test_activating_scene(hass, caplog): +async def test_activating_scene( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test the activation of a scene.""" context = Context() calls = async_mock_service(hass, scene.DOMAIN, SERVICE_TURN_ON) @@ -466,7 +471,7 @@ async def test_activating_scene(hass, caplog): @pytest.mark.parametrize("count", [1, 3]) -async def test_stop_no_wait(hass, count): +async def test_stop_no_wait(hass: HomeAssistant, count) -> None: """Test stopping script.""" service_started_sem = asyncio.Semaphore(0) finish_service_event = asyncio.Event() @@ -616,7 +621,9 @@ async def test_delay_template_ok(hass: HomeAssistant) -> None: ) -async def test_delay_template_invalid(hass, caplog): +async def test_delay_template_invalid( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test the delay as a template that fails.""" event = "test_event" events = async_capture_events(hass, event) @@ -677,7 +684,9 @@ async def test_delay_template_complex_ok(hass: HomeAssistant) -> None: ) -async def test_delay_template_complex_invalid(hass, caplog): +async def test_delay_template_complex_invalid( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test the delay with a complex template that fails.""" event = "test_event" events = async_capture_events(hass, event) @@ -751,7 +760,7 @@ async def test_cancel_delay(hass: HomeAssistant) -> None: @pytest.mark.parametrize("action_type", ["template", "trigger"]) -async def test_wait_basic(hass, action_type): +async def test_wait_basic(hass: HomeAssistant, action_type) -> None: """Test wait actions.""" wait_alias = "wait step" action = {"alias": wait_alias} @@ -847,7 +856,7 @@ async def test_wait_for_trigger_variables(hass: HomeAssistant) -> None: @pytest.mark.parametrize("action_type", ["template", "trigger"]) -async def test_wait_basic_times_out(hass, action_type): +async def test_wait_basic_times_out(hass: HomeAssistant, action_type) -> None: """Test wait actions times out when the action does not happen.""" wait_alias = "wait step" action = {"alias": wait_alias} @@ -896,7 +905,7 @@ async def test_wait_basic_times_out(hass, action_type): @pytest.mark.parametrize("action_type", ["template", "trigger"]) -async def test_multiple_runs_wait(hass, action_type): +async def test_multiple_runs_wait(hass: HomeAssistant, action_type) -> None: """Test multiple runs with wait in script.""" event = "test_event" events = async_capture_events(hass, event) @@ -951,7 +960,7 @@ async def test_multiple_runs_wait(hass, action_type): @pytest.mark.parametrize("action_type", ["template", "trigger"]) -async def test_cancel_wait(hass, action_type): +async def test_cancel_wait(hass: HomeAssistant, action_type) -> None: """Test the cancelling while wait is present.""" event = "test_event" events = async_capture_events(hass, event) @@ -1047,7 +1056,9 @@ async def test_wait_template_not_schedule(hass: HomeAssistant) -> None: "timeout_param", [5, "{{ 5 }}", {"seconds": 5}, {"seconds": "{{ 5 }}"}] ) @pytest.mark.parametrize("action_type", ["template", "trigger"]) -async def test_wait_timeout(hass, caplog, timeout_param, action_type): +async def test_wait_timeout( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture, timeout_param, action_type +) -> None: """Test the wait timeout option.""" event = "test_event" events = async_capture_events(hass, event) @@ -1113,8 +1124,8 @@ async def test_wait_timeout(hass, caplog, timeout_param, action_type): ) @pytest.mark.parametrize("action_type", ["template", "trigger"]) async def test_wait_continue_on_timeout( - hass, continue_on_timeout, n_events, action_type -): + hass: HomeAssistant, continue_on_timeout, n_events, action_type +) -> None: """Test the wait continue_on_timeout option.""" event = "test_event" events = async_capture_events(hass, event) @@ -1274,7 +1285,7 @@ async def test_wait_template_with_utcnow_no_match(hass: HomeAssistant) -> None: @pytest.mark.parametrize("mode", ["no_timeout", "timeout_finish", "timeout_not_finish"]) @pytest.mark.parametrize("action_type", ["template", "trigger"]) -async def test_wait_variables_out(hass, mode, action_type): +async def test_wait_variables_out(hass: HomeAssistant, mode, action_type) -> None: """Test the wait output variable.""" event = "test_event" events = async_capture_events(hass, event) @@ -1342,7 +1353,9 @@ async def test_wait_variables_out(hass, mode, action_type): assert float(remaining) == 0.0 -async def test_wait_for_trigger_bad(hass, caplog): +async def test_wait_for_trigger_bad( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test bad wait_for_trigger.""" sequence = cv.SCRIPT_SCHEMA( {"wait_for_trigger": {"platform": "state", "entity_id": "sensor.abc"}} @@ -1374,7 +1387,9 @@ async def test_wait_for_trigger_bad(hass, caplog): ) -async def test_wait_for_trigger_generated_exception(hass, caplog): +async def test_wait_for_trigger_generated_exception( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test bad wait_for_trigger.""" sequence = cv.SCRIPT_SCHEMA( {"wait_for_trigger": {"platform": "state", "entity_id": "sensor.abc"}} @@ -1408,7 +1423,9 @@ async def test_wait_for_trigger_generated_exception(hass, caplog): ) -async def test_condition_warning(hass, caplog): +async def test_condition_warning( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test warning on condition.""" event = "test_event" events = async_capture_events(hass, event) @@ -1447,7 +1464,9 @@ async def test_condition_warning(hass, caplog): ) -async def test_condition_basic(hass, caplog): +async def test_condition_basic( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test if we can use conditions in a script.""" event = "test_event" events = async_capture_events(hass, event) @@ -1502,7 +1521,9 @@ async def test_condition_basic(hass, caplog): ) -async def test_condition_subscript(hass, caplog): +async def test_condition_subscript( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test failing conditions in a subscript don't stop the parent script.""" event = "test_event" events = async_capture_events(hass, event) @@ -1551,7 +1572,9 @@ async def test_condition_subscript(hass, caplog): ) -async def test_and_default_condition(hass, caplog): +async def test_and_default_condition( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test that a list of conditions evaluates as AND.""" alias = "condition step" sequence = cv.SCRIPT_SCHEMA( @@ -1587,7 +1610,9 @@ async def test_and_default_condition(hass, caplog): assert f"Test condition {alias}: False" in caplog.text -async def test_shorthand_template_condition(hass, caplog): +async def test_shorthand_template_condition( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test if we can use shorthand template conditions in a script.""" event = "test_event" events = async_capture_events(hass, event) @@ -1641,7 +1666,9 @@ async def test_shorthand_template_condition(hass, caplog): ) -async def test_condition_validation(hass, caplog): +async def test_condition_validation( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test if we can use conditions which validate late in a script.""" registry = er.async_get(hass) entry = registry.async_get_or_create( @@ -1716,7 +1743,7 @@ async def test_condition_validation(hass, caplog): @patch("homeassistant.helpers.script.condition.async_from_config") -async def test_condition_created_once(async_from_config, hass): +async def test_condition_created_once(async_from_config, hass: HomeAssistant) -> None: """Test that the conditions do not get created multiple times.""" sequence = cv.SCRIPT_SCHEMA( { @@ -1764,7 +1791,9 @@ async def test_condition_all_cached(hass: HomeAssistant) -> None: @pytest.mark.parametrize("count", [3, script.ACTION_TRACE_NODE_MAX_LEN * 2]) -async def test_repeat_count(hass, caplog, count): +async def test_repeat_count( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture, count +) -> None: """Test repeat action w/ count option.""" event = "test_event" events = async_capture_events(hass, event) @@ -1827,7 +1856,9 @@ async def test_repeat_count(hass, caplog, count): ) -async def test_repeat_count_0(hass, caplog): +async def test_repeat_count_0( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test repeat action w/ count option.""" event = "test_event" events = async_capture_events(hass, event) @@ -2058,7 +2089,9 @@ async def test_repeat_for_each_non_list_template(hass: HomeAssistant) -> None: ) -async def test_repeat_for_each_invalid_template(hass: HomeAssistant, caplog) -> None: +async def test_repeat_for_each_invalid_template( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test repeat action using for each with an invalid template.""" events = async_capture_events(hass, "test_event") sequence = cv.SCRIPT_SCHEMA( @@ -2092,7 +2125,9 @@ async def test_repeat_for_each_invalid_template(hass: HomeAssistant, caplog) -> @pytest.mark.parametrize("condition", ["while", "until"]) -async def test_repeat_condition_warning(hass, caplog, condition): +async def test_repeat_condition_warning( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture, condition +) -> None: """Test warning on repeat conditions.""" event = "test_event" events = async_capture_events(hass, event) @@ -2154,7 +2189,9 @@ async def test_repeat_condition_warning(hass, caplog, condition): @pytest.mark.parametrize("condition", ["while", "until"]) @pytest.mark.parametrize("direct_template", [False, True]) -async def test_repeat_conditional(hass, condition, direct_template): +async def test_repeat_conditional( + hass: HomeAssistant, condition, direct_template +) -> None: """Test repeat action w/ while option.""" event = "test_event" events = async_capture_events(hass, event) @@ -2226,7 +2263,9 @@ async def test_repeat_conditional(hass, condition, direct_template): assert event.data.get("index") == index + 1 -async def test_repeat_until_condition_validation(hass, caplog): +async def test_repeat_until_condition_validation( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test if we can use conditions in repeat until conditions which validate late.""" registry = er.async_get(hass) entry = registry.async_get_or_create( @@ -2286,7 +2325,9 @@ async def test_repeat_until_condition_validation(hass, caplog): ) -async def test_repeat_while_condition_validation(hass, caplog): +async def test_repeat_while_condition_validation( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test if we can use conditions in repeat while conditions which validate late.""" registry = er.async_get(hass) entry = registry.async_get_or_create( @@ -2347,7 +2388,7 @@ async def test_repeat_while_condition_validation(hass, caplog): @pytest.mark.parametrize("condition", ["while", "until"]) -async def test_repeat_var_in_condition(hass, condition): +async def test_repeat_var_in_condition(hass: HomeAssistant, condition) -> None: """Test repeat action w/ while option.""" event = "test_event" events = async_capture_events(hass, event) @@ -2439,7 +2480,9 @@ async def test_repeat_var_in_condition(hass, condition): (MappingProxyType({"x": 1}), {"repeat": None, "x": 1}, 1), ], ) -async def test_repeat_nested(hass, variables, first_last, inside_x): +async def test_repeat_nested( + hass: HomeAssistant, variables, first_last, inside_x +) -> None: """Test nested repeats.""" event = "test_event" events = async_capture_events(hass, event) @@ -2576,7 +2619,9 @@ async def test_repeat_nested(hass, variables, first_last, inside_x): assert_action_trace(expected_trace) -async def test_choose_warning(hass, caplog): +async def test_choose_warning( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test warning on choose.""" event = "test_event" events = async_capture_events(hass, event) @@ -2628,7 +2673,9 @@ async def test_choose_warning(hass, caplog): @pytest.mark.parametrize( ("var", "result"), [(1, "first"), (2, "second"), (3, "default")] ) -async def test_choose(hass, caplog, var, result): +async def test_choose( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture, var, result +) -> None: """Test choose action.""" event = "test_event" events = async_capture_events(hass, event) @@ -2711,7 +2758,9 @@ async def test_choose(hass, caplog, var, result): assert_action_trace(expected_trace) -async def test_choose_condition_validation(hass, caplog): +async def test_choose_condition_validation( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test if we can use conditions in choose actions which validate late.""" registry = er.async_get(hass) entry = registry.async_get_or_create( @@ -2801,7 +2850,9 @@ async def test_choose_condition_validation(hass, caplog): {"choose": [], "default": {"event": "abc"}}, ], ) -async def test_multiple_runs_repeat_choose(hass, caplog, action): +async def test_multiple_runs_repeat_choose( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture, action +) -> None: """Test parallel runs with repeat & choose actions & max_runs > default.""" max_runs = script.DEFAULT_MAX + 1 script_obj = script.Script( @@ -3786,7 +3837,9 @@ def does_not_raise(): yield -async def test_script_mode_single(hass, caplog): +async def test_script_mode_single( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test overlapping runs with max_runs = 1.""" event = "test_event" events = async_capture_events(hass, event) @@ -3831,7 +3884,13 @@ async def test_script_mode_single(hass, caplog): @pytest.mark.parametrize( ("script_mode", "max_runs"), [("single", 1), ("parallel", 2), ("queued", 2)] ) -async def test_max_exceeded(hass, caplog, max_exceeded, script_mode, max_runs): +async def test_max_exceeded( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + max_exceeded, + script_mode, + max_runs, +) -> None: """Test max_exceeded option.""" sequence = cv.SCRIPT_SCHEMA( {"wait_template": "{{ states.switch.test.state == 'off' }}"} @@ -3885,7 +3944,13 @@ async def test_max_exceeded(hass, caplog, max_exceeded, script_mode, max_runs): ("script_mode", "messages", "last_events"), [("restart", ["Restarting"], [2]), ("parallel", [], [2, 2])], ) -async def test_script_mode_2(hass, caplog, script_mode, messages, last_events): +async def test_script_mode_2( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + script_mode, + messages, + last_events, +) -> None: """Test overlapping runs with max_runs > 1.""" event = "test_event" events = async_capture_events(hass, event) @@ -4119,7 +4184,9 @@ async def test_script_mode_queued_stop(hass: HomeAssistant) -> None: assert script_obj.runs == 0 -async def test_script_logging(hass, caplog): +async def test_script_logging( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test script logging.""" script_obj = script.Script(hass, [], "Script with % Name", "test_domain") script_obj._log("Test message with name %s", 1) @@ -4127,7 +4194,9 @@ async def test_script_logging(hass, caplog): assert "Script with % Name: Test message with name 1" in caplog.text -async def test_shutdown_at(hass, caplog): +async def test_shutdown_at( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test stopping scripts at shutdown.""" delay_alias = "delay step" sequence = cv.SCRIPT_SCHEMA({"delay": {"seconds": 120}, "alias": delay_alias}) @@ -4156,7 +4225,9 @@ async def test_shutdown_at(hass, caplog): assert_action_trace(expected_trace) -async def test_shutdown_after(hass, caplog): +async def test_shutdown_after( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test stopping scripts at shutdown.""" delay_alias = "delay step" sequence = cv.SCRIPT_SCHEMA({"delay": {"seconds": 120}, "alias": delay_alias}) @@ -4192,7 +4263,9 @@ async def test_shutdown_after(hass, caplog): assert_action_trace(expected_trace) -async def test_start_script_after_shutdown(hass, caplog): +async def test_start_script_after_shutdown( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test starting scripts after shutdown is blocked.""" delay_alias = "delay step" sequence = cv.SCRIPT_SCHEMA({"delay": {"seconds": 120}, "alias": delay_alias}) @@ -4212,7 +4285,9 @@ async def test_start_script_after_shutdown(hass, caplog): assert "Home Assistant is shutting down, starting script blocked" in caplog.text -async def test_update_logger(hass, caplog): +async def test_update_logger( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test updating logger.""" sequence = cv.SCRIPT_SCHEMA({"event": "test_event"}) script_obj = script.Script(hass, sequence, "Test Name", "test_domain") @@ -4231,7 +4306,9 @@ async def test_update_logger(hass, caplog): assert log_name in caplog.text -async def test_started_action(hass, caplog): +async def test_started_action( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test the callback of started_action.""" event = "test_event" log_message = "The script started!" @@ -4250,7 +4327,9 @@ async def test_started_action(hass, caplog): assert log_message in caplog.text -async def test_set_variable(hass, caplog): +async def test_set_variable( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test setting variables in scripts.""" alias = "variables step" sequence = cv.SCRIPT_SCHEMA( @@ -4290,7 +4369,9 @@ async def test_set_variable(hass, caplog): assert_action_trace(expected_trace) -async def test_set_redefines_variable(hass, caplog): +async def test_set_redefines_variable( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test setting variables based on their current value.""" sequence = cv.SCRIPT_SCHEMA( [ @@ -4685,7 +4766,9 @@ async def test_platform_async_validate_action_config(hass: HomeAssistant) -> Non device_automation_validate_action_mock.assert_awaited() -async def test_stop_action(hass, caplog): +async def test_stop_action( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test if automation stops on calling the stop action.""" event = "test_event" events = async_capture_events(hass, event) @@ -4726,8 +4809,13 @@ async def test_stop_action(hass, caplog): ), ) async def test_stop_action_subscript( - hass, caplog, error, error_type, logmsg, script_execution -): + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + error, + error_type, + logmsg, + script_execution, +) -> None: """Test if automation stops on calling the stop action from a sub-script.""" event = "test_event" events = async_capture_events(hass, event) @@ -4777,7 +4865,9 @@ async def test_stop_action_subscript( ) -async def test_stop_action_with_error(hass, caplog): +async def test_stop_action_with_error( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test if automation fails on calling the error action.""" event = "test_event" events = async_capture_events(hass, event) @@ -5038,7 +5128,9 @@ async def test_disabled_actions( ) -async def test_condition_and_shorthand(hass, caplog): +async def test_condition_and_shorthand( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test if we can use the shorthand and conditions in a script.""" events = async_capture_events(hass, "test_event") sequence = cv.SCRIPT_SCHEMA( @@ -5077,7 +5169,9 @@ async def test_condition_and_shorthand(hass, caplog): ) -async def test_condition_or_shorthand(hass, caplog): +async def test_condition_or_shorthand( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test if we can use the shorthand or conditions in a script.""" events = async_capture_events(hass, "test_event") sequence = cv.SCRIPT_SCHEMA( @@ -5116,7 +5210,9 @@ async def test_condition_or_shorthand(hass, caplog): ) -async def test_condition_not_shorthand(hass, caplog): +async def test_condition_not_shorthand( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test if we can use the shorthand not conditions in a script.""" events = async_capture_events(hass, "test_event") sequence = cv.SCRIPT_SCHEMA( diff --git a/tests/helpers/test_selector.py b/tests/helpers/test_selector.py index 78d21bcc0a1..75e8a8dc542 100644 --- a/tests/helpers/test_selector.py +++ b/tests/helpers/test_selector.py @@ -17,7 +17,7 @@ FAKE_UUID = "a266a680b608c32770e6c45bfe6b8411" {"entity": None}, ), ) -def test_valid_base_schema(schema): +def test_valid_base_schema(schema) -> None: """Test base schema validation.""" selector.validate_selector(schema) @@ -33,7 +33,7 @@ def test_valid_base_schema(schema): {"device": {}, "entity": {}}, ), ) -def test_invalid_base_schema(schema): +def test_invalid_base_schema(schema) -> None: """Test base schema validation.""" with pytest.raises(vol.Invalid): selector.validate_selector(schema) @@ -109,7 +109,7 @@ def _test_selector( ), ), ) -def test_device_selector_schema(schema, valid_selections, invalid_selections): +def test_device_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test device selector.""" _test_selector("device", schema, valid_selections, invalid_selections) @@ -169,7 +169,7 @@ def test_device_selector_schema(schema, valid_selections, invalid_selections): ), ), ) -def test_entity_selector_schema(schema, valid_selections, invalid_selections): +def test_entity_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test entity selector.""" _test_selector("entity", schema, valid_selections, invalid_selections) @@ -216,7 +216,7 @@ def test_entity_selector_schema(schema, valid_selections, invalid_selections): ), ), ) -def test_area_selector_schema(schema, valid_selections, invalid_selections): +def test_area_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test area selector.""" _test_selector("area", schema, valid_selections, invalid_selections) @@ -244,7 +244,7 @@ def test_area_selector_schema(schema, valid_selections, invalid_selections): ({"mode": "box", "step": "any"}, (), ()), ), ) -def test_number_selector_schema(schema, valid_selections, invalid_selections): +def test_number_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test number selector.""" _test_selector("number", schema, valid_selections, invalid_selections) @@ -262,7 +262,7 @@ def test_number_selector_schema(schema, valid_selections, invalid_selections): }, ), ) -def test_number_selector_schema_error(schema): +def test_number_selector_schema_error(schema) -> None: """Test number selector.""" with pytest.raises(vol.Invalid): selector.validate_selector({"number": schema}) @@ -272,7 +272,7 @@ def test_number_selector_schema_error(schema): ("schema", "valid_selections", "invalid_selections"), (({}, ("abc123",), (None,)),), ) -def test_addon_selector_schema(schema, valid_selections, invalid_selections): +def test_addon_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test add-on selector.""" _test_selector("addon", schema, valid_selections, invalid_selections) @@ -281,7 +281,7 @@ def test_addon_selector_schema(schema, valid_selections, invalid_selections): ("schema", "valid_selections", "invalid_selections"), (({}, (1, "one", None), ()),), # Everything can be coarced to bool ) -def test_boolean_selector_schema(schema, valid_selections, invalid_selections): +def test_boolean_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test boolean selector.""" _test_selector( "boolean", @@ -307,7 +307,9 @@ def test_boolean_selector_schema(schema, valid_selections, invalid_selections): ), ), ) -def test_config_entry_selector_schema(schema, valid_selections, invalid_selections): +def test_config_entry_selector_schema( + schema, valid_selections, invalid_selections +) -> None: """Test boolean selector.""" _test_selector("config_entry", schema, valid_selections, invalid_selections) @@ -316,7 +318,7 @@ def test_config_entry_selector_schema(schema, valid_selections, invalid_selectio ("schema", "valid_selections", "invalid_selections"), (({}, ("00:00:00",), ("blah", None)),), ) -def test_time_selector_schema(schema, valid_selections, invalid_selections): +def test_time_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test time selector.""" _test_selector("time", schema, valid_selections, invalid_selections) @@ -331,7 +333,7 @@ def test_time_selector_schema(schema, valid_selections, invalid_selections): ), ), ) -def test_state_selector_schema(schema, valid_selections, invalid_selections): +def test_state_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test state selector.""" _test_selector("state", schema, valid_selections, invalid_selections) @@ -365,7 +367,7 @@ def test_state_selector_schema(schema, valid_selections, invalid_selections): ), ), ) -def test_target_selector_schema(schema, valid_selections, invalid_selections): +def test_target_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test target selector.""" _test_selector("target", schema, valid_selections, invalid_selections) @@ -374,7 +376,7 @@ def test_target_selector_schema(schema, valid_selections, invalid_selections): ("schema", "valid_selections", "invalid_selections"), (({}, ("abc123",), ()),), ) -def test_action_selector_schema(schema, valid_selections, invalid_selections): +def test_action_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test action sequence selector.""" _test_selector("action", schema, valid_selections, invalid_selections) @@ -383,7 +385,7 @@ def test_action_selector_schema(schema, valid_selections, invalid_selections): ("schema", "valid_selections", "invalid_selections"), (({}, ("abc123",), ()),), ) -def test_object_selector_schema(schema, valid_selections, invalid_selections): +def test_object_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test object selector.""" _test_selector("object", schema, valid_selections, invalid_selections) @@ -396,7 +398,7 @@ def test_object_selector_schema(schema, valid_selections, invalid_selections): ({"multiline": False, "type": "email"}, (), ()), ), ) -def test_text_selector_schema(schema, valid_selections, invalid_selections): +def test_text_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test text selector.""" _test_selector("text", schema, valid_selections, invalid_selections) @@ -469,7 +471,7 @@ def test_text_selector_schema(schema, valid_selections, invalid_selections): ), ), ) -def test_select_selector_schema(schema, valid_selections, invalid_selections): +def test_select_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test select selector.""" _test_selector("select", schema, valid_selections, invalid_selections) @@ -485,7 +487,7 @@ def test_select_selector_schema(schema, valid_selections, invalid_selections): {"options": ["red", {"value": "green", "label": "Emerald Green"}]}, ), ) -def test_select_selector_schema_error(schema): +def test_select_selector_schema_error(schema) -> None: """Test select selector.""" with pytest.raises(vol.Invalid): selector.validate_selector({"select": schema}) @@ -506,7 +508,9 @@ def test_select_selector_schema_error(schema): ), ), ) -def test_attribute_selector_schema(schema, valid_selections, invalid_selections): +def test_attribute_selector_schema( + schema, valid_selections, invalid_selections +) -> None: """Test attribute selector.""" _test_selector("attribute", schema, valid_selections, invalid_selections) @@ -529,7 +533,7 @@ def test_attribute_selector_schema(schema, valid_selections, invalid_selections) ), ), ) -def test_duration_selector_schema(schema, valid_selections, invalid_selections): +def test_duration_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test duration selector.""" _test_selector("duration", schema, valid_selections, invalid_selections) @@ -544,7 +548,7 @@ def test_duration_selector_schema(schema, valid_selections, invalid_selections): ), ), ) -def test_icon_selector_schema(schema, valid_selections, invalid_selections): +def test_icon_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test icon selector.""" _test_selector("icon", schema, valid_selections, invalid_selections) @@ -559,7 +563,7 @@ def test_icon_selector_schema(schema, valid_selections, invalid_selections): ), ), ) -def test_theme_selector_schema(schema, valid_selections, invalid_selections): +def test_theme_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test theme selector.""" _test_selector("theme", schema, valid_selections, invalid_selections) @@ -586,7 +590,7 @@ def test_theme_selector_schema(schema, valid_selections, invalid_selections): ), ), ) -def test_media_selector_schema(schema, valid_selections, invalid_selections): +def test_media_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test media selector.""" def drop_metadata(data): @@ -630,7 +634,7 @@ def test_media_selector_schema(schema, valid_selections, invalid_selections): ), ), ) -def test_location_selector_schema(schema, valid_selections, invalid_selections): +def test_location_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test location selector.""" _test_selector("location", schema, valid_selections, invalid_selections) @@ -646,7 +650,9 @@ def test_location_selector_schema(schema, valid_selections, invalid_selections): ), ), ) -def test_rgb_color_selector_schema(schema, valid_selections, invalid_selections): +def test_rgb_color_selector_schema( + schema, valid_selections, invalid_selections +) -> None: """Test color_rgb selector.""" _test_selector("color_rgb", schema, valid_selections, invalid_selections) @@ -667,7 +673,9 @@ def test_rgb_color_selector_schema(schema, valid_selections, invalid_selections) ), ), ) -def test_color_tempselector_schema(schema, valid_selections, invalid_selections): +def test_color_tempselector_schema( + schema, valid_selections, invalid_selections +) -> None: """Test color_temp selector.""" _test_selector("color_temp", schema, valid_selections, invalid_selections) @@ -683,7 +691,7 @@ def test_color_tempselector_schema(schema, valid_selections, invalid_selections) ), ), ) -def test_date_selector_schema(schema, valid_selections, invalid_selections): +def test_date_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test date selector.""" _test_selector("date", schema, valid_selections, invalid_selections) @@ -699,7 +707,7 @@ def test_date_selector_schema(schema, valid_selections, invalid_selections): ), ), ) -def test_datetime_selector_schema(schema, valid_selections, invalid_selections): +def test_datetime_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test datetime selector.""" _test_selector("datetime", schema, valid_selections, invalid_selections) @@ -709,7 +717,7 @@ def test_datetime_selector_schema(schema, valid_selections, invalid_selections): ("schema", "valid_selections", "invalid_selections"), (({}, ("abc123", "{{ now() }}"), (None, "{{ incomplete }", "{% if True %}Hi!")),), ) -def test_template_selector_schema(schema, valid_selections, invalid_selections): +def test_template_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test template selector.""" _test_selector("template", schema, valid_selections, invalid_selections) @@ -724,7 +732,7 @@ def test_template_selector_schema(schema, valid_selections, invalid_selections): ), ), ) -def test_file_selector_schema(schema, valid_selections, invalid_selections): +def test_file_selector_schema(schema, valid_selections, invalid_selections) -> None: """Test file selector.""" _test_selector("file", schema, valid_selections, invalid_selections) diff --git a/tests/helpers/test_service.py b/tests/helpers/test_service.py index 0cabacb63ec..9f47bb72197 100644 --- a/tests/helpers/test_service.py +++ b/tests/helpers/test_service.py @@ -31,6 +31,7 @@ from homeassistant.setup import async_setup_component from tests.common import ( MockEntity, + MockUser, async_mock_service, get_test_home_assistant, mock_device_registry, @@ -424,7 +425,7 @@ async def test_service_call_entry_id(hass: HomeAssistant) -> None: @pytest.mark.parametrize("target", ("all", "none")) -async def test_service_call_all_none(hass, target): +async def test_service_call_all_none(hass: HomeAssistant, target) -> None: """Test service call targeting all.""" calls = async_mock_service(hass, "test_domain", "test_service") @@ -474,7 +475,7 @@ async def test_extract_entity_ids(hass: HomeAssistant) -> None: ) -async def test_extract_entity_ids_from_area(hass, area_mock): +async def test_extract_entity_ids_from_area(hass: HomeAssistant, area_mock) -> None: """Test extract_entity_ids method with areas.""" call = ServiceCall("light", "turn_on", {"area_id": "own-area"}) @@ -505,7 +506,7 @@ async def test_extract_entity_ids_from_area(hass, area_mock): ) -async def test_extract_entity_ids_from_devices(hass, area_mock): +async def test_extract_entity_ids_from_devices(hass: HomeAssistant, area_mock) -> None: """Test extract_entity_ids method with devices.""" assert await service.async_extract_entity_ids( hass, ServiceCall("light", "turn_on", {"device_id": "device-no-area-id"}) @@ -551,7 +552,7 @@ async def test_async_get_all_descriptions(hass: HomeAssistant) -> None: assert "fields" in descriptions[logger.DOMAIN]["set_level"] -async def test_call_with_required_features(hass, mock_entities): +async def test_call_with_required_features(hass: HomeAssistant, mock_entities) -> None: """Test service calls invoked only if entity has required features.""" test_service_mock = AsyncMock(return_value=None) await service.entity_service_call( @@ -585,7 +586,9 @@ async def test_call_with_required_features(hass, mock_entities): assert test_service_mock.call_count == 0 -async def test_call_with_both_required_features(hass, mock_entities): +async def test_call_with_both_required_features( + hass: HomeAssistant, mock_entities +) -> None: """Test service calls invoked only if entity has both features.""" test_service_mock = AsyncMock(return_value=None) await service.entity_service_call( @@ -602,7 +605,9 @@ async def test_call_with_both_required_features(hass, mock_entities): ] -async def test_call_with_one_of_required_features(hass, mock_entities): +async def test_call_with_one_of_required_features( + hass: HomeAssistant, mock_entities +) -> None: """Test service calls invoked with one entity having the required features.""" test_service_mock = AsyncMock(return_value=None) await service.entity_service_call( @@ -623,7 +628,7 @@ async def test_call_with_one_of_required_features(hass, mock_entities): assert all(entity in actual for entity in expected) -async def test_call_with_sync_func(hass, mock_entities): +async def test_call_with_sync_func(hass: HomeAssistant, mock_entities) -> None: """Test invoking sync service calls.""" test_service_mock = Mock(return_value=None) await service.entity_service_call( @@ -635,7 +640,7 @@ async def test_call_with_sync_func(hass, mock_entities): assert test_service_mock.call_count == 1 -async def test_call_with_sync_attr(hass, mock_entities): +async def test_call_with_sync_attr(hass: HomeAssistant, mock_entities) -> None: """Test invoking sync service calls.""" mock_method = mock_entities["light.kitchen"].sync_method = Mock(return_value=None) await service.entity_service_call( @@ -670,7 +675,9 @@ async def test_call_context_user_not_exist(hass: HomeAssistant) -> None: assert err.value.context.user_id == "non-existing" -async def test_call_context_target_all(hass, mock_handle_entity_call, mock_entities): +async def test_call_context_target_all( + hass: HomeAssistant, mock_handle_entity_call, mock_entities +) -> None: """Check we only target allowed entities if targeting all.""" with patch( "homeassistant.auth.AuthManager.async_get_user", @@ -697,8 +704,8 @@ async def test_call_context_target_all(hass, mock_handle_entity_call, mock_entit async def test_call_context_target_specific( - hass, mock_handle_entity_call, mock_entities -): + hass: HomeAssistant, mock_handle_entity_call, mock_entities +) -> None: """Check targeting specific entities.""" with patch( "homeassistant.auth.AuthManager.async_get_user", @@ -725,8 +732,8 @@ async def test_call_context_target_specific( async def test_call_context_target_specific_no_auth( - hass, mock_handle_entity_call, mock_entities -): + hass: HomeAssistant, mock_handle_entity_call, mock_entities +) -> None: """Check targeting specific entities without auth.""" with pytest.raises(exceptions.Unauthorized) as err, patch( "homeassistant.auth.AuthManager.async_get_user", @@ -748,7 +755,9 @@ async def test_call_context_target_specific_no_auth( assert err.value.entity_id == "light.kitchen" -async def test_call_no_context_target_all(hass, mock_handle_entity_call, mock_entities): +async def test_call_no_context_target_all( + hass: HomeAssistant, mock_handle_entity_call, mock_entities +) -> None: """Check we target all if no user context given.""" await service.entity_service_call( hass, @@ -766,8 +775,8 @@ async def test_call_no_context_target_all(hass, mock_handle_entity_call, mock_en async def test_call_no_context_target_specific( - hass, mock_handle_entity_call, mock_entities -): + hass: HomeAssistant, mock_handle_entity_call, mock_entities +) -> None: """Check we can target specified entities.""" await service.entity_service_call( hass, @@ -785,8 +794,11 @@ async def test_call_no_context_target_specific( async def test_call_with_match_all( - hass, mock_handle_entity_call, mock_entities, caplog -): + hass: HomeAssistant, + mock_handle_entity_call, + mock_entities, + caplog: pytest.LogCaptureFixture, +) -> None: """Check we only target allowed entities if targeting all.""" await service.entity_service_call( hass, @@ -801,7 +813,9 @@ async def test_call_with_match_all( ) -async def test_call_with_omit_entity_id(hass, mock_handle_entity_call, mock_entities): +async def test_call_with_omit_entity_id( + hass: HomeAssistant, mock_handle_entity_call, mock_entities +) -> None: """Check service call if we do not pass an entity ID.""" await service.entity_service_call( hass, @@ -813,7 +827,9 @@ async def test_call_with_omit_entity_id(hass, mock_handle_entity_call, mock_enti assert len(mock_handle_entity_call.mock_calls) == 0 -async def test_register_admin_service(hass, hass_read_only_user, hass_admin_user): +async def test_register_admin_service( + hass: HomeAssistant, hass_read_only_user: MockUser, hass_admin_user: MockUser +) -> None: """Test the register admin service.""" calls = [] @@ -880,7 +896,7 @@ async def test_register_admin_service(hass, hass_read_only_user, hass_admin_user assert calls[0].context.user_id == hass_admin_user.id -async def test_domain_control_not_async(hass, mock_entities): +async def test_domain_control_not_async(hass: HomeAssistant, mock_entities) -> None: """Test domain verification in a service call with an unknown user.""" calls = [] @@ -892,7 +908,7 @@ async def test_domain_control_not_async(hass, mock_entities): service.verify_domain_control(hass, "test_domain")(mock_service_log) -async def test_domain_control_unknown(hass, mock_entities): +async def test_domain_control_unknown(hass: HomeAssistant, mock_entities) -> None: """Test domain verification in a service call with an unknown user.""" calls = [] @@ -923,7 +939,9 @@ async def test_domain_control_unknown(hass, mock_entities): assert len(calls) == 0 -async def test_domain_control_unauthorized(hass, hass_read_only_user): +async def test_domain_control_unauthorized( + hass: HomeAssistant, hass_read_only_user: MockUser +) -> None: """Test domain verification in a service call with an unauthorized user.""" mock_registry( hass, @@ -962,7 +980,9 @@ async def test_domain_control_unauthorized(hass, hass_read_only_user): assert len(calls) == 0 -async def test_domain_control_admin(hass, hass_admin_user): +async def test_domain_control_admin( + hass: HomeAssistant, hass_admin_user: MockUser +) -> None: """Test domain verification in a service call with an admin user.""" mock_registry( hass, @@ -1114,7 +1134,7 @@ async def test_extract_from_service_filter_out_non_existing_entities( ] -async def test_extract_from_service_area_id(hass, area_mock): +async def test_extract_from_service_area_id(hass: HomeAssistant, area_mock) -> None: """Test the extraction using area ID as reference.""" entities = [ MockEntity(name="in_area", entity_id="light.in_area"), @@ -1149,7 +1169,9 @@ async def test_extract_from_service_area_id(hass, area_mock): ] -async def test_entity_service_call_warn_referenced(hass, caplog): +async def test_entity_service_call_warn_referenced( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test we only warn for referenced entities in entity_service_call.""" call = ServiceCall( "light", @@ -1167,7 +1189,9 @@ async def test_entity_service_call_warn_referenced(hass, caplog): ) -async def test_async_extract_entities_warn_referenced(hass, caplog): +async def test_async_extract_entities_warn_referenced( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test we only warn for referenced entities in async_extract_entities.""" call = ServiceCall( "light", diff --git a/tests/helpers/test_significant_change.py b/tests/helpers/test_significant_change.py index b707e369931..c0d9f1b3a4a 100644 --- a/tests/helpers/test_significant_change.py +++ b/tests/helpers/test_significant_change.py @@ -3,7 +3,7 @@ import pytest from homeassistant.components.sensor import SensorDeviceClass from homeassistant.const import ATTR_DEVICE_CLASS, STATE_UNAVAILABLE, STATE_UNKNOWN -from homeassistant.core import State +from homeassistant.core import HomeAssistant, State from homeassistant.helpers import significant_change @@ -23,7 +23,7 @@ async def checker_fixture(hass): return checker -async def test_signicant_change(hass, checker): +async def test_signicant_change(hass: HomeAssistant, checker) -> None: """Test initialize helper works.""" ent_id = "test_domain.test_entity" attrs = {ATTR_DEVICE_CLASS: SensorDeviceClass.BATTERY} @@ -47,7 +47,7 @@ async def test_signicant_change(hass, checker): assert checker.async_is_significant_change(State(ent_id, STATE_UNAVAILABLE, attrs)) -async def test_significant_change_extra(hass, checker): +async def test_significant_change_extra(hass: HomeAssistant, checker) -> None: """Test extra significant checker works.""" ent_id = "test_domain.test_entity" attrs = {ATTR_DEVICE_CLASS: SensorDeviceClass.BATTERY} diff --git a/tests/helpers/test_singleton.py b/tests/helpers/test_singleton.py index 1d4f496a794..81579202799 100644 --- a/tests/helpers/test_singleton.py +++ b/tests/helpers/test_singleton.py @@ -13,7 +13,7 @@ def mock_hass(): @pytest.mark.parametrize("result", (object(), {}, [])) -async def test_singleton_async(mock_hass, result): +async def test_singleton_async(mock_hass, result) -> None: """Test singleton with async function.""" @singleton.singleton("test_key") @@ -29,7 +29,7 @@ async def test_singleton_async(mock_hass, result): @pytest.mark.parametrize("result", (object(), {}, [])) -def test_singleton(mock_hass, result): +def test_singleton(mock_hass, result) -> None: """Test singleton with function.""" @singleton.singleton("test_key") diff --git a/tests/helpers/test_start.py b/tests/helpers/test_start.py index 574c28a6588..ec7ffbc9afc 100644 --- a/tests/helpers/test_start.py +++ b/tests/helpers/test_start.py @@ -1,4 +1,6 @@ """Test starting HA helpers.""" +import pytest + from homeassistant.const import EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STARTED from homeassistant.core import CoreState, HomeAssistant, callback from homeassistant.helpers import start @@ -27,7 +29,9 @@ async def test_at_start_when_running_awaitable(hass: HomeAssistant) -> None: assert len(calls) == 2 -async def test_at_start_when_running_callback(hass, caplog): +async def test_at_start_when_running_callback( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test at start when already running.""" assert hass.state == CoreState.running assert hass.is_running @@ -73,7 +77,9 @@ async def test_at_start_when_starting_awaitable(hass: HomeAssistant) -> None: assert len(calls) == 1 -async def test_at_start_when_starting_callback(hass, caplog): +async def test_at_start_when_starting_callback( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test at start when yet to start.""" hass.state = CoreState.not_running assert not hass.is_running @@ -100,7 +106,9 @@ async def test_at_start_when_starting_callback(hass, caplog): assert record.levelname in ("DEBUG", "INFO") -async def test_cancelling_at_start_when_running(hass, caplog): +async def test_cancelling_at_start_when_running( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test cancelling at start when already running.""" assert hass.state == CoreState.running assert hass.is_running @@ -163,7 +171,9 @@ async def test_at_started_when_running_awaitable(hass: HomeAssistant) -> None: assert len(calls) == 1 -async def test_at_started_when_running_callback(hass, caplog): +async def test_at_started_when_running_callback( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test at started when already running.""" assert hass.state == CoreState.running @@ -211,7 +221,9 @@ async def test_at_started_when_starting_awaitable(hass: HomeAssistant) -> None: assert len(calls) == 1 -async def test_at_started_when_starting_callback(hass, caplog): +async def test_at_started_when_starting_callback( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test at started when yet to start.""" hass.state = CoreState.not_running @@ -241,7 +253,9 @@ async def test_at_started_when_starting_callback(hass, caplog): assert record.levelname in ("DEBUG", "INFO") -async def test_cancelling_at_started_when_running(hass, caplog): +async def test_cancelling_at_started_when_running( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test cancelling at start when already running.""" assert hass.state == CoreState.running assert hass.is_running diff --git a/tests/helpers/test_storage.py b/tests/helpers/test_storage.py index 4613a9162c2..77e5fa4aef8 100644 --- a/tests/helpers/test_storage.py +++ b/tests/helpers/test_storage.py @@ -2,7 +2,7 @@ import asyncio from datetime import timedelta import json -from typing import NamedTuple +from typing import Any, NamedTuple from unittest.mock import Mock, patch import pytest @@ -57,7 +57,7 @@ def store_v_2_1(hass): ) -async def test_loading(hass, store): +async def test_loading(hass: HomeAssistant, store) -> None: """Test we can save and load data.""" await store.async_save(MOCK_DATA) data = await store.async_load() @@ -82,14 +82,19 @@ async def test_custom_encoder(hass: HomeAssistant) -> None: assert data == "9" -async def test_loading_non_existing(hass, store): +async def test_loading_non_existing(hass: HomeAssistant, store) -> None: """Test we can save and load data.""" with patch("homeassistant.util.json.open", side_effect=FileNotFoundError): data = await store.async_load() assert data is None -async def test_loading_parallel(hass, store, hass_storage, caplog): +async def test_loading_parallel( + hass: HomeAssistant, + store, + hass_storage: dict[str, Any], + caplog: pytest.LogCaptureFixture, +) -> None: """Test we can save and load data.""" hass_storage[store.key] = {"version": MOCK_VERSION, "data": MOCK_DATA} @@ -100,7 +105,9 @@ async def test_loading_parallel(hass, store, hass_storage, caplog): assert caplog.text.count(f"Loading data for {store.key}") -async def test_saving_with_delay(hass, store, hass_storage): +async def test_saving_with_delay( + hass: HomeAssistant, store, hass_storage: dict[str, Any] +) -> None: """Test saving data after a delay.""" store.async_delay_save(lambda: MOCK_DATA, 1) assert store.key not in hass_storage @@ -115,7 +122,9 @@ async def test_saving_with_delay(hass, store, hass_storage): } -async def test_saving_on_final_write(hass, hass_storage): +async def test_saving_on_final_write( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test delayed saves trigger when we quit Home Assistant.""" store = storage.Store(hass, MOCK_VERSION, MOCK_KEY) store.async_delay_save(lambda: MOCK_DATA, 5) @@ -139,7 +148,9 @@ async def test_saving_on_final_write(hass, hass_storage): } -async def test_not_delayed_saving_while_stopping(hass, hass_storage): +async def test_not_delayed_saving_while_stopping( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test delayed saves don't write after the stop event has fired.""" store = storage.Store(hass, MOCK_VERSION, MOCK_KEY) hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) @@ -152,7 +163,9 @@ async def test_not_delayed_saving_while_stopping(hass, hass_storage): assert store.key not in hass_storage -async def test_not_delayed_saving_after_stopping(hass, hass_storage): +async def test_not_delayed_saving_after_stopping( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test delayed saves don't write after stop if issued before stopping Home Assistant.""" store = storage.Store(hass, MOCK_VERSION, MOCK_KEY) store.async_delay_save(lambda: MOCK_DATA, 10) @@ -168,7 +181,9 @@ async def test_not_delayed_saving_after_stopping(hass, hass_storage): assert store.key not in hass_storage -async def test_not_saving_while_stopping(hass, hass_storage): +async def test_not_saving_while_stopping( + hass: HomeAssistant, hass_storage: dict[str, Any] +) -> None: """Test saves don't write when stopping Home Assistant.""" store = storage.Store(hass, MOCK_VERSION, MOCK_KEY) hass.state = CoreState.stopping @@ -176,7 +191,9 @@ async def test_not_saving_while_stopping(hass, hass_storage): assert store.key not in hass_storage -async def test_loading_while_delay(hass, store, hass_storage): +async def test_loading_while_delay( + hass: HomeAssistant, store, hass_storage: dict[str, Any] +) -> None: """Test we load new data even if not written yet.""" await store.async_save({"delay": "no"}) assert hass_storage[store.key] == { @@ -198,7 +215,9 @@ async def test_loading_while_delay(hass, store, hass_storage): assert data == {"delay": "yes"} -async def test_writing_while_writing_delay(hass, store, hass_storage): +async def test_writing_while_writing_delay( + hass: HomeAssistant, store, hass_storage: dict[str, Any] +) -> None: """Test a write while a write with delay is active.""" store.async_delay_save(lambda: {"delay": "yes"}, 1) assert store.key not in hass_storage @@ -223,7 +242,9 @@ async def test_writing_while_writing_delay(hass, store, hass_storage): assert data == {"delay": "no"} -async def test_multiple_delay_save_calls(hass, store, hass_storage): +async def test_multiple_delay_save_calls( + hass: HomeAssistant, store, hass_storage: dict[str, Any] +) -> None: """Test a write while a write with changing delays.""" store.async_delay_save(lambda: {"delay": "yes"}, 1) store.async_delay_save(lambda: {"delay": "yes"}, 2) @@ -251,7 +272,9 @@ async def test_multiple_delay_save_calls(hass, store, hass_storage): assert data == {"delay": "no"} -async def test_multiple_save_calls(hass, store, hass_storage): +async def test_multiple_save_calls( + hass: HomeAssistant, store, hass_storage: dict[str, Any] +) -> None: """Test multiple write tasks.""" assert store.key not in hass_storage @@ -269,7 +292,9 @@ async def test_multiple_save_calls(hass, store, hass_storage): assert data == {"savecount": 5} -async def test_migrator_no_existing_config(hass, store, hass_storage): +async def test_migrator_no_existing_config( + hass: HomeAssistant, store, hass_storage: dict[str, Any] +) -> None: """Test migrator with no existing config.""" with patch("os.path.isfile", return_value=False), patch.object( store, "async_load", return_value={"cur": "config"} @@ -280,7 +305,9 @@ async def test_migrator_no_existing_config(hass, store, hass_storage): assert store.key not in hass_storage -async def test_migrator_existing_config(hass, store, hass_storage): +async def test_migrator_existing_config( + hass: HomeAssistant, store, hass_storage: dict[str, Any] +) -> None: """Test migrating existing config.""" with patch("os.path.isfile", return_value=True), patch("os.remove") as mock_remove: data = await storage.async_migrator( @@ -297,7 +324,9 @@ async def test_migrator_existing_config(hass, store, hass_storage): } -async def test_migrator_transforming_config(hass, store, hass_storage): +async def test_migrator_transforming_config( + hass: HomeAssistant, store, hass_storage: dict[str, Any] +) -> None: """Test migrating config to new format.""" async def old_conf_migrate_func(old_config): @@ -323,21 +352,27 @@ async def test_migrator_transforming_config(hass, store, hass_storage): } -async def test_minor_version_default(hass, store, hass_storage): +async def test_minor_version_default( + hass: HomeAssistant, store, hass_storage: dict[str, Any] +) -> None: """Test minor version default.""" await store.async_save(MOCK_DATA) assert hass_storage[store.key]["minor_version"] == 1 -async def test_minor_version(hass, store_v_1_2, hass_storage): +async def test_minor_version( + hass: HomeAssistant, store_v_1_2, hass_storage: dict[str, Any] +) -> None: """Test minor version.""" await store_v_1_2.async_save(MOCK_DATA) assert hass_storage[store_v_1_2.key]["minor_version"] == MOCK_MINOR_VERSION_2 -async def test_migrate_major_not_implemented_raises(hass, store, store_v_2_1): +async def test_migrate_major_not_implemented_raises( + hass: HomeAssistant, store, store_v_2_1 +) -> None: """Test migrating between major versions fails if not implemented.""" await store_v_2_1.async_save(MOCK_DATA) @@ -346,8 +381,8 @@ async def test_migrate_major_not_implemented_raises(hass, store, store_v_2_1): async def test_migrate_minor_not_implemented( - hass, hass_storage, store_v_1_1, store_v_1_2 -): + hass: HomeAssistant, hass_storage: dict[str, Any], store_v_1_1, store_v_1_2 +) -> None: """Test migrating between minor versions does not fail if not implemented.""" assert store_v_1_1.key == store_v_1_2.key @@ -371,7 +406,9 @@ async def test_migrate_minor_not_implemented( } -async def test_migration(hass, hass_storage, store_v_1_2): +async def test_migration( + hass: HomeAssistant, hass_storage: dict[str, Any], store_v_1_2 +) -> None: """Test migration.""" calls = 0 @@ -408,7 +445,9 @@ async def test_migration(hass, hass_storage, store_v_1_2): } -async def test_legacy_migration(hass, hass_storage, store_v_1_2): +async def test_legacy_migration( + hass: HomeAssistant, hass_storage: dict[str, Any], store_v_1_2 +) -> None: """Test legacy migration method signature.""" calls = 0 @@ -442,7 +481,9 @@ async def test_legacy_migration(hass, hass_storage, store_v_1_2): } -async def test_changing_delayed_written_data(hass, store, hass_storage): +async def test_changing_delayed_written_data( + hass: HomeAssistant, store, hass_storage: dict[str, Any] +) -> None: """Test changing data that is written with delay.""" data_to_store = {"hello": "world"} store.async_delay_save(lambda: data_to_store, 1) @@ -464,7 +505,7 @@ async def test_changing_delayed_written_data(hass, store, hass_storage): } -async def test_saving_load_round_trip(tmpdir): +async def test_saving_load_round_trip(tmpdir) -> None: """Test saving and loading round trip.""" loop = asyncio.get_running_loop() hass = await async_test_home_assistant(loop) diff --git a/tests/helpers/test_storage_remove.py b/tests/helpers/test_storage_remove.py index aa118aded59..b90d0df0d03 100644 --- a/tests/helpers/test_storage_remove.py +++ b/tests/helpers/test_storage_remove.py @@ -10,7 +10,7 @@ from homeassistant.util import dt from tests.common import async_fire_time_changed, async_test_home_assistant -async def test_removing_while_delay_in_progress(tmpdir): +async def test_removing_while_delay_in_progress(tmpdir) -> None: """Test removing while delay in progress.""" loop = asyncio.get_event_loop() diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 740cbdd1fca..ec6714bafe1 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -371,7 +371,7 @@ def test_bool_filter(hass: HomeAssistant) -> None: ("inf", False), ], ) -def test_isnumber(hass, value, expected): +def test_isnumber(hass: HomeAssistant, value, expected) -> None: """Test is_number.""" assert ( template.Template("{{ is_number(value) }}", hass).async_render({"value": value}) @@ -895,7 +895,7 @@ def test_timestamp_local(hass: HomeAssistant) -> None: "invalid", ), ) -def test_as_datetime(hass, input): +def test_as_datetime(hass: HomeAssistant, input) -> None: """Test converting a timestamp string to a date object.""" expected = dt_util.parse_datetime(input) if expected is not None: @@ -1061,7 +1061,7 @@ def test_max(hass: HomeAssistant) -> None: "c", ), ) -def test_min_max_attribute(hass, attribute): +def test_min_max_attribute(hass: HomeAssistant, attribute) -> None: """Test the min and max filters with attribute.""" hass.states.async_set( "test.object", @@ -1234,7 +1234,7 @@ def test_as_timestamp(hass: HomeAssistant) -> None: @patch.object(random, "choice") -def test_random_every_time(test_choice, hass): +def test_random_every_time(test_choice, hass: HomeAssistant) -> None: """Ensure the random filter runs every time, not just once.""" tpl = template.Template("{{ [1,2] | random }}", hass) test_choice.return_value = "foo" @@ -1510,7 +1510,7 @@ def test_states_function(hass: HomeAssistant) -> None: "homeassistant.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) -def test_now(mock_is_safe, hass): +def test_now(mock_is_safe, hass: HomeAssistant) -> None: """Test now method.""" now = dt_util.now() with patch("homeassistant.util.dt.now", return_value=now): @@ -1524,7 +1524,7 @@ def test_now(mock_is_safe, hass): "homeassistant.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) -def test_utcnow(mock_is_safe, hass): +def test_utcnow(mock_is_safe, hass: HomeAssistant) -> None: """Test now method.""" utcnow = dt_util.utcnow() with patch("homeassistant.util.dt.utcnow", return_value=utcnow): @@ -1559,7 +1559,9 @@ def test_utcnow(mock_is_safe, hass): "homeassistant.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) -def test_today_at(mock_is_safe, hass, now, expected, expected_midnight, timezone_str): +def test_today_at( + mock_is_safe, hass: HomeAssistant, now, expected, expected_midnight, timezone_str +) -> None: """Test today_at method.""" freezer = freeze_time(now) freezer.start() @@ -1600,7 +1602,7 @@ def test_today_at(mock_is_safe, hass, now, expected, expected_midnight, timezone "homeassistant.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) -def test_relative_time(mock_is_safe, hass): +def test_relative_time(mock_is_safe, hass: HomeAssistant) -> None: """Test relative_time method.""" hass.config.set_time_zone("UTC") now = datetime.strptime("2000-01-01 10:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z") @@ -1670,7 +1672,7 @@ def test_relative_time(mock_is_safe, hass): "homeassistant.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) -def test_timedelta(mock_is_safe, hass): +def test_timedelta(mock_is_safe, hass: HomeAssistant) -> None: """Test relative_time method.""" now = datetime.strptime("2000-01-01 10:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z") with patch("homeassistant.util.dt.now", return_value=now): @@ -1954,7 +1956,7 @@ def test_bitwise_or(hass: HomeAssistant) -> None: assert tpl.async_render() == 8 | 2 -def test_pack(hass, caplog): +def test_pack(hass: HomeAssistant, caplog: pytest.LogCaptureFixture) -> None: """Test struct pack method.""" # render as filter @@ -2019,7 +2021,7 @@ def test_pack(hass, caplog): ) -def test_unpack(hass, caplog): +def test_unpack(hass: HomeAssistant, caplog: pytest.LogCaptureFixture) -> None: """Test struct unpack method.""" # render as filter @@ -4243,7 +4245,9 @@ async def test_parse_result(hass: HomeAssistant) -> None: assert template.Template(tpl, hass).async_render() == result -async def test_undefined_variable(hass, caplog): +async def test_undefined_variable( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test a warning is logged on undefined variables.""" tpl = template.Template("{{ no_such_variable }}", hass) assert tpl.async_render() == "" @@ -4285,7 +4289,7 @@ async def test_template_states_can_serialize(hass: HomeAssistant) -> None: ([], None, False), ], ) -def test_contains(hass, seq, value, expected): +def test_contains(hass: HomeAssistant, seq, value, expected) -> None: """Test contains.""" assert ( template.Template("{{ seq | contains(value) }}", hass).async_render( diff --git a/tests/helpers/test_translation.py b/tests/helpers/test_translation.py index 0cafe48f008..25f1a742664 100644 --- a/tests/helpers/test_translation.py +++ b/tests/helpers/test_translation.py @@ -34,7 +34,9 @@ def test_recursive_flatten() -> None: } -async def test_component_translation_path(hass, enable_custom_integrations): +async def test_component_translation_path( + hass: HomeAssistant, enable_custom_integrations: None +) -> None: """Test the component translation file function.""" assert await async_setup_component( hass, @@ -96,7 +98,9 @@ def test_load_translations_files(hass: HomeAssistant) -> None: } -async def test_get_translations(hass, mock_config_flows, enable_custom_integrations): +async def test_get_translations( + hass: HomeAssistant, mock_config_flows, enable_custom_integrations: None +) -> None: """Test the get translations helper.""" translations = await translation.async_get_translations(hass, "en", "state") assert translations == {} @@ -127,7 +131,9 @@ async def test_get_translations(hass, mock_config_flows, enable_custom_integrati assert translations["component.switch.state.string2"] == "Value 2" -async def test_get_translations_loads_config_flows(hass, mock_config_flows): +async def test_get_translations_loads_config_flows( + hass: HomeAssistant, mock_config_flows +) -> None: """Test the get translations helper loads config flow translations.""" mock_config_flows["integration"].append("component1") integration = Mock(file_path=pathlib.Path(__file__)) @@ -245,7 +251,9 @@ async def test_get_translation_categories(hass: HomeAssistant) -> None: assert "component.light.device_automation.action_type.turn_on" in translations -async def test_translation_merging(hass, caplog): +async def test_translation_merging( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test we merge translations of two integrations.""" hass.config.components.add("sensor.moon") hass.config.components.add("sensor") @@ -291,7 +299,9 @@ async def test_translation_merging(hass, caplog): ) in caplog.text -async def test_translation_merging_loaded_apart(hass, caplog): +async def test_translation_merging_loaded_apart( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test we merge translations of two integrations when they are not loaded at the same time.""" orig_load_translations = translation.load_translations_files @@ -334,7 +344,9 @@ async def test_translation_merging_loaded_apart(hass, caplog): assert "component.sensor.state.moon__phase.first_quarter" in translations -async def test_translation_merging_loaded_together(hass, caplog): +async def test_translation_merging_loaded_together( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test we merge translations of two integrations when they are loaded at the same time.""" hass.config.components.add("hue") hass.config.components.add("homekit") @@ -417,7 +429,9 @@ async def test_caching(hass: HomeAssistant) -> None: assert len(mock_build.mock_calls) > 1 -async def test_custom_component_translations(hass, enable_custom_integrations): +async def test_custom_component_translations( + hass: HomeAssistant, enable_custom_integrations: None +) -> None: """Test getting translation from custom components.""" hass.config.components.add("test_embedded") hass.config.components.add("test_package") diff --git a/tests/helpers/test_trigger.py b/tests/helpers/test_trigger.py index 1481df3b97b..0a102c4ce42 100644 --- a/tests/helpers/test_trigger.py +++ b/tests/helpers/test_trigger.py @@ -43,7 +43,7 @@ async def test_trigger_variables(hass: HomeAssistant) -> None: """Test trigger variables.""" -async def test_if_fires_on_event(hass, calls): +async def test_if_fires_on_event(hass: HomeAssistant, calls) -> None: """Test the firing of events.""" assert await async_setup_component( hass, diff --git a/tests/helpers/test_update_coordinator.py b/tests/helpers/test_update_coordinator.py index 5af4f02cc87..6bba27af654 100644 --- a/tests/helpers/test_update_coordinator.py +++ b/tests/helpers/test_update_coordinator.py @@ -85,7 +85,7 @@ def crd_without_update_interval(hass): return get_crd(hass, None) -async def test_async_refresh(crd): +async def test_async_refresh(crd) -> None: """Test async_refresh for update coordinator.""" assert crd.data is None await crd.async_refresh() @@ -134,7 +134,7 @@ async def test_update_context(crd: update_coordinator.DataUpdateCoordinator[int] assert not set(crd.async_contexts()) -async def test_request_refresh(crd): +async def test_request_refresh(crd) -> None: """Test request refresh for update coordinator.""" assert crd.data is None await crd.async_request_refresh() @@ -147,7 +147,7 @@ async def test_request_refresh(crd): assert crd.last_update_success is True -async def test_request_refresh_no_auto_update(crd_without_update_interval): +async def test_request_refresh_no_auto_update(crd_without_update_interval) -> None: """Test request refresh for update coordinator without automatic update.""" crd = crd_without_update_interval assert crd.data is None @@ -165,7 +165,9 @@ async def test_request_refresh_no_auto_update(crd_without_update_interval): "err_msg", KNOWN_ERRORS, ) -async def test_refresh_known_errors(err_msg, crd, caplog): +async def test_refresh_known_errors( + err_msg, crd, caplog: pytest.LogCaptureFixture +) -> None: """Test raising known errors.""" crd.update_method = AsyncMock(side_effect=err_msg[0]) @@ -177,7 +179,7 @@ async def test_refresh_known_errors(err_msg, crd, caplog): assert err_msg[2] in caplog.text -async def test_refresh_fail_unknown(crd, caplog): +async def test_refresh_fail_unknown(crd, caplog: pytest.LogCaptureFixture) -> None: """Test raising unknown error.""" await crd.async_refresh() @@ -190,7 +192,7 @@ async def test_refresh_fail_unknown(crd, caplog): assert "Unexpected error fetching test data" in caplog.text -async def test_refresh_no_update_method(crd): +async def test_refresh_no_update_method(crd) -> None: """Test raising error is no update method is provided.""" await crd.async_refresh() @@ -200,7 +202,7 @@ async def test_refresh_no_update_method(crd): await crd.async_refresh() -async def test_update_interval(hass, crd): +async def test_update_interval(hass: HomeAssistant, crd) -> None: """Test update interval works.""" # Test we don't update without subscriber async_fire_time_changed(hass, utcnow() + crd.update_interval) @@ -230,7 +232,9 @@ async def test_update_interval(hass, crd): assert crd.data == 2 -async def test_update_interval_not_present(hass, crd_without_update_interval): +async def test_update_interval_not_present( + hass: HomeAssistant, crd_without_update_interval +) -> None: """Test update never happens with no update interval.""" crd = crd_without_update_interval # Test we don't update without subscriber with no update interval @@ -261,7 +265,7 @@ async def test_update_interval_not_present(hass, crd_without_update_interval): assert crd.data is None -async def test_refresh_recover(crd, caplog): +async def test_refresh_recover(crd, caplog: pytest.LogCaptureFixture) -> None: """Test recovery of freshing data.""" crd.last_update_success = False @@ -300,7 +304,7 @@ async def test_coordinator_entity(crd: update_coordinator.DataUpdateCoordinator[ assert list(crd.async_contexts()) == [context] -async def test_async_set_updated_data(crd): +async def test_async_set_updated_data(crd) -> None: """Test async_set_updated_data for update coordinator.""" assert crd.data is None @@ -334,7 +338,7 @@ async def test_async_set_updated_data(crd): assert crd._unsub_refresh is not old_refresh -async def test_stop_refresh_on_ha_stop(hass, crd): +async def test_stop_refresh_on_ha_stop(hass: HomeAssistant, crd) -> None: """Test no update interval refresh when Home Assistant is stopping.""" # Add subscriber update_callback = Mock() @@ -371,7 +375,9 @@ async def test_stop_refresh_on_ha_stop(hass, crd): "err_msg", KNOWN_ERRORS, ) -async def test_async_config_entry_first_refresh_failure(err_msg, crd, caplog): +async def test_async_config_entry_first_refresh_failure( + err_msg, crd, caplog: pytest.LogCaptureFixture +) -> None: """Test async_config_entry_first_refresh raises ConfigEntryNotReady on failure. Verify we do not log the exception since raising ConfigEntryNotReady @@ -388,7 +394,9 @@ async def test_async_config_entry_first_refresh_failure(err_msg, crd, caplog): assert err_msg[2] not in caplog.text -async def test_async_config_entry_first_refresh_success(crd, caplog): +async def test_async_config_entry_first_refresh_success( + crd, caplog: pytest.LogCaptureFixture +) -> None: """Test first refresh successfully.""" await crd.async_config_entry_first_refresh() @@ -406,7 +414,7 @@ async def test_not_schedule_refresh_if_system_option_disable_polling( assert crd._unsub_refresh is None -async def test_async_set_update_error(crd, caplog): +async def test_async_set_update_error(crd, caplog: pytest.LogCaptureFixture) -> None: """Test manually setting an update failure.""" update_callback = Mock() crd.async_add_listener(update_callback) diff --git a/tests/scripts/test_auth.py b/tests/scripts/test_auth.py index a5478d149ec..82a8a408c53 100644 --- a/tests/scripts/test_auth.py +++ b/tests/scripts/test_auth.py @@ -1,9 +1,11 @@ """Test the auth script to manage local users.""" +from typing import Any from unittest.mock import Mock, patch import pytest from homeassistant.auth.providers import homeassistant as hass_auth +from homeassistant.core import HomeAssistant from homeassistant.scripts import auth as script_auth from tests.common import register_auth_provider @@ -19,7 +21,7 @@ def provider(hass): return provider -async def test_list_user(hass, provider, capsys): +async def test_list_user(hass: HomeAssistant, provider, capsys) -> None: """Test we can list users.""" data = provider.data data.add_auth("test-user", "test-pass") @@ -34,7 +36,9 @@ async def test_list_user(hass, provider, capsys): ) -async def test_add_user(hass, provider, capsys, hass_storage): +async def test_add_user( + hass: HomeAssistant, provider, capsys, hass_storage: dict[str, Any] +) -> None: """Test we can add a user.""" data = provider.data await script_auth.add_user( @@ -50,7 +54,7 @@ async def test_add_user(hass, provider, capsys, hass_storage): data.validate_login("paulus", "test-pass") -async def test_validate_login(hass, provider, capsys): +async def test_validate_login(hass: HomeAssistant, provider, capsys) -> None: """Test we can validate a user login.""" data = provider.data data.add_auth("test-user", "test-pass") @@ -74,7 +78,9 @@ async def test_validate_login(hass, provider, capsys): assert captured.out == "Auth invalid\n" -async def test_change_password(hass, provider, capsys, hass_storage): +async def test_change_password( + hass: HomeAssistant, provider, capsys, hass_storage: dict[str, Any] +) -> None: """Test we can change a password.""" data = provider.data data.add_auth("test-user", "test-pass") @@ -91,7 +97,9 @@ async def test_change_password(hass, provider, capsys, hass_storage): data.validate_login("test-user", "test-pass") -async def test_change_password_invalid_user(hass, provider, capsys, hass_storage): +async def test_change_password_invalid_user( + hass: HomeAssistant, provider, capsys, hass_storage: dict[str, Any] +) -> None: """Test changing password of non-existing user.""" data = provider.data data.add_auth("test-user", "test-pass") @@ -108,7 +116,7 @@ async def test_change_password_invalid_user(hass, provider, capsys, hass_storage data.validate_login("invalid-user", "new-pass") -def test_parsing_args(event_loop): +def test_parsing_args(event_loop) -> None: """Test we parse args correctly.""" called = False diff --git a/tests/scripts/test_check_config.py b/tests/scripts/test_check_config.py index 8720ae1a1f1..1e6f1c184be 100644 --- a/tests/scripts/test_check_config.py +++ b/tests/scripts/test_check_config.py @@ -43,7 +43,7 @@ def normalize_yaml_files(check_dict): return [key.replace(root, "...") for key in sorted(check_dict["yaml_files"].keys())] -def test_bad_core_config(mock_is_file, event_loop): +def test_bad_core_config(mock_is_file, event_loop) -> None: """Test a bad core config setup.""" files = {YAML_CONFIG_FILE: BAD_CORE_CONFIG} with patch_yaml_files(files): @@ -52,7 +52,7 @@ def test_bad_core_config(mock_is_file, event_loop): assert res["except"]["homeassistant"][1] == {"unit_system": "bad"} -def test_config_platform_valid(mock_is_file, event_loop): +def test_config_platform_valid(mock_is_file, event_loop) -> None: """Test a valid platform setup.""" files = {YAML_CONFIG_FILE: BASE_CONFIG + "light:\n platform: demo"} with patch_yaml_files(files): @@ -65,7 +65,7 @@ def test_config_platform_valid(mock_is_file, event_loop): assert len(res["yaml_files"]) == 1 -def test_component_platform_not_found(mock_is_file, event_loop): +def test_component_platform_not_found(mock_is_file, event_loop) -> None: """Test errors if component or platform not found.""" # Make sure they don't exist files = {YAML_CONFIG_FILE: BASE_CONFIG + "beer:"} @@ -96,7 +96,7 @@ def test_component_platform_not_found(mock_is_file, event_loop): assert len(res["yaml_files"]) == 1 -def test_secrets(mock_is_file, event_loop): +def test_secrets(mock_is_file, event_loop) -> None: """Test secrets config checking method.""" secrets_path = get_test_config_dir("secrets.yaml") @@ -126,7 +126,7 @@ def test_secrets(mock_is_file, event_loop): ] -def test_package_invalid(mock_is_file, event_loop): +def test_package_invalid(mock_is_file, event_loop) -> None: """Test an invalid package.""" files = {YAML_CONFIG_FILE: BASE_CONFIG + ' packages:\n p1:\n group: ["a"]'} with patch_yaml_files(files): @@ -142,7 +142,7 @@ def test_package_invalid(mock_is_file, event_loop): assert len(res["yaml_files"]) == 1 -def test_bootstrap_error(event_loop): +def test_bootstrap_error(event_loop) -> None: """Test a valid platform setup.""" files = {YAML_CONFIG_FILE: BASE_CONFIG + "automation: !include no.yaml"} with patch_yaml_files(files): diff --git a/tests/scripts/test_init.py b/tests/scripts/test_init.py index 8feef2d3384..44090019a29 100644 --- a/tests/scripts/test_init.py +++ b/tests/scripts/test_init.py @@ -5,7 +5,7 @@ import homeassistant.scripts as scripts @patch("homeassistant.scripts.get_default_config_dir", return_value="/default") -def test_config_per_platform(mock_def): +def test_config_per_platform(mock_def) -> None: """Test config per platform method.""" assert scripts.get_default_config_dir() == "/default" assert scripts.extract_config_dir() == "/default" diff --git a/tests/util/test_async.py b/tests/util/test_async.py index 37abd87c2a1..48d9ee02f8d 100644 --- a/tests/util/test_async.py +++ b/tests/util/test_async.py @@ -15,7 +15,7 @@ from homeassistant.util import async_ as hasync @patch("threading.get_ident") def test_fire_coroutine_threadsafe_from_inside_event_loop( mock_ident, _, mock_iscoroutine -): +) -> None: """Testing calling fire_coroutine_threadsafe from inside an event loop.""" coro = MagicMock() loop = MagicMock() @@ -49,7 +49,7 @@ def test_fire_coroutine_threadsafe_from_inside_event_loop( @patch("concurrent.futures.Future") @patch("threading.get_ident") -def test_run_callback_threadsafe_from_inside_event_loop(mock_ident, _): +def test_run_callback_threadsafe_from_inside_event_loop(mock_ident, _) -> None: """Testing calling run_callback_threadsafe from inside an event loop.""" callback = MagicMock() @@ -82,7 +82,7 @@ async def test_check_loop_async() -> None: hasync.check_loop(banned_function) -async def test_check_loop_async_integration(caplog): +async def test_check_loop_async_integration(caplog: pytest.LogCaptureFixture) -> None: """Test check_loop detects and raises when called from event loop from integration context.""" with pytest.raises(RuntimeError), patch( "homeassistant.util.async_.extract_stack", @@ -113,7 +113,9 @@ async def test_check_loop_async_integration(caplog): ) -async def test_check_loop_async_integration_non_strict(caplog): +async def test_check_loop_async_integration_non_strict( + caplog: pytest.LogCaptureFixture, +) -> None: """Test check_loop detects when called from event loop from integration context.""" with patch( "homeassistant.util.async_.extract_stack", @@ -144,7 +146,7 @@ async def test_check_loop_async_integration_non_strict(caplog): ) -async def test_check_loop_async_custom(caplog): +async def test_check_loop_async_custom(caplog: pytest.LogCaptureFixture) -> None: """Test check_loop detects when called from event loop with custom component context.""" with pytest.raises(RuntimeError), patch( "homeassistant.util.async_.extract_stack", @@ -175,7 +177,7 @@ async def test_check_loop_async_custom(caplog): ) in caplog.text -def test_check_loop_sync(caplog): +def test_check_loop_sync(caplog: pytest.LogCaptureFixture) -> None: """Test check_loop does nothing when called from thread.""" hasync.check_loop(banned_function) assert "Detected blocking call inside the event loop" not in caplog.text @@ -190,7 +192,7 @@ def test_protect_loop_sync() -> None: func.assert_called_once_with(1, test=2) -async def test_protect_loop_debugger_sleep(caplog): +async def test_protect_loop_debugger_sleep(caplog: pytest.LogCaptureFixture) -> None: """Test time.sleep injected by the debugger is not reported.""" block_async_io.enable() diff --git a/tests/util/test_distance.py b/tests/util/test_distance.py index 2de39208ac0..d0b4bbc1ebe 100644 --- a/tests/util/test_distance.py +++ b/tests/util/test_distance.py @@ -64,7 +64,7 @@ def test_convert_nonnumeric_value() -> None: (LENGTH_INCHES, 316800.171072), ], ) -def test_convert_from_miles(unit, expected): +def test_convert_from_miles(unit, expected) -> None: """Test conversion from miles to other units.""" miles = 5 assert distance_util.convert(miles, LENGTH_MILES, unit) == pytest.approx(expected) @@ -82,7 +82,7 @@ def test_convert_from_miles(unit, expected): (LENGTH_INCHES, 180.0000972), ], ) -def test_convert_from_yards(unit, expected): +def test_convert_from_yards(unit, expected) -> None: """Test conversion from yards to other units.""" yards = 5 assert distance_util.convert(yards, LENGTH_YARD, unit) == pytest.approx(expected) @@ -100,7 +100,7 @@ def test_convert_from_yards(unit, expected): (LENGTH_INCHES, 60000.032400000004), ], ) -def test_convert_from_feet(unit, expected): +def test_convert_from_feet(unit, expected) -> None: """Test conversion from feet to other units.""" feet = 5000 assert distance_util.convert(feet, LENGTH_FEET, unit) == pytest.approx(expected) @@ -118,7 +118,7 @@ def test_convert_from_feet(unit, expected): (LENGTH_FEET, 416.66668), ], ) -def test_convert_from_inches(unit, expected): +def test_convert_from_inches(unit, expected) -> None: """Test conversion from inches to other units.""" inches = 5000 assert distance_util.convert(inches, LENGTH_INCHES, unit) == pytest.approx(expected) @@ -136,7 +136,7 @@ def test_convert_from_inches(unit, expected): (LENGTH_INCHES, 196850.5), ], ) -def test_convert_from_kilometers(unit, expected): +def test_convert_from_kilometers(unit, expected) -> None: """Test conversion from kilometers to other units.""" km = 5 assert distance_util.convert(km, LENGTH_KILOMETERS, unit) == pytest.approx(expected) @@ -154,7 +154,7 @@ def test_convert_from_kilometers(unit, expected): (LENGTH_INCHES, 196850.5), ], ) -def test_convert_from_meters(unit, expected): +def test_convert_from_meters(unit, expected) -> None: """Test conversion from meters to other units.""" m = 5000 assert distance_util.convert(m, LENGTH_METERS, unit) == pytest.approx(expected) @@ -172,7 +172,7 @@ def test_convert_from_meters(unit, expected): (LENGTH_INCHES, 196850.5), ], ) -def test_convert_from_centimeters(unit, expected): +def test_convert_from_centimeters(unit, expected) -> None: """Test conversion from centimeters to other units.""" cm = 500000 assert distance_util.convert(cm, LENGTH_CENTIMETERS, unit) == pytest.approx( @@ -192,7 +192,7 @@ def test_convert_from_centimeters(unit, expected): (LENGTH_INCHES, 196850.5), ], ) -def test_convert_from_millimeters(unit, expected): +def test_convert_from_millimeters(unit, expected) -> None: """Test conversion from millimeters to other units.""" mm = 5000000 assert distance_util.convert(mm, LENGTH_MILLIMETERS, unit) == pytest.approx( diff --git a/tests/util/test_dt.py b/tests/util/test_dt.py index 1f4758a75d8..e9cde21a265 100644 --- a/tests/util/test_dt.py +++ b/tests/util/test_dt.py @@ -325,7 +325,7 @@ def test_find_next_time_expression_time_dst() -> None: ), ], ) -def test_find_next_time_expression_entering_dst(now_dt, expected_dt): +def test_find_next_time_expression_entering_dst(now_dt, expected_dt) -> None: """Test entering daylight saving time for find_next_time_expression_time.""" tz = dt_util.get_time_zone("Europe/Vienna") dt_util.set_default_time_zone(tz) @@ -409,7 +409,7 @@ def test_find_next_time_expression_entering_dst(now_dt, expected_dt): ), ], ) -def test_find_next_time_expression_exiting_dst(now_dt, expected_dt): +def test_find_next_time_expression_exiting_dst(now_dt, expected_dt) -> None: """Test exiting daylight saving time for find_next_time_expression_time.""" tz = dt_util.get_time_zone("Europe/Vienna") dt_util.set_default_time_zone(tz) diff --git a/tests/util/test_executor.py b/tests/util/test_executor.py index 70c1f5f3a7f..763efa494e7 100644 --- a/tests/util/test_executor.py +++ b/tests/util/test_executor.py @@ -10,7 +10,9 @@ from homeassistant.util import executor from homeassistant.util.executor import InterruptibleThreadPoolExecutor -async def test_executor_shutdown_can_interrupt_threads(caplog): +async def test_executor_shutdown_can_interrupt_threads( + caplog: pytest.LogCaptureFixture, +) -> None: """Test that the executor shutdown can interrupt threads.""" iexecutor = InterruptibleThreadPoolExecutor() @@ -34,7 +36,9 @@ async def test_executor_shutdown_can_interrupt_threads(caplog): assert "time.sleep(0.1)" in caplog.text -async def test_executor_shutdown_only_logs_max_attempts(caplog): +async def test_executor_shutdown_only_logs_max_attempts( + caplog: pytest.LogCaptureFixture, +) -> None: """Test that the executor shutdown will only log max attempts.""" iexecutor = InterruptibleThreadPoolExecutor() @@ -52,7 +56,9 @@ async def test_executor_shutdown_only_logs_max_attempts(caplog): iexecutor.shutdown() -async def test_executor_shutdown_does_not_log_shutdown_on_first_attempt(caplog): +async def test_executor_shutdown_does_not_log_shutdown_on_first_attempt( + caplog: pytest.LogCaptureFixture, +) -> None: """Test that the executor shutdown does not log on first attempt.""" iexecutor = InterruptibleThreadPoolExecutor() @@ -68,7 +74,7 @@ async def test_executor_shutdown_does_not_log_shutdown_on_first_attempt(caplog): assert "is still running at shutdown" not in caplog.text -async def test_overall_timeout_reached(caplog): +async def test_overall_timeout_reached(caplog: pytest.LogCaptureFixture) -> None: """Test that shutdown moves on when the overall timeout is reached.""" iexecutor = InterruptibleThreadPoolExecutor() diff --git a/tests/util/test_file.py b/tests/util/test_file.py index 41d104cdd8a..5934dc689f0 100644 --- a/tests/util/test_file.py +++ b/tests/util/test_file.py @@ -9,7 +9,7 @@ from homeassistant.util.file import WriteError, write_utf8_file, write_utf8_file @pytest.mark.parametrize("func", [write_utf8_file, write_utf8_file_atomic]) -def test_write_utf8_file_atomic_private(tmpdir, func): +def test_write_utf8_file_atomic_private(tmpdir, func) -> None: """Test files can be written as 0o600 or 0o644.""" test_dir = tmpdir.mkdir("files") test_file = Path(test_dir / "test.json") @@ -25,7 +25,7 @@ def test_write_utf8_file_atomic_private(tmpdir, func): assert os.stat(test_file).st_mode & 0o777 == 0o600 -def test_write_utf8_file_fails_at_creation(tmpdir): +def test_write_utf8_file_fails_at_creation(tmpdir) -> None: """Test that failed creation of the temp file does not create an empty file.""" test_dir = tmpdir.mkdir("files") test_file = Path(test_dir / "test.json") @@ -38,7 +38,9 @@ def test_write_utf8_file_fails_at_creation(tmpdir): assert not os.path.exists(test_file) -def test_write_utf8_file_fails_at_rename(tmpdir, caplog): +def test_write_utf8_file_fails_at_rename( + tmpdir, caplog: pytest.LogCaptureFixture +) -> None: """Test that if rename fails not not remove, we do not log the failed cleanup.""" test_dir = tmpdir.mkdir("files") test_file = Path(test_dir / "test.json") @@ -53,7 +55,9 @@ def test_write_utf8_file_fails_at_rename(tmpdir, caplog): assert "File replacement cleanup failed" not in caplog.text -def test_write_utf8_file_fails_at_rename_and_remove(tmpdir, caplog): +def test_write_utf8_file_fails_at_rename_and_remove( + tmpdir, caplog: pytest.LogCaptureFixture +) -> None: """Test that if rename and remove both fail, we log the failed cleanup.""" test_dir = tmpdir.mkdir("files") test_file = Path(test_dir / "test.json") @@ -66,7 +70,7 @@ def test_write_utf8_file_fails_at_rename_and_remove(tmpdir, caplog): assert "File replacement cleanup failed" in caplog.text -def test_write_utf8_file_atomic_fails(tmpdir): +def test_write_utf8_file_atomic_fails(tmpdir) -> None: """Test OSError from write_utf8_file_atomic is rethrown as WriteError.""" test_dir = tmpdir.mkdir("files") test_file = Path(test_dir / "test.json") diff --git a/tests/util/test_init.py b/tests/util/test_init.py index 4e9de0bdd85..3ead4cf41c8 100644 --- a/tests/util/test_init.py +++ b/tests/util/test_init.py @@ -200,7 +200,7 @@ def test_throttle_on_two_method() -> None: @patch.object(util, "random") -def test_get_random_string(mock_random): +def test_get_random_string(mock_random) -> None: """Test get random string.""" results = ["A", "B", "C"] diff --git a/tests/util/test_location.py b/tests/util/test_location.py index 801b145373d..e998c10e565 100644 --- a/tests/util/test_location.py +++ b/tests/util/test_location.py @@ -8,6 +8,7 @@ from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.util.location as location_util from tests.common import load_fixture +from tests.test_util.aiohttp import AiohttpClientMocker # Paris COORDINATES_PARIS = (48.864716, 2.349014) @@ -73,7 +74,9 @@ def test_get_miles() -> None: assert round(miles, 2) == DISTANCE_MILES -async def test_detect_location_info_whoami(aioclient_mock, session): +async def test_detect_location_info_whoami( + aioclient_mock: AiohttpClientMocker, session +) -> None: """Test detect location info using services.home-assistant.io/whoami.""" aioclient_mock.get(location_util.WHOAMI_URL, text=load_fixture("whoami.json")) @@ -95,7 +98,7 @@ async def test_detect_location_info_whoami(aioclient_mock, session): assert info.use_metric -async def test_dev_url(aioclient_mock, session): +async def test_dev_url(aioclient_mock: AiohttpClientMocker, session) -> None: """Test usage of dev URL.""" aioclient_mock.get(location_util.WHOAMI_URL_DEV, text=load_fixture("whoami.json")) with patch("homeassistant.util.location.HA_VERSION", "1.0.dev0"): @@ -106,7 +109,7 @@ async def test_dev_url(aioclient_mock, session): assert info.currency == "XXX" -async def test_whoami_query_raises(raising_session): +async def test_whoami_query_raises(raising_session) -> None: """Test whoami query when the request to API fails.""" info = await location_util._get_whoami(raising_session) assert info is None diff --git a/tests/util/test_logging.py b/tests/util/test_logging.py index 2a2e0107a83..39bf38f56b1 100644 --- a/tests/util/test_logging.py +++ b/tests/util/test_logging.py @@ -78,7 +78,9 @@ async def test_migrate_log_handler(hass: HomeAssistant) -> None: @pytest.mark.no_fail_on_log_exception -async def test_async_create_catching_coro(hass, caplog): +async def test_async_create_catching_coro( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """Test exception logging of wrapped coroutine.""" async def job(): diff --git a/tests/util/test_package.py b/tests/util/test_package.py index 7c9ecdd75fe..2a190d2aea5 100644 --- a/tests/util/test_package.py +++ b/tests/util/test_package.py @@ -84,7 +84,7 @@ def mock_async_subprocess(): return async_popen -def test_install(mock_sys, mock_popen, mock_env_copy, mock_venv): +def test_install(mock_sys, mock_popen, mock_env_copy, mock_venv) -> None: """Test an install attempt on a package that doesn't exist.""" env = mock_env_copy() assert package.install_package(TEST_NEW_REQ, False) @@ -100,7 +100,7 @@ def test_install(mock_sys, mock_popen, mock_env_copy, mock_venv): assert mock_popen.return_value.communicate.call_count == 1 -def test_install_upgrade(mock_sys, mock_popen, mock_env_copy, mock_venv): +def test_install_upgrade(mock_sys, mock_popen, mock_env_copy, mock_venv) -> None: """Test an upgrade attempt on a package.""" env = mock_env_copy() assert package.install_package(TEST_NEW_REQ) @@ -124,7 +124,7 @@ def test_install_upgrade(mock_sys, mock_popen, mock_env_copy, mock_venv): assert mock_popen.return_value.communicate.call_count == 1 -def test_install_target(mock_sys, mock_popen, mock_env_copy, mock_venv): +def test_install_target(mock_sys, mock_popen, mock_env_copy, mock_venv) -> None: """Test an install with a target.""" target = "target_folder" env = mock_env_copy() @@ -149,14 +149,16 @@ def test_install_target(mock_sys, mock_popen, mock_env_copy, mock_venv): assert mock_popen.return_value.communicate.call_count == 1 -def test_install_target_venv(mock_sys, mock_popen, mock_env_copy, mock_venv): +def test_install_target_venv(mock_sys, mock_popen, mock_env_copy, mock_venv) -> None: """Test an install with a target in a virtual environment.""" target = "target_folder" with pytest.raises(AssertionError): package.install_package(TEST_NEW_REQ, False, target=target) -def test_install_error(caplog, mock_sys, mock_popen, mock_venv): +def test_install_error( + caplog: pytest.LogCaptureFixture, mock_sys, mock_popen, mock_venv +) -> None: """Test an install that errors out.""" caplog.set_level(logging.WARNING) mock_popen.return_value.returncode = 1 @@ -166,7 +168,7 @@ def test_install_error(caplog, mock_sys, mock_popen, mock_venv): assert record.levelname == "ERROR" -def test_install_constraint(mock_sys, mock_popen, mock_env_copy, mock_venv): +def test_install_constraint(mock_sys, mock_popen, mock_env_copy, mock_venv) -> None: """Test install with constraint file on not installed package.""" env = mock_env_copy() constraints = "constraints_file.txt" @@ -192,7 +194,7 @@ def test_install_constraint(mock_sys, mock_popen, mock_env_copy, mock_venv): assert mock_popen.return_value.communicate.call_count == 1 -def test_install_find_links(mock_sys, mock_popen, mock_env_copy, mock_venv): +def test_install_find_links(mock_sys, mock_popen, mock_env_copy, mock_venv) -> None: """Test install with find-links on not installed package.""" env = mock_env_copy() link = "https://wheels-repository" @@ -219,7 +221,7 @@ def test_install_find_links(mock_sys, mock_popen, mock_env_copy, mock_venv): assert mock_popen.return_value.communicate.call_count == 1 -async def test_async_get_user_site(mock_env_copy): +async def test_async_get_user_site(mock_env_copy) -> None: """Test async get user site directory.""" deps_dir = "/deps_dir" env = mock_env_copy() diff --git a/tests/util/test_speed.py b/tests/util/test_speed.py index a425ff2274e..ae47b4d39cc 100644 --- a/tests/util/test_speed.py +++ b/tests/util/test_speed.py @@ -85,7 +85,7 @@ def test_convert_nonnumeric_value() -> None: (5, UnitOfSpeed.FEET_PER_SECOND, 1.524, UnitOfSpeed.METERS_PER_SECOND), ], ) -def test_convert_different_units(from_value, from_unit, expected, to_unit): +def test_convert_different_units(from_value, from_unit, expected, to_unit) -> None: """Test conversion between units.""" assert speed_util.convert(from_value, from_unit, to_unit) == pytest.approx( expected, rel=1e-4 diff --git a/tests/util/test_timeout.py b/tests/util/test_timeout.py index 74a20c0c100..60c87fa7434 100644 --- a/tests/util/test_timeout.py +++ b/tests/util/test_timeout.py @@ -97,8 +97,8 @@ async def test_mix_global_timeout_freeze_and_zone_freeze_different_order( async def test_mix_global_timeout_freeze_and_zone_freeze_other_zone_inside_executor_job( - hass, -): + hass: HomeAssistant, +) -> None: """Test a simple global timeout freeze other zone inside an executor job.""" timeout = TimeoutManager() @@ -114,8 +114,8 @@ async def test_mix_global_timeout_freeze_and_zone_freeze_other_zone_inside_execu async def test_mix_global_timeout_freeze_and_zone_freeze_inside_executor_job_second_job_outside_zone_context( - hass, -): + hass: HomeAssistant, +) -> None: """Test a simple global timeout freeze inside an executor job with second job outside of zone context.""" timeout = TimeoutManager() diff --git a/tests/util/test_variance.py b/tests/util/test_variance.py index f4db65dbfd7..2072e3f3417 100644 --- a/tests/util/test_variance.py +++ b/tests/util/test_variance.py @@ -33,7 +33,7 @@ from homeassistant.util.variance import ignore_variance ), ], ) -def test_ignore_variance(value_1, value_2, variance, expected): +def test_ignore_variance(value_1, value_2, variance, expected) -> None: """Test ignore_variance.""" with_ignore = ignore_variance(lambda x: x, variance) assert with_ignore(value_1) == value_1 diff --git a/tests/util/test_volume.py b/tests/util/test_volume.py index 1a49200b838..f8a73929b70 100644 --- a/tests/util/test_volume.py +++ b/tests/util/test_volume.py @@ -130,7 +130,7 @@ def test_convert_from_cubic_feet() -> None: (VOLUME_MILLILITERS, VOLUME_LITERS, 0.5), ], ) -def test_convert(source_unit, target_unit, expected): +def test_convert(source_unit, target_unit, expected) -> None: """Test conversion between units.""" value = 500 assert volume_util.convert(value, source_unit, target_unit) == pytest.approx(