Add type hints to integration tests (part 3) (#87844)

This commit is contained in:
epenet 2023-02-10 16:05:01 +01:00 committed by GitHub
parent 22bfb99db4
commit fa7acb4f0d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
50 changed files with 745 additions and 386 deletions

View File

@ -32,7 +32,7 @@ DISCOVERY_INFO = zeroconf.ZeroconfServiceInfo(
) )
async def test_form_user(hass, mock_zeroconf): async def test_form_user(hass: HomeAssistant, mock_zeroconf: None) -> None:
"""Test we get the form.""" """Test we get the form."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
@ -96,7 +96,9 @@ async def test_form_user(hass, mock_zeroconf):
assert len(mock_setup_entry.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
async def test_form_get_info_connection_error(hass, mock_zeroconf): async def test_form_get_info_connection_error(
hass: HomeAssistant, mock_zeroconf: None
) -> None:
"""Test we handle connection error.""" """Test we handle connection error."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -140,7 +142,7 @@ async def test_form_get_info_exception(hass: HomeAssistant) -> None:
assert result2["errors"] == {"base": "unknown"} assert result2["errors"] == {"base": "unknown"}
async def test_form_pairing_error(hass, mock_zeroconf): async def test_form_pairing_error(hass: HomeAssistant, mock_zeroconf: None) -> None:
"""Test we handle pairing error.""" """Test we handle pairing error."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -182,7 +184,7 @@ async def test_form_pairing_error(hass, mock_zeroconf):
assert result3["errors"] == {"base": "pairing_failed"} assert result3["errors"] == {"base": "pairing_failed"}
async def test_form_user_invalid_auth(hass, mock_zeroconf): async def test_form_user_invalid_auth(hass: HomeAssistant, mock_zeroconf: None) -> None:
"""Test we handle invalid auth.""" """Test we handle invalid auth."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -231,7 +233,9 @@ async def test_form_user_invalid_auth(hass, mock_zeroconf):
assert result3["errors"] == {"base": "invalid_auth"} assert result3["errors"] == {"base": "invalid_auth"}
async def test_form_validate_connection_error(hass, mock_zeroconf): async def test_form_validate_connection_error(
hass: HomeAssistant, mock_zeroconf: None
) -> None:
"""Test we handle connection error.""" """Test we handle connection error."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -280,7 +284,9 @@ async def test_form_validate_connection_error(hass, mock_zeroconf):
assert result3["errors"] == {"base": "cannot_connect"} assert result3["errors"] == {"base": "cannot_connect"}
async def test_form_validate_session_error(hass, mock_zeroconf): async def test_form_validate_session_error(
hass: HomeAssistant, mock_zeroconf: None
) -> None:
"""Test we handle session error.""" """Test we handle session error."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -329,7 +335,9 @@ async def test_form_validate_session_error(hass, mock_zeroconf):
assert result3["errors"] == {"base": "session_error"} assert result3["errors"] == {"base": "session_error"}
async def test_form_validate_exception(hass, mock_zeroconf): async def test_form_validate_exception(
hass: HomeAssistant, mock_zeroconf: None
) -> None:
"""Test we handle exception.""" """Test we handle exception."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -378,7 +386,9 @@ async def test_form_validate_exception(hass, mock_zeroconf):
assert result3["errors"] == {"base": "unknown"} assert result3["errors"] == {"base": "unknown"}
async def test_form_already_configured(hass, mock_zeroconf): async def test_form_already_configured(
hass: HomeAssistant, mock_zeroconf: None
) -> None:
"""Test we get the form.""" """Test we get the form."""
entry = MockConfigEntry( entry = MockConfigEntry(
@ -414,7 +424,7 @@ async def test_form_already_configured(hass, mock_zeroconf):
assert entry.data["host"] == "1.1.1.1" assert entry.data["host"] == "1.1.1.1"
async def test_zeroconf(hass, mock_zeroconf): async def test_zeroconf(hass: HomeAssistant, mock_zeroconf: None) -> None:
"""Test we get the form.""" """Test we get the form."""
with patch( with patch(
@ -482,7 +492,9 @@ async def test_zeroconf(hass, mock_zeroconf):
assert len(mock_setup_entry.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
async def test_zeroconf_already_configured(hass, mock_zeroconf): async def test_zeroconf_already_configured(
hass: HomeAssistant, mock_zeroconf: None
) -> None:
"""Test we get the form.""" """Test we get the form."""
entry = MockConfigEntry( entry = MockConfigEntry(
@ -515,7 +527,9 @@ async def test_zeroconf_already_configured(hass, mock_zeroconf):
assert entry.data["host"] == "1.1.1.1" assert entry.data["host"] == "1.1.1.1"
async def test_zeroconf_cannot_connect(hass, mock_zeroconf): async def test_zeroconf_cannot_connect(
hass: HomeAssistant, mock_zeroconf: None
) -> None:
"""Test we get the form.""" """Test we get the form."""
with patch( with patch(
"boschshcpy.session.SHCSession.mdns_info", side_effect=SHCConnectionError "boschshcpy.session.SHCSession.mdns_info", side_effect=SHCConnectionError
@ -529,7 +543,7 @@ async def test_zeroconf_cannot_connect(hass, mock_zeroconf):
assert result["reason"] == "cannot_connect" assert result["reason"] == "cannot_connect"
async def test_zeroconf_not_bosch_shc(hass, mock_zeroconf): async def test_zeroconf_not_bosch_shc(hass: HomeAssistant, mock_zeroconf: None) -> None:
"""Test we filter out non-bosch_shc devices.""" """Test we filter out non-bosch_shc devices."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,
@ -548,7 +562,7 @@ async def test_zeroconf_not_bosch_shc(hass, mock_zeroconf):
assert result["reason"] == "not_bosch_shc" assert result["reason"] == "not_bosch_shc"
async def test_reauth(hass, mock_zeroconf): async def test_reauth(hass: HomeAssistant, mock_zeroconf: None) -> None:
"""Test we get the form.""" """Test we get the form."""
mock_config = MockConfigEntry( mock_config = MockConfigEntry(

View File

@ -199,7 +199,7 @@ async def test_user_invalid_host(hass: HomeAssistant) -> None:
(BraviaConnectionError, "cannot_connect"), (BraviaConnectionError, "cannot_connect"),
], ],
) )
async def test_pin_form_error(hass, side_effect, error_message): async def test_pin_form_error(hass: HomeAssistant, side_effect, error_message) -> None:
"""Test that PIN form errors are correct.""" """Test that PIN form errors are correct."""
with patch( with patch(
"pybravia.BraviaClient.connect", "pybravia.BraviaClient.connect",
@ -226,7 +226,7 @@ async def test_pin_form_error(hass, side_effect, error_message):
(BraviaConnectionError, "cannot_connect"), (BraviaConnectionError, "cannot_connect"),
], ],
) )
async def test_psk_form_error(hass, side_effect, error_message): async def test_psk_form_error(hass: HomeAssistant, side_effect, error_message) -> None:
"""Test that PSK form errors are correct.""" """Test that PSK form errors are correct."""
with patch( with patch(
"pybravia.BraviaClient.connect", "pybravia.BraviaClient.connect",
@ -382,7 +382,7 @@ async def test_create_entry_psk(hass: HomeAssistant) -> None:
(False, "newpsk"), (False, "newpsk"),
], ],
) )
async def test_reauth_successful(hass, use_psk, new_pin): async def test_reauth_successful(hass: HomeAssistant, use_psk, new_pin) -> None:
"""Test that the reauthorization is successful.""" """Test that the reauthorization is successful."""
config_entry = MockConfigEntry( config_entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,

View File

@ -71,7 +71,7 @@ async def test_form_duplicate_login(hass: HomeAssistant) -> None:
(Exception, "unknown"), (Exception, "unknown"),
], ],
) )
async def test_form_error(hass, side_effect, error_message): async def test_form_error(hass: HomeAssistant, side_effect, error_message) -> None:
"""Test we handle cannot connect.""" """Test we handle cannot connect."""
with patch( with patch(
"homeassistant.components.brunt.config_flow.BruntClientAsync.async_login", "homeassistant.components.brunt.config_flow.BruntClientAsync.async_login",
@ -98,7 +98,9 @@ async def test_form_error(hass, side_effect, error_message):
), ),
], ],
) )
async def test_reauth(hass, side_effect, result_type, password, step_id, reason): async def test_reauth(
hass: HomeAssistant, side_effect, result_type, password, step_id, reason
) -> None:
"""Test uniqueness of username.""" """Test uniqueness of username."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,

View File

@ -12,7 +12,7 @@ async def test_diagnostics(
hass: HomeAssistant, hass: HomeAssistant,
hass_client: ClientSessionGenerator, hass_client: ClientSessionGenerator,
init_integration: MockConfigEntry, init_integration: MockConfigEntry,
): ) -> None:
"""Test diagnostics.""" """Test diagnostics."""
diagnostics_fixture = json.loads(load_fixture("bsblan/diagnostics.json")) diagnostics_fixture = json.loads(load_fixture("bsblan/diagnostics.json"))

View File

@ -1,11 +1,11 @@
"""Test BTHome binary sensors.""" """Test BTHome binary sensors."""
import logging import logging
import pytest import pytest
from homeassistant.components.bthome.const import DOMAIN from homeassistant.components.bthome.const import DOMAIN
from homeassistant.const import ATTR_FRIENDLY_NAME, STATE_OFF, STATE_ON from homeassistant.const import ATTR_FRIENDLY_NAME, STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from . import make_bthome_v1_adv, make_bthome_v2_adv from . import make_bthome_v1_adv, make_bthome_v2_adv
@ -66,12 +66,12 @@ _LOGGER = logging.getLogger(__name__)
], ],
) )
async def test_v1_binary_sensors( async def test_v1_binary_sensors(
hass, hass: HomeAssistant,
mac_address, mac_address,
advertisement, advertisement,
bind_key, bind_key,
result, result,
): ) -> None:
"""Test the different BTHome v1 binary sensors.""" """Test the different BTHome v1 binary sensors."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,
@ -152,12 +152,12 @@ async def test_v1_binary_sensors(
], ],
) )
async def test_v2_binary_sensors( async def test_v2_binary_sensors(
hass, hass: HomeAssistant,
mac_address, mac_address,
advertisement, advertisement,
bind_key, bind_key,
result, result,
): ) -> None:
"""Test the different BTHome v2 binary sensors.""" """Test the different BTHome v2 binary sensors."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,

View File

@ -1,6 +1,4 @@
"""Test the BTHome sensors.""" """Test the BTHome sensors."""
import logging import logging
import pytest import pytest
@ -8,6 +6,7 @@ import pytest
from homeassistant.components.bthome.const import DOMAIN from homeassistant.components.bthome.const import DOMAIN
from homeassistant.components.sensor import ATTR_STATE_CLASS from homeassistant.components.sensor import ATTR_STATE_CLASS
from homeassistant.const import ATTR_FRIENDLY_NAME, ATTR_UNIT_OF_MEASUREMENT from homeassistant.const import ATTR_FRIENDLY_NAME, ATTR_UNIT_OF_MEASUREMENT
from homeassistant.core import HomeAssistant
from . import make_bthome_v1_adv, make_bthome_v2_adv, make_encrypted_bthome_v1_adv from . import make_bthome_v1_adv, make_bthome_v2_adv, make_encrypted_bthome_v1_adv
@ -332,12 +331,12 @@ _LOGGER = logging.getLogger(__name__)
], ],
) )
async def test_v1_sensors( async def test_v1_sensors(
hass, hass: HomeAssistant,
mac_address, mac_address,
advertisement, advertisement,
bind_key, bind_key,
result, result,
): ) -> None:
"""Test the different BTHome V1 sensors.""" """Test the different BTHome V1 sensors."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,
@ -948,12 +947,12 @@ async def test_v1_sensors(
], ],
) )
async def test_v2_sensors( async def test_v2_sensors(
hass, hass: HomeAssistant,
mac_address, mac_address,
advertisement, advertisement,
bind_key, bind_key,
result, result,
): ) -> None:
"""Test the different BTHome V2 sensors.""" """Test the different BTHome V2 sensors."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,

View File

@ -8,10 +8,13 @@ from aiohttp.client_exceptions import ClientResponseError
from homeassistant.components.buienradar.const import CONF_COUNTRY, CONF_DELTA, DOMAIN from homeassistant.components.buienradar.const import CONF_COUNTRY, CONF_DELTA, DOMAIN
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_registry import async_get from homeassistant.helpers.entity_registry import async_get
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import ClientSessionGenerator
# An infinitesimally small time-delta. # An infinitesimally small time-delta.
EPSILON_DELTA = 0.0000000001 EPSILON_DELTA = 0.0000000001
@ -42,7 +45,11 @@ async def _setup_config_entry(hass, entry):
await hass.async_block_till_done() await hass.async_block_till_done()
async def test_fetching_url_and_caching(aioclient_mock, hass, hass_client): async def test_fetching_url_and_caching(
aioclient_mock: AiohttpClientMocker,
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
) -> None:
"""Test that it fetches the given url.""" """Test that it fetches the given url."""
aioclient_mock.get(radar_map_url(), text="hello world") aioclient_mock.get(radar_map_url(), text="hello world")
@ -68,7 +75,11 @@ async def test_fetching_url_and_caching(aioclient_mock, hass, hass_client):
assert aioclient_mock.call_count == 1 assert aioclient_mock.call_count == 1
async def test_expire_delta(aioclient_mock, hass, hass_client): async def test_expire_delta(
aioclient_mock: AiohttpClientMocker,
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
) -> None:
"""Test that the cache expires after delta.""" """Test that the cache expires after delta."""
aioclient_mock.get(radar_map_url(), text="hello world") aioclient_mock.get(radar_map_url(), text="hello world")
@ -97,7 +108,11 @@ async def test_expire_delta(aioclient_mock, hass, hass_client):
assert aioclient_mock.call_count == 2 assert aioclient_mock.call_count == 2
async def test_only_one_fetch_at_a_time(aioclient_mock, hass, hass_client): async def test_only_one_fetch_at_a_time(
aioclient_mock: AiohttpClientMocker,
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
) -> None:
"""Test that it fetches with only one request at the same time.""" """Test that it fetches with only one request at the same time."""
aioclient_mock.get(radar_map_url(), text="hello world") aioclient_mock.get(radar_map_url(), text="hello world")
@ -120,7 +135,11 @@ async def test_only_one_fetch_at_a_time(aioclient_mock, hass, hass_client):
assert aioclient_mock.call_count == 1 assert aioclient_mock.call_count == 1
async def test_belgium_country(aioclient_mock, hass, hass_client): async def test_belgium_country(
aioclient_mock: AiohttpClientMocker,
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
) -> None:
"""Test that it actually adheres to another country like Belgium.""" """Test that it actually adheres to another country like Belgium."""
aioclient_mock.get(radar_map_url(country_code="BE"), text="hello world") aioclient_mock.get(radar_map_url(country_code="BE"), text="hello world")
@ -140,7 +159,11 @@ async def test_belgium_country(aioclient_mock, hass, hass_client):
assert aioclient_mock.call_count == 1 assert aioclient_mock.call_count == 1
async def test_failure_response_not_cached(aioclient_mock, hass, hass_client): async def test_failure_response_not_cached(
aioclient_mock: AiohttpClientMocker,
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
) -> None:
"""Test that it does not cache a failure response.""" """Test that it does not cache a failure response."""
aioclient_mock.get(radar_map_url(), text="hello world", status=401) aioclient_mock.get(radar_map_url(), text="hello world", status=401)
@ -158,7 +181,11 @@ async def test_failure_response_not_cached(aioclient_mock, hass, hass_client):
assert aioclient_mock.call_count == 2 assert aioclient_mock.call_count == 2
async def test_last_modified_updates(aioclient_mock, hass, hass_client): async def test_last_modified_updates(
aioclient_mock: AiohttpClientMocker,
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
) -> None:
"""Test that it does respect HTTP not modified.""" """Test that it does respect HTTP not modified."""
# Build Last-Modified header value # Build Last-Modified header value
now = dt_util.utcnow() now = dt_util.utcnow()
@ -203,7 +230,11 @@ async def test_last_modified_updates(aioclient_mock, hass, hass_client):
assert (await resp_1.read()) == (await resp_2.read()) assert (await resp_1.read()) == (await resp_2.read())
async def test_retries_after_error(aioclient_mock, hass, hass_client): async def test_retries_after_error(
aioclient_mock: AiohttpClientMocker,
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
) -> None:
"""Test that it does retry after an error instead of caching.""" """Test that it does retry after an error instead of caching."""
mock_entry = MockConfigEntry(domain=DOMAIN, unique_id="TEST_ID", data=TEST_CFG_DATA) mock_entry = MockConfigEntry(domain=DOMAIN, unique_id="TEST_ID", data=TEST_CFG_DATA)

View File

@ -2,14 +2,18 @@
from homeassistant.components.buienradar.const import DOMAIN from homeassistant.components.buienradar.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
TEST_LATITUDE = 51.5288504 TEST_LATITUDE = 51.5288504
TEST_LONGITUDE = 5.4002156 TEST_LONGITUDE = 5.4002156
async def test_load_unload(aioclient_mock, hass): async def test_load_unload(
aioclient_mock: AiohttpClientMocker, hass: HomeAssistant
) -> None:
"""Test options flow.""" """Test options flow."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,

View File

@ -1,9 +1,11 @@
"""The tests for the Buienradar sensor platform.""" """The tests for the Buienradar sensor platform."""
from homeassistant.components.buienradar.const import DOMAIN from homeassistant.components.buienradar.const import DOMAIN
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_registry import async_get from homeassistant.helpers.entity_registry import async_get
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
TEST_LONGITUDE = 51.5288504 TEST_LONGITUDE = 51.5288504
TEST_LATITUDE = 5.4002156 TEST_LATITUDE = 5.4002156
@ -12,7 +14,9 @@ CONDITIONS = ["stationname", "temperature"]
TEST_CFG_DATA = {CONF_LATITUDE: TEST_LATITUDE, CONF_LONGITUDE: TEST_LONGITUDE} TEST_CFG_DATA = {CONF_LATITUDE: TEST_LATITUDE, CONF_LONGITUDE: TEST_LONGITUDE}
async def test_smoke_test_setup_component(aioclient_mock, hass): async def test_smoke_test_setup_component(
aioclient_mock: AiohttpClientMocker, hass: HomeAssistant
) -> None:
"""Smoke test for successfully set-up with default config.""" """Smoke test for successfully set-up with default config."""
mock_entry = MockConfigEntry(domain=DOMAIN, unique_id="TEST_ID", data=TEST_CFG_DATA) mock_entry = MockConfigEntry(domain=DOMAIN, unique_id="TEST_ID", data=TEST_CFG_DATA)

View File

@ -1,13 +1,17 @@
"""The tests for the buienradar weather component.""" """The tests for the buienradar weather component."""
from homeassistant.components.buienradar.const import DOMAIN from homeassistant.components.buienradar.const import DOMAIN
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
TEST_CFG_DATA = {CONF_LATITUDE: 51.5288504, CONF_LONGITUDE: 5.4002156} TEST_CFG_DATA = {CONF_LATITUDE: 51.5288504, CONF_LONGITUDE: 5.4002156}
async def test_smoke_test_setup_component(aioclient_mock, hass): async def test_smoke_test_setup_component(
aioclient_mock: AiohttpClientMocker, hass: HomeAssistant
) -> None:
"""Smoke test for successfully set-up with default config.""" """Smoke test for successfully set-up with default config."""
mock_entry = MockConfigEntry(domain=DOMAIN, unique_id="TEST_ID", data=TEST_CFG_DATA) mock_entry = MockConfigEntry(domain=DOMAIN, unique_id="TEST_ID", data=TEST_CFG_DATA)

View File

@ -104,7 +104,7 @@ async def test_get_triggers_hidden_auxiliary(
assert_lists_same(triggers, expected_triggers) assert_lists_same(triggers, expected_triggers)
async def test_if_fires_on_state_change(hass, calls): async def test_if_fires_on_state_change(hass: HomeAssistant, calls) -> None:
"""Test for turn_on and turn_off triggers firing.""" """Test for turn_on and turn_off triggers firing."""
hass.states.async_set("button.entity", "unknown") hass.states.async_set("button.entity", "unknown")

View File

@ -28,7 +28,11 @@ async def test_button(hass: HomeAssistant) -> None:
assert button.press.called assert button.press.called
async def test_custom_integration(hass, caplog, enable_custom_integrations): async def test_custom_integration(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
enable_custom_integrations: None,
) -> None:
"""Test we integration.""" """Test we integration."""
platform = getattr(hass.components, f"test.{DOMAIN}") platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init() platform.init()
@ -51,7 +55,9 @@ async def test_custom_integration(hass, caplog, enable_custom_integrations):
assert "The button has been pressed" in caplog.text assert "The button has been pressed" in caplog.text
async def test_restore_state(hass, enable_custom_integrations): async def test_restore_state(
hass: HomeAssistant, enable_custom_integrations: None
) -> None:
"""Test we restore state integration.""" """Test we restore state integration."""
mock_restore_cache(hass, (State("button.button_1", "2021-01-01T23:59:59+00:00"),)) mock_restore_cache(hass, (State("button.button_1", "2021-01-01T23:59:59+00:00"),))

View File

@ -7,6 +7,7 @@ from caldav.objects import Event
import pytest import pytest
from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from homeassistant.util import dt from homeassistant.util import dt
@ -359,7 +360,7 @@ def _mock_calendar(name):
return calendar return calendar
async def test_setup_component(hass, mock_dav_client): async def test_setup_component(hass: HomeAssistant, mock_dav_client) -> None:
"""Test setup component with calendars.""" """Test setup component with calendars."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -370,7 +371,9 @@ async def test_setup_component(hass, mock_dav_client):
assert state.name == "Second" assert state.name == "Second"
async def test_setup_component_with_no_calendar_matching(hass, mock_dav_client): async def test_setup_component_with_no_calendar_matching(
hass: HomeAssistant, mock_dav_client
) -> None:
"""Test setup component with wrong calendar.""" """Test setup component with wrong calendar."""
config = dict(CALDAV_CONFIG) config = dict(CALDAV_CONFIG)
config["calendars"] = ["none"] config["calendars"] = ["none"]
@ -382,7 +385,9 @@ async def test_setup_component_with_no_calendar_matching(hass, mock_dav_client):
assert not all_calendar_states assert not all_calendar_states
async def test_setup_component_with_a_calendar_match(hass, mock_dav_client): async def test_setup_component_with_a_calendar_match(
hass: HomeAssistant, mock_dav_client
) -> None:
"""Test setup component with right calendar.""" """Test setup component with right calendar."""
config = dict(CALDAV_CONFIG) config = dict(CALDAV_CONFIG)
config["calendars"] = ["Second"] config["calendars"] = ["Second"]
@ -396,7 +401,9 @@ async def test_setup_component_with_a_calendar_match(hass, mock_dav_client):
assert state.name == "Second" assert state.name == "Second"
async def test_setup_component_with_one_custom_calendar(hass, mock_dav_client): async def test_setup_component_with_one_custom_calendar(
hass: HomeAssistant, mock_dav_client
) -> None:
"""Test setup component with custom calendars.""" """Test setup component with custom calendars."""
config = dict(CALDAV_CONFIG) config = dict(CALDAV_CONFIG)
config["custom_calendars"] = [ config["custom_calendars"] = [
@ -414,7 +421,7 @@ async def test_setup_component_with_one_custom_calendar(hass, mock_dav_client):
@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @pytest.mark.parametrize("set_tz", ["utc"], indirect=True)
@patch("homeassistant.util.dt.now", return_value=_local_datetime(17, 45)) @patch("homeassistant.util.dt.now", return_value=_local_datetime(17, 45))
async def test_ongoing_event(mock_now, hass, calendar, set_tz): async def test_ongoing_event(mock_now, hass: HomeAssistant, calendar, set_tz) -> None:
"""Test that the ongoing event is returned.""" """Test that the ongoing event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -436,7 +443,9 @@ async def test_ongoing_event(mock_now, hass, calendar, set_tz):
@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @pytest.mark.parametrize("set_tz", ["utc"], indirect=True)
@patch("homeassistant.util.dt.now", return_value=_local_datetime(17, 30)) @patch("homeassistant.util.dt.now", return_value=_local_datetime(17, 30))
async def test_just_ended_event(mock_now, hass, calendar, set_tz): async def test_just_ended_event(
mock_now, hass: HomeAssistant, calendar, set_tz
) -> None:
"""Test that the next ongoing event is returned.""" """Test that the next ongoing event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -458,7 +467,9 @@ async def test_just_ended_event(mock_now, hass, calendar, set_tz):
@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @pytest.mark.parametrize("set_tz", ["utc"], indirect=True)
@patch("homeassistant.util.dt.now", return_value=_local_datetime(17, 00)) @patch("homeassistant.util.dt.now", return_value=_local_datetime(17, 00))
async def test_ongoing_event_different_tz(mock_now, hass, calendar, set_tz): async def test_ongoing_event_different_tz(
mock_now, hass: HomeAssistant, calendar, set_tz
) -> None:
"""Test that the ongoing event with another timezone is returned.""" """Test that the ongoing event with another timezone is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -480,7 +491,9 @@ async def test_ongoing_event_different_tz(mock_now, hass, calendar, set_tz):
@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @pytest.mark.parametrize("set_tz", ["utc"], indirect=True)
@patch("homeassistant.util.dt.now", return_value=_local_datetime(19, 10)) @patch("homeassistant.util.dt.now", return_value=_local_datetime(19, 10))
async def test_ongoing_floating_event_returned(mock_now, hass, calendar, set_tz): async def test_ongoing_floating_event_returned(
mock_now, hass: HomeAssistant, calendar, set_tz
) -> None:
"""Test that floating events without timezones work.""" """Test that floating events without timezones work."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -502,7 +515,9 @@ async def test_ongoing_floating_event_returned(mock_now, hass, calendar, set_tz)
@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @pytest.mark.parametrize("set_tz", ["utc"], indirect=True)
@patch("homeassistant.util.dt.now", return_value=_local_datetime(8, 30)) @patch("homeassistant.util.dt.now", return_value=_local_datetime(8, 30))
async def test_ongoing_event_with_offset(mock_now, hass, calendar, set_tz): async def test_ongoing_event_with_offset(
mock_now, hass: HomeAssistant, calendar, set_tz
) -> None:
"""Test that the offset is taken into account.""" """Test that the offset is taken into account."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -524,7 +539,7 @@ async def test_ongoing_event_with_offset(mock_now, hass, calendar, set_tz):
@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @pytest.mark.parametrize("set_tz", ["utc"], indirect=True)
@patch("homeassistant.util.dt.now", return_value=_local_datetime(12, 00)) @patch("homeassistant.util.dt.now", return_value=_local_datetime(12, 00))
async def test_matching_filter(mock_now, hass, calendar, set_tz): async def test_matching_filter(mock_now, hass: HomeAssistant, calendar, set_tz) -> None:
"""Test that the matching event is returned.""" """Test that the matching event is returned."""
config = dict(CALDAV_CONFIG) config = dict(CALDAV_CONFIG)
config["custom_calendars"] = [ config["custom_calendars"] = [
@ -551,7 +566,9 @@ async def test_matching_filter(mock_now, hass, calendar, set_tz):
@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @pytest.mark.parametrize("set_tz", ["utc"], indirect=True)
@patch("homeassistant.util.dt.now", return_value=_local_datetime(12, 00)) @patch("homeassistant.util.dt.now", return_value=_local_datetime(12, 00))
async def test_matching_filter_real_regexp(mock_now, hass, calendar, set_tz): async def test_matching_filter_real_regexp(
mock_now, hass: HomeAssistant, calendar, set_tz
) -> None:
"""Test that the event matching the regexp is returned.""" """Test that the event matching the regexp is returned."""
config = dict(CALDAV_CONFIG) config = dict(CALDAV_CONFIG)
config["custom_calendars"] = [ config["custom_calendars"] = [
@ -577,7 +594,9 @@ async def test_matching_filter_real_regexp(mock_now, hass, calendar, set_tz):
@patch("homeassistant.util.dt.now", return_value=_local_datetime(20, 00)) @patch("homeassistant.util.dt.now", return_value=_local_datetime(20, 00))
async def test_filter_matching_past_event(mock_now, hass, calendar): async def test_filter_matching_past_event(
mock_now, hass: HomeAssistant, calendar
) -> None:
"""Test that the matching past event is not returned.""" """Test that the matching past event is not returned."""
config = dict(CALDAV_CONFIG) config = dict(CALDAV_CONFIG)
config["custom_calendars"] = [ config["custom_calendars"] = [
@ -593,7 +612,9 @@ async def test_filter_matching_past_event(mock_now, hass, calendar):
@patch("homeassistant.util.dt.now", return_value=_local_datetime(12, 00)) @patch("homeassistant.util.dt.now", return_value=_local_datetime(12, 00))
async def test_no_result_with_filtering(mock_now, hass, calendar): async def test_no_result_with_filtering(
mock_now, hass: HomeAssistant, calendar
) -> None:
"""Test that nothing is returned since nothing matches.""" """Test that nothing is returned since nothing matches."""
config = dict(CALDAV_CONFIG) config = dict(CALDAV_CONFIG)
config["custom_calendars"] = [ config["custom_calendars"] = [
@ -633,7 +654,9 @@ async def _day_event_returned(hass, calendar, config, date_time):
@pytest.mark.parametrize("set_tz", ["utc", "new_york", "baghdad"], indirect=True) @pytest.mark.parametrize("set_tz", ["utc", "new_york", "baghdad"], indirect=True)
async def test_all_day_event_returned_early(hass, calendar, set_tz): async def test_all_day_event_returned_early(
hass: HomeAssistant, calendar, set_tz
) -> None:
"""Test that the event lasting the whole day is returned, if it's early in the local day.""" """Test that the event lasting the whole day is returned, if it's early in the local day."""
config = dict(CALDAV_CONFIG) config = dict(CALDAV_CONFIG)
config["custom_calendars"] = [ config["custom_calendars"] = [
@ -649,7 +672,9 @@ async def test_all_day_event_returned_early(hass, calendar, set_tz):
@pytest.mark.parametrize("set_tz", ["utc", "new_york", "baghdad"], indirect=True) @pytest.mark.parametrize("set_tz", ["utc", "new_york", "baghdad"], indirect=True)
async def test_all_day_event_returned_mid(hass, calendar, set_tz): async def test_all_day_event_returned_mid(
hass: HomeAssistant, calendar, set_tz
) -> None:
"""Test that the event lasting the whole day is returned, if it's in the middle of the local day.""" """Test that the event lasting the whole day is returned, if it's in the middle of the local day."""
config = dict(CALDAV_CONFIG) config = dict(CALDAV_CONFIG)
config["custom_calendars"] = [ config["custom_calendars"] = [
@ -665,7 +690,9 @@ async def test_all_day_event_returned_mid(hass, calendar, set_tz):
@pytest.mark.parametrize("set_tz", ["utc", "new_york", "baghdad"], indirect=True) @pytest.mark.parametrize("set_tz", ["utc", "new_york", "baghdad"], indirect=True)
async def test_all_day_event_returned_late(hass, calendar, set_tz): async def test_all_day_event_returned_late(
hass: HomeAssistant, calendar, set_tz
) -> None:
"""Test that the event lasting the whole day is returned, if it's late in the local day.""" """Test that the event lasting the whole day is returned, if it's late in the local day."""
config = dict(CALDAV_CONFIG) config = dict(CALDAV_CONFIG)
config["custom_calendars"] = [ config["custom_calendars"] = [
@ -682,7 +709,7 @@ async def test_all_day_event_returned_late(hass, calendar, set_tz):
@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @pytest.mark.parametrize("set_tz", ["utc"], indirect=True)
@patch("homeassistant.util.dt.now", return_value=_local_datetime(21, 45)) @patch("homeassistant.util.dt.now", return_value=_local_datetime(21, 45))
async def test_event_rrule(mock_now, hass, calendar, set_tz): async def test_event_rrule(mock_now, hass: HomeAssistant, calendar, set_tz) -> None:
"""Test that the future recurring event is returned.""" """Test that the future recurring event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -704,7 +731,9 @@ async def test_event_rrule(mock_now, hass, calendar, set_tz):
@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @pytest.mark.parametrize("set_tz", ["utc"], indirect=True)
@patch("homeassistant.util.dt.now", return_value=_local_datetime(22, 15)) @patch("homeassistant.util.dt.now", return_value=_local_datetime(22, 15))
async def test_event_rrule_ongoing(mock_now, hass, calendar, set_tz): async def test_event_rrule_ongoing(
mock_now, hass: HomeAssistant, calendar, set_tz
) -> None:
"""Test that the current recurring event is returned.""" """Test that the current recurring event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -726,7 +755,9 @@ async def test_event_rrule_ongoing(mock_now, hass, calendar, set_tz):
@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @pytest.mark.parametrize("set_tz", ["utc"], indirect=True)
@patch("homeassistant.util.dt.now", return_value=_local_datetime(22, 45)) @patch("homeassistant.util.dt.now", return_value=_local_datetime(22, 45))
async def test_event_rrule_duration(mock_now, hass, calendar, set_tz): async def test_event_rrule_duration(
mock_now, hass: HomeAssistant, calendar, set_tz
) -> None:
"""Test that the future recurring event is returned.""" """Test that the future recurring event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -748,7 +779,9 @@ async def test_event_rrule_duration(mock_now, hass, calendar, set_tz):
@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @pytest.mark.parametrize("set_tz", ["utc"], indirect=True)
@patch("homeassistant.util.dt.now", return_value=_local_datetime(23, 15)) @patch("homeassistant.util.dt.now", return_value=_local_datetime(23, 15))
async def test_event_rrule_duration_ongoing(mock_now, hass, calendar, set_tz): async def test_event_rrule_duration_ongoing(
mock_now, hass: HomeAssistant, calendar, set_tz
) -> None:
"""Test that the ongoing recurring event is returned.""" """Test that the ongoing recurring event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -770,7 +803,9 @@ async def test_event_rrule_duration_ongoing(mock_now, hass, calendar, set_tz):
@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @pytest.mark.parametrize("set_tz", ["utc"], indirect=True)
@patch("homeassistant.util.dt.now", return_value=_local_datetime(23, 37)) @patch("homeassistant.util.dt.now", return_value=_local_datetime(23, 37))
async def test_event_rrule_endless(mock_now, hass, calendar, set_tz): async def test_event_rrule_endless(
mock_now, hass: HomeAssistant, calendar, set_tz
) -> None:
"""Test that the endless recurring event is returned.""" """Test that the endless recurring event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -811,7 +846,7 @@ async def _event_rrule_all_day(hass, calendar, config, date_time):
@pytest.mark.parametrize("set_tz", ["utc", "new_york", "baghdad"], indirect=True) @pytest.mark.parametrize("set_tz", ["utc", "new_york", "baghdad"], indirect=True)
async def test_event_rrule_all_day_early(hass, calendar, set_tz): async def test_event_rrule_all_day_early(hass: HomeAssistant, calendar, set_tz) -> None:
"""Test that the recurring all day event is returned early in the local day, and not on the first occurrence.""" """Test that the recurring all day event is returned early in the local day, and not on the first occurrence."""
config = dict(CALDAV_CONFIG) config = dict(CALDAV_CONFIG)
config["custom_calendars"] = [ config["custom_calendars"] = [
@ -827,7 +862,7 @@ async def test_event_rrule_all_day_early(hass, calendar, set_tz):
@pytest.mark.parametrize("set_tz", ["utc", "new_york", "baghdad"], indirect=True) @pytest.mark.parametrize("set_tz", ["utc", "new_york", "baghdad"], indirect=True)
async def test_event_rrule_all_day_mid(hass, calendar, set_tz): async def test_event_rrule_all_day_mid(hass: HomeAssistant, calendar, set_tz) -> None:
"""Test that the recurring all day event is returned in the middle of the local day, and not on the first occurrence.""" """Test that the recurring all day event is returned in the middle of the local day, and not on the first occurrence."""
config = dict(CALDAV_CONFIG) config = dict(CALDAV_CONFIG)
config["custom_calendars"] = [ config["custom_calendars"] = [
@ -843,7 +878,7 @@ async def test_event_rrule_all_day_mid(hass, calendar, set_tz):
@pytest.mark.parametrize("set_tz", ["utc", "new_york", "baghdad"], indirect=True) @pytest.mark.parametrize("set_tz", ["utc", "new_york", "baghdad"], indirect=True)
async def test_event_rrule_all_day_late(hass, calendar, set_tz): async def test_event_rrule_all_day_late(hass: HomeAssistant, calendar, set_tz) -> None:
"""Test that the recurring all day event is returned late in the local day, and not on the first occurrence.""" """Test that the recurring all day event is returned late in the local day, and not on the first occurrence."""
config = dict(CALDAV_CONFIG) config = dict(CALDAV_CONFIG)
config["custom_calendars"] = [ config["custom_calendars"] = [
@ -863,7 +898,9 @@ async def test_event_rrule_all_day_late(hass, calendar, set_tz):
"homeassistant.util.dt.now", "homeassistant.util.dt.now",
return_value=dt.as_local(datetime.datetime(2015, 11, 27, 0, 15)), return_value=dt.as_local(datetime.datetime(2015, 11, 27, 0, 15)),
) )
async def test_event_rrule_hourly_on_first(mock_now, hass, calendar, set_tz): async def test_event_rrule_hourly_on_first(
mock_now, hass: HomeAssistant, calendar, set_tz
) -> None:
"""Test that the endless recurring event is returned.""" """Test that the endless recurring event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -888,7 +925,9 @@ async def test_event_rrule_hourly_on_first(mock_now, hass, calendar, set_tz):
"homeassistant.util.dt.now", "homeassistant.util.dt.now",
return_value=dt.as_local(datetime.datetime(2015, 11, 27, 11, 15)), return_value=dt.as_local(datetime.datetime(2015, 11, 27, 11, 15)),
) )
async def test_event_rrule_hourly_on_last(mock_now, hass, calendar, set_tz): async def test_event_rrule_hourly_on_last(
mock_now, hass: HomeAssistant, calendar, set_tz
) -> None:
"""Test that the endless recurring event is returned.""" """Test that the endless recurring event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -912,7 +951,9 @@ async def test_event_rrule_hourly_on_last(mock_now, hass, calendar, set_tz):
"homeassistant.util.dt.now", "homeassistant.util.dt.now",
return_value=dt.as_local(datetime.datetime(2015, 11, 27, 0, 45)), return_value=dt.as_local(datetime.datetime(2015, 11, 27, 0, 45)),
) )
async def test_event_rrule_hourly_off_first(mock_now, hass, calendar): async def test_event_rrule_hourly_off_first(
mock_now, hass: HomeAssistant, calendar
) -> None:
"""Test that the endless recurring event is returned.""" """Test that the endless recurring event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -926,7 +967,9 @@ async def test_event_rrule_hourly_off_first(mock_now, hass, calendar):
"homeassistant.util.dt.now", "homeassistant.util.dt.now",
return_value=dt.as_local(datetime.datetime(2015, 11, 27, 11, 45)), return_value=dt.as_local(datetime.datetime(2015, 11, 27, 11, 45)),
) )
async def test_event_rrule_hourly_off_last(mock_now, hass, calendar): async def test_event_rrule_hourly_off_last(
mock_now, hass: HomeAssistant, calendar
) -> None:
"""Test that the endless recurring event is returned.""" """Test that the endless recurring event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -940,7 +983,9 @@ async def test_event_rrule_hourly_off_last(mock_now, hass, calendar):
"homeassistant.util.dt.now", "homeassistant.util.dt.now",
return_value=dt.as_local(datetime.datetime(2015, 11, 27, 12, 15)), return_value=dt.as_local(datetime.datetime(2015, 11, 27, 12, 15)),
) )
async def test_event_rrule_hourly_ended(mock_now, hass, calendar): async def test_event_rrule_hourly_ended(
mock_now, hass: HomeAssistant, calendar
) -> None:
"""Test that the endless recurring event is returned.""" """Test that the endless recurring event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -950,7 +995,7 @@ async def test_event_rrule_hourly_ended(mock_now, hass, calendar):
assert state.state == STATE_OFF assert state.state == STATE_OFF
async def test_get_events(hass, calendar, get_api_events): async def test_get_events(hass: HomeAssistant, calendar, get_api_events) -> None:
"""Test that all events are returned on API.""" """Test that all events are returned on API."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -960,7 +1005,9 @@ async def test_get_events(hass, calendar, get_api_events):
assert calendar.call assert calendar.call
async def test_get_events_custom_calendars(hass, calendar, get_api_events): async def test_get_events_custom_calendars(
hass: HomeAssistant, calendar, get_api_events
) -> None:
"""Test that only searched events are returned on API.""" """Test that only searched events are returned on API."""
config = dict(CALDAV_CONFIG) config = dict(CALDAV_CONFIG)
config["custom_calendars"] = [ config["custom_calendars"] = [

View File

@ -15,7 +15,7 @@ from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
from tests.typing import ClientSessionGenerator from tests.typing import ClientSessionGenerator, WebSocketGenerator
async def test_events_http_api( async def test_events_http_api(
@ -158,7 +158,9 @@ async def test_calendars_http_api(
), ),
], ],
) )
async def test_unsupported_websocket(hass, hass_ws_client, payload, code): async def test_unsupported_websocket(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, payload, code
) -> None:
"""Test unsupported websocket command.""" """Test unsupported websocket command."""
await async_setup_component(hass, "calendar", {"calendar": {"platform": "demo"}}) await async_setup_component(hass, "calendar", {"calendar": {"platform": "demo"}})
await hass.async_block_till_done() await hass.async_block_till_done()

View File

@ -1,11 +1,11 @@
"""The tests for calendar recorder.""" """The tests for calendar recorder."""
from datetime import timedelta from datetime import timedelta
from homeassistant.components.recorder import Recorder
from homeassistant.components.recorder.db_schema import StateAttributes, States from homeassistant.components.recorder.db_schema import StateAttributes, States
from homeassistant.components.recorder.util import session_scope from homeassistant.components.recorder.util import session_scope
from homeassistant.const import ATTR_FRIENDLY_NAME from homeassistant.const import ATTR_FRIENDLY_NAME
from homeassistant.core import State from homeassistant.core import HomeAssistant, State
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
@ -13,7 +13,7 @@ from tests.common import async_fire_time_changed
from tests.components.recorder.common import async_wait_recording_done from tests.components.recorder.common import async_wait_recording_done
async def test_events_http_api(recorder_mock, hass): async def test_events_http_api(recorder_mock: Recorder, hass: HomeAssistant) -> None:
"""Test the calendar demo view.""" """Test the calendar demo view."""
await async_setup_component(hass, "calendar", {"calendar": {"platform": "demo"}}) await async_setup_component(hass, "calendar", {"calendar": {"platform": "demo"}})
await hass.async_block_till_done() await hass.async_block_till_done()

View File

@ -193,7 +193,7 @@ def mock_update_interval() -> Generator[None, None, None]:
yield yield
async def test_event_start_trigger(hass, calls, fake_schedule): async def test_event_start_trigger(hass: HomeAssistant, calls, fake_schedule) -> None:
"""Test the a calendar trigger based on start time.""" """Test the a calendar trigger based on start time."""
event_data = fake_schedule.create_event( event_data = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00"), start=datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00"),
@ -222,8 +222,8 @@ async def test_event_start_trigger(hass, calls, fake_schedule):
], ],
) )
async def test_event_start_trigger_with_offset( async def test_event_start_trigger_with_offset(
hass, calls, fake_schedule, offset_str, offset_delta hass: HomeAssistant, calls, fake_schedule, offset_str, offset_delta
): ) -> None:
"""Test the a calendar trigger based on start time with an offset.""" """Test the a calendar trigger based on start time with an offset."""
event_data = fake_schedule.create_event( event_data = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 12:00:00+00:00"), start=datetime.datetime.fromisoformat("2022-04-19 12:00:00+00:00"),
@ -250,7 +250,7 @@ async def test_event_start_trigger_with_offset(
] ]
async def test_event_end_trigger(hass, calls, fake_schedule): async def test_event_end_trigger(hass: HomeAssistant, calls, fake_schedule) -> None:
"""Test the a calendar trigger based on end time.""" """Test the a calendar trigger based on end time."""
event_data = fake_schedule.create_event( event_data = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00"), start=datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00"),
@ -285,8 +285,8 @@ async def test_event_end_trigger(hass, calls, fake_schedule):
], ],
) )
async def test_event_end_trigger_with_offset( async def test_event_end_trigger_with_offset(
hass, calls, fake_schedule, offset_str, offset_delta hass: HomeAssistant, calls, fake_schedule, offset_str, offset_delta
): ) -> None:
"""Test the a calendar trigger based on end time with an offset.""" """Test the a calendar trigger based on end time with an offset."""
event_data = fake_schedule.create_event( event_data = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 12:00:00+00:00"), start=datetime.datetime.fromisoformat("2022-04-19 12:00:00+00:00"),
@ -313,7 +313,9 @@ async def test_event_end_trigger_with_offset(
] ]
async def test_calendar_trigger_with_no_events(hass, calls, fake_schedule): async def test_calendar_trigger_with_no_events(
hass: HomeAssistant, calls, fake_schedule
) -> None:
"""Test a calendar trigger setup with no events.""" """Test a calendar trigger setup with no events."""
await create_automation(hass, EVENT_START) await create_automation(hass, EVENT_START)
@ -326,7 +328,7 @@ async def test_calendar_trigger_with_no_events(hass, calls, fake_schedule):
assert len(calls()) == 0 assert len(calls()) == 0
async def test_multiple_start_events(hass, calls, fake_schedule): async def test_multiple_start_events(hass: HomeAssistant, calls, fake_schedule) -> None:
"""Test that a trigger fires for multiple events.""" """Test that a trigger fires for multiple events."""
event_data1 = fake_schedule.create_event( event_data1 = fake_schedule.create_event(
@ -356,7 +358,7 @@ async def test_multiple_start_events(hass, calls, fake_schedule):
] ]
async def test_multiple_end_events(hass, calls, fake_schedule): async def test_multiple_end_events(hass: HomeAssistant, calls, fake_schedule) -> None:
"""Test that a trigger fires for multiple events.""" """Test that a trigger fires for multiple events."""
event_data1 = fake_schedule.create_event( event_data1 = fake_schedule.create_event(
@ -386,7 +388,9 @@ async def test_multiple_end_events(hass, calls, fake_schedule):
] ]
async def test_multiple_events_sharing_start_time(hass, calls, fake_schedule): async def test_multiple_events_sharing_start_time(
hass: HomeAssistant, calls, fake_schedule
) -> None:
"""Test that a trigger fires for every event sharing a start time.""" """Test that a trigger fires for every event sharing a start time."""
event_data1 = fake_schedule.create_event( event_data1 = fake_schedule.create_event(
@ -416,7 +420,7 @@ async def test_multiple_events_sharing_start_time(hass, calls, fake_schedule):
] ]
async def test_overlap_events(hass, calls, fake_schedule): async def test_overlap_events(hass: HomeAssistant, calls, fake_schedule) -> None:
"""Test that a trigger fires for events that overlap.""" """Test that a trigger fires for events that overlap."""
event_data1 = fake_schedule.create_event( event_data1 = fake_schedule.create_event(
@ -488,7 +492,7 @@ async def test_legacy_entity_type(
assert "is not a calendar entity" in caplog.text assert "is not a calendar entity" in caplog.text
async def test_update_next_event(hass, calls, fake_schedule): async def test_update_next_event(hass: HomeAssistant, calls, fake_schedule) -> None:
"""Test detection of a new event after initial trigger is setup.""" """Test detection of a new event after initial trigger is setup."""
event_data1 = fake_schedule.create_event( event_data1 = fake_schedule.create_event(
@ -527,7 +531,7 @@ async def test_update_next_event(hass, calls, fake_schedule):
] ]
async def test_update_missed(hass, calls, fake_schedule): async def test_update_missed(hass: HomeAssistant, calls, fake_schedule) -> None:
"""Test that new events are missed if they arrive outside the update interval.""" """Test that new events are missed if they arrive outside the update interval."""
event_data1 = fake_schedule.create_event( event_data1 = fake_schedule.create_event(
@ -614,8 +618,14 @@ async def test_update_missed(hass, calls, fake_schedule):
ids=["basic", "more-fields", "all-day"], ids=["basic", "more-fields", "all-day"],
) )
async def test_event_payload( async def test_event_payload(
hass, calls, fake_schedule, set_time_zone, create_data, fire_time, payload_data hass: HomeAssistant,
): calls,
fake_schedule,
set_time_zone,
create_data,
fire_time,
payload_data,
) -> None:
"""Test the fields in the calendar event payload are set.""" """Test the fields in the calendar event payload are set."""
fake_schedule.create_event(**create_data) fake_schedule.create_event(**create_data)
await create_automation(hass, EVENT_START) await create_automation(hass, EVENT_START)
@ -631,7 +641,9 @@ async def test_event_payload(
] ]
async def test_trigger_timestamp_window_edge(hass, calls, fake_schedule, freezer): async def test_trigger_timestamp_window_edge(
hass: HomeAssistant, calls, fake_schedule, freezer
) -> None:
"""Test that events in the edge of a scan are included.""" """Test that events in the edge of a scan are included."""
freezer.move_to("2022-04-19 11:00:00+00:00") freezer.move_to("2022-04-19 11:00:00+00:00")
# Exactly at a TEST_UPDATE_INTERVAL boundary the start time, # Exactly at a TEST_UPDATE_INTERVAL boundary the start time,

View File

@ -107,7 +107,7 @@ SCALE_TEST_EXPECTED = [
) )
def test_find_supported_scaling_factor( def test_find_supported_scaling_factor(
image_width, image_height, input_width, input_height, scaling_factor image_width, image_height, input_width, input_height, scaling_factor
): ) -> None:
"""Test we always get an image of at least the size we ask if its big enough.""" """Test we always get an image of at least the size we ask if its big enough."""
assert ( assert (

View File

@ -19,12 +19,15 @@ from homeassistant.const import (
EVENT_HOMEASSISTANT_STARTED, EVENT_HOMEASSISTANT_STARTED,
STATE_UNAVAILABLE, STATE_UNAVAILABLE,
) )
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from .common import EMPTY_8_6_JPEG, WEBRTC_ANSWER, mock_turbo_jpeg from .common import EMPTY_8_6_JPEG, WEBRTC_ANSWER, mock_turbo_jpeg
from tests.typing import ClientSessionGenerator, WebSocketGenerator
STREAM_SOURCE = "rtsp://127.0.0.1/stream" STREAM_SOURCE = "rtsp://127.0.0.1/stream"
HLS_STREAM_SOURCE = "http://127.0.0.1/example.m3u" HLS_STREAM_SOURCE = "http://127.0.0.1/example.m3u"
WEBRTC_OFFER = "v=0\r\n" WEBRTC_OFFER = "v=0\r\n"
@ -91,7 +94,7 @@ async def mock_rtsp_to_web_rtc_fixture(hass):
unsub() unsub()
async def test_get_image_from_camera(hass, image_mock_url): async def test_get_image_from_camera(hass: HomeAssistant, image_mock_url) -> None:
"""Grab an image from camera entity.""" """Grab an image from camera entity."""
with patch( with patch(
@ -105,7 +108,9 @@ async def test_get_image_from_camera(hass, image_mock_url):
assert image.content == b"Test" assert image.content == b"Test"
async def test_get_image_from_camera_with_width_height(hass, image_mock_url): async def test_get_image_from_camera_with_width_height(
hass: HomeAssistant, image_mock_url
) -> None:
"""Grab an image from camera entity with width and height.""" """Grab an image from camera entity with width and height."""
turbo_jpeg = mock_turbo_jpeg( turbo_jpeg = mock_turbo_jpeg(
@ -127,7 +132,9 @@ async def test_get_image_from_camera_with_width_height(hass, image_mock_url):
assert image.content == b"Test" assert image.content == b"Test"
async def test_get_image_from_camera_with_width_height_scaled(hass, image_mock_url): async def test_get_image_from_camera_with_width_height_scaled(
hass: HomeAssistant, image_mock_url
) -> None:
"""Grab an image from camera entity with width and height and scale it.""" """Grab an image from camera entity with width and height and scale it."""
turbo_jpeg = mock_turbo_jpeg( turbo_jpeg = mock_turbo_jpeg(
@ -150,7 +157,9 @@ async def test_get_image_from_camera_with_width_height_scaled(hass, image_mock_u
assert image.content == EMPTY_8_6_JPEG assert image.content == EMPTY_8_6_JPEG
async def test_get_image_from_camera_not_jpeg(hass, image_mock_url): async def test_get_image_from_camera_not_jpeg(
hass: HomeAssistant, image_mock_url
) -> None:
"""Grab an image from camera entity that we cannot scale.""" """Grab an image from camera entity that we cannot scale."""
turbo_jpeg = mock_turbo_jpeg( turbo_jpeg = mock_turbo_jpeg(
@ -173,7 +182,9 @@ async def test_get_image_from_camera_not_jpeg(hass, image_mock_url):
assert image.content == b"png" assert image.content == b"png"
async def test_get_stream_source_from_camera(hass, mock_camera, mock_stream_source): async def test_get_stream_source_from_camera(
hass: HomeAssistant, mock_camera, mock_stream_source
) -> None:
"""Fetch stream source from camera entity.""" """Fetch stream source from camera entity."""
stream_source = await camera.async_get_stream_source(hass, "camera.demo_camera") stream_source = await camera.async_get_stream_source(hass, "camera.demo_camera")
@ -182,7 +193,9 @@ async def test_get_stream_source_from_camera(hass, mock_camera, mock_stream_sour
assert stream_source == STREAM_SOURCE assert stream_source == STREAM_SOURCE
async def test_get_image_without_exists_camera(hass, image_mock_url): async def test_get_image_without_exists_camera(
hass: HomeAssistant, image_mock_url
) -> None:
"""Try to get image without exists camera.""" """Try to get image without exists camera."""
with patch( with patch(
"homeassistant.helpers.entity_component.EntityComponent.get_entity", "homeassistant.helpers.entity_component.EntityComponent.get_entity",
@ -191,7 +204,7 @@ async def test_get_image_without_exists_camera(hass, image_mock_url):
await camera.async_get_image(hass, "camera.demo_camera") await camera.async_get_image(hass, "camera.demo_camera")
async def test_get_image_with_timeout(hass, image_mock_url): async def test_get_image_with_timeout(hass: HomeAssistant, image_mock_url) -> None:
"""Try to get image with timeout.""" """Try to get image with timeout."""
with patch( with patch(
"homeassistant.components.demo.camera.DemoCamera.async_camera_image", "homeassistant.components.demo.camera.DemoCamera.async_camera_image",
@ -200,7 +213,7 @@ async def test_get_image_with_timeout(hass, image_mock_url):
await camera.async_get_image(hass, "camera.demo_camera") await camera.async_get_image(hass, "camera.demo_camera")
async def test_get_image_fails(hass, image_mock_url): async def test_get_image_fails(hass: HomeAssistant, image_mock_url) -> None:
"""Try to get image with timeout.""" """Try to get image with timeout."""
with patch( with patch(
"homeassistant.components.demo.camera.DemoCamera.async_camera_image", "homeassistant.components.demo.camera.DemoCamera.async_camera_image",
@ -209,7 +222,7 @@ async def test_get_image_fails(hass, image_mock_url):
await camera.async_get_image(hass, "camera.demo_camera") await camera.async_get_image(hass, "camera.demo_camera")
async def test_snapshot_service(hass, mock_camera): async def test_snapshot_service(hass: HomeAssistant, mock_camera) -> None:
"""Test snapshot service.""" """Test snapshot service."""
mopen = mock_open() mopen = mock_open()
@ -233,8 +246,8 @@ async def test_snapshot_service(hass, mock_camera):
async def test_websocket_stream_no_source( async def test_websocket_stream_no_source(
hass, hass_ws_client, mock_camera, mock_stream hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_camera, mock_stream
): ) -> None:
"""Test camera/stream websocket command with camera with no source.""" """Test camera/stream websocket command with camera with no source."""
await async_setup_component(hass, "camera", {}) await async_setup_component(hass, "camera", {})
@ -251,7 +264,9 @@ async def test_websocket_stream_no_source(
assert not msg["success"] assert not msg["success"]
async def test_websocket_camera_stream(hass, hass_ws_client, mock_camera, mock_stream): async def test_websocket_camera_stream(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_camera, mock_stream
) -> None:
"""Test camera/stream websocket command.""" """Test camera/stream websocket command."""
await async_setup_component(hass, "camera", {}) await async_setup_component(hass, "camera", {})
@ -277,7 +292,9 @@ async def test_websocket_camera_stream(hass, hass_ws_client, mock_camera, mock_s
assert msg["result"]["url"][-13:] == "playlist.m3u8" assert msg["result"]["url"][-13:] == "playlist.m3u8"
async def test_websocket_get_prefs(hass, hass_ws_client, mock_camera): async def test_websocket_get_prefs(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_camera
) -> None:
"""Test get camera preferences websocket command.""" """Test get camera preferences websocket command."""
await async_setup_component(hass, "camera", {}) await async_setup_component(hass, "camera", {})
@ -292,7 +309,9 @@ async def test_websocket_get_prefs(hass, hass_ws_client, mock_camera):
assert msg["success"] assert msg["success"]
async def test_websocket_update_preload_prefs(hass, hass_ws_client, mock_camera): async def test_websocket_update_preload_prefs(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_camera
) -> None:
"""Test updating camera preferences.""" """Test updating camera preferences."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
@ -327,7 +346,9 @@ async def test_websocket_update_preload_prefs(hass, hass_ws_client, mock_camera)
assert msg["result"][PREF_PRELOAD_STREAM] is True assert msg["result"][PREF_PRELOAD_STREAM] is True
async def test_websocket_update_orientation_prefs(hass, hass_ws_client, mock_camera): async def test_websocket_update_orientation_prefs(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_camera
) -> None:
"""Test updating camera preferences.""" """Test updating camera preferences."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
@ -378,7 +399,9 @@ async def test_websocket_update_orientation_prefs(hass, hass_ws_client, mock_cam
assert msg["result"]["orientation"] == camera.Orientation.ROTATE_180 assert msg["result"]["orientation"] == camera.Orientation.ROTATE_180
async def test_play_stream_service_no_source(hass, mock_camera, mock_stream): async def test_play_stream_service_no_source(
hass: HomeAssistant, mock_camera, mock_stream
) -> None:
"""Test camera play_stream service.""" """Test camera play_stream service."""
data = { data = {
ATTR_ENTITY_ID: "camera.demo_camera", ATTR_ENTITY_ID: "camera.demo_camera",
@ -391,7 +414,9 @@ async def test_play_stream_service_no_source(hass, mock_camera, mock_stream):
) )
async def test_handle_play_stream_service(hass, mock_camera, mock_stream): async def test_handle_play_stream_service(
hass: HomeAssistant, mock_camera, mock_stream
) -> None:
"""Test camera play_stream service.""" """Test camera play_stream service."""
await async_process_ha_core_config( await async_process_ha_core_config(
hass, hass,
@ -419,7 +444,7 @@ async def test_handle_play_stream_service(hass, mock_camera, mock_stream):
assert mock_request_stream.called assert mock_request_stream.called
async def test_no_preload_stream(hass, mock_stream): async def test_no_preload_stream(hass: HomeAssistant, mock_stream) -> None:
"""Test camera preload preference.""" """Test camera preload preference."""
demo_settings = camera.DynamicStreamSettings() demo_settings = camera.DynamicStreamSettings()
with patch( with patch(
@ -438,7 +463,7 @@ async def test_no_preload_stream(hass, mock_stream):
assert not mock_request_stream.called assert not mock_request_stream.called
async def test_preload_stream(hass, mock_stream): async def test_preload_stream(hass: HomeAssistant, mock_stream) -> None:
"""Test camera preload preference.""" """Test camera preload preference."""
demo_settings = camera.DynamicStreamSettings(preload_stream=True) demo_settings = camera.DynamicStreamSettings(preload_stream=True)
with patch( with patch(
@ -460,7 +485,7 @@ async def test_preload_stream(hass, mock_stream):
assert mock_create_stream.called assert mock_create_stream.called
async def test_record_service_invalid_path(hass, mock_camera): async def test_record_service_invalid_path(hass: HomeAssistant, mock_camera) -> None:
"""Test record service with invalid path.""" """Test record service with invalid path."""
with patch.object( with patch.object(
hass.config, "is_allowed_path", return_value=False hass.config, "is_allowed_path", return_value=False
@ -477,7 +502,7 @@ async def test_record_service_invalid_path(hass, mock_camera):
) )
async def test_record_service(hass, mock_camera, mock_stream): async def test_record_service(hass: HomeAssistant, mock_camera, mock_stream) -> None:
"""Test record service.""" """Test record service."""
with patch( with patch(
"homeassistant.components.demo.camera.DemoCamera.stream_source", "homeassistant.components.demo.camera.DemoCamera.stream_source",
@ -498,7 +523,9 @@ async def test_record_service(hass, mock_camera, mock_stream):
assert mock_record.called assert mock_record.called
async def test_camera_proxy_stream(hass, mock_camera, hass_client): async def test_camera_proxy_stream(
hass: HomeAssistant, mock_camera, hass_client: ClientSessionGenerator
) -> None:
"""Test record service.""" """Test record service."""
client = await hass_client() client = await hass_client()
@ -517,10 +544,10 @@ async def test_camera_proxy_stream(hass, mock_camera, hass_client):
async def test_websocket_web_rtc_offer( async def test_websocket_web_rtc_offer(
hass, hass: HomeAssistant,
hass_ws_client, hass_ws_client: WebSocketGenerator,
mock_camera_web_rtc, mock_camera_web_rtc,
): ) -> None:
"""Test initiating a WebRTC stream with offer and answer.""" """Test initiating a WebRTC stream with offer and answer."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
await client.send_json( await client.send_json(
@ -540,10 +567,10 @@ async def test_websocket_web_rtc_offer(
async def test_websocket_web_rtc_offer_invalid_entity( async def test_websocket_web_rtc_offer_invalid_entity(
hass, hass: HomeAssistant,
hass_ws_client, hass_ws_client: WebSocketGenerator,
mock_camera_web_rtc, mock_camera_web_rtc,
): ) -> None:
"""Test WebRTC with a camera entity that does not exist.""" """Test WebRTC with a camera entity that does not exist."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
await client.send_json( await client.send_json(
@ -562,10 +589,10 @@ async def test_websocket_web_rtc_offer_invalid_entity(
async def test_websocket_web_rtc_offer_missing_offer( async def test_websocket_web_rtc_offer_missing_offer(
hass, hass: HomeAssistant,
hass_ws_client, hass_ws_client: WebSocketGenerator,
mock_camera_web_rtc, mock_camera_web_rtc,
): ) -> None:
"""Test WebRTC stream with missing required fields.""" """Test WebRTC stream with missing required fields."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
await client.send_json( await client.send_json(
@ -584,10 +611,10 @@ async def test_websocket_web_rtc_offer_missing_offer(
async def test_websocket_web_rtc_offer_failure( async def test_websocket_web_rtc_offer_failure(
hass, hass: HomeAssistant,
hass_ws_client, hass_ws_client: WebSocketGenerator,
mock_camera_web_rtc, mock_camera_web_rtc,
): ) -> None:
"""Test WebRTC stream that fails handling the offer.""" """Test WebRTC stream that fails handling the offer."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
@ -613,10 +640,10 @@ async def test_websocket_web_rtc_offer_failure(
async def test_websocket_web_rtc_offer_timeout( async def test_websocket_web_rtc_offer_timeout(
hass, hass: HomeAssistant,
hass_ws_client, hass_ws_client: WebSocketGenerator,
mock_camera_web_rtc, mock_camera_web_rtc,
): ) -> None:
"""Test WebRTC stream with timeout handling the offer.""" """Test WebRTC stream with timeout handling the offer."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
@ -642,10 +669,10 @@ async def test_websocket_web_rtc_offer_timeout(
async def test_websocket_web_rtc_offer_invalid_stream_type( async def test_websocket_web_rtc_offer_invalid_stream_type(
hass, hass: HomeAssistant,
hass_ws_client, hass_ws_client: WebSocketGenerator,
mock_camera, mock_camera,
): ) -> None:
"""Test WebRTC initiating for a camera with a different stream_type.""" """Test WebRTC initiating for a camera with a different stream_type."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
await client.send_json( await client.send_json(
@ -664,14 +691,18 @@ async def test_websocket_web_rtc_offer_invalid_stream_type(
assert response["error"]["code"] == "web_rtc_offer_failed" assert response["error"]["code"] == "web_rtc_offer_failed"
async def test_state_streaming(hass, hass_ws_client, mock_camera): async def test_state_streaming(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_camera
) -> None:
"""Camera state.""" """Camera state."""
demo_camera = hass.states.get("camera.demo_camera") demo_camera = hass.states.get("camera.demo_camera")
assert demo_camera is not None assert demo_camera is not None
assert demo_camera.state == camera.STATE_STREAMING assert demo_camera.state == camera.STATE_STREAMING
async def test_stream_unavailable(hass, hass_ws_client, mock_camera, mock_stream): async def test_stream_unavailable(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_camera, mock_stream
) -> None:
"""Camera state.""" """Camera state."""
await async_setup_component(hass, "camera", {}) await async_setup_component(hass, "camera", {})
@ -718,12 +749,12 @@ async def test_stream_unavailable(hass, hass_ws_client, mock_camera, mock_stream
async def test_rtsp_to_web_rtc_offer( async def test_rtsp_to_web_rtc_offer(
hass, hass: HomeAssistant,
hass_ws_client, hass_ws_client: WebSocketGenerator,
mock_camera, mock_camera,
mock_stream_source, mock_stream_source,
mock_rtsp_to_web_rtc, mock_rtsp_to_web_rtc,
): ) -> None:
"""Test creating a web_rtc offer from an rstp provider.""" """Test creating a web_rtc offer from an rstp provider."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
await client.send_json( await client.send_json(
@ -771,11 +802,11 @@ async def test_unsupported_rtsp_to_web_rtc_stream_type(
async def test_rtsp_to_web_rtc_provider_unregistered( async def test_rtsp_to_web_rtc_provider_unregistered(
hass, hass: HomeAssistant,
hass_ws_client, hass_ws_client: WebSocketGenerator,
mock_camera, mock_camera,
mock_stream_source, mock_stream_source,
): ) -> None:
"""Test creating a web_rtc offer from an rstp provider.""" """Test creating a web_rtc offer from an rstp provider."""
mock_provider = Mock(side_effect=provide_web_rtc_answer) mock_provider = Mock(side_effect=provide_web_rtc_answer)
unsub = camera.async_register_rtsp_to_web_rtc_provider( unsub = camera.async_register_rtsp_to_web_rtc_provider(
@ -822,11 +853,11 @@ async def test_rtsp_to_web_rtc_provider_unregistered(
async def test_rtsp_to_web_rtc_offer_not_accepted( async def test_rtsp_to_web_rtc_offer_not_accepted(
hass, hass: HomeAssistant,
hass_ws_client, hass_ws_client: WebSocketGenerator,
mock_camera, mock_camera,
mock_stream_source, mock_stream_source,
): ) -> None:
"""Test a provider that can't satisfy the rtsp to webrtc offer.""" """Test a provider that can't satisfy the rtsp to webrtc offer."""
async def provide_none(stream_source: str, offer: str) -> str: async def provide_none(stream_source: str, offer: str) -> str:

View File

@ -6,6 +6,7 @@ import pytest
from homeassistant.components import media_source from homeassistant.components import media_source
from homeassistant.components.camera.const import StreamType from homeassistant.components.camera.const import StreamType
from homeassistant.components.stream import FORMAT_CONTENT_TYPE from homeassistant.components.stream import FORMAT_CONTENT_TYPE
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -15,7 +16,7 @@ async def setup_media_source(hass):
assert await async_setup_component(hass, "media_source", {}) assert await async_setup_component(hass, "media_source", {})
async def test_browsing_hls(hass, mock_camera_hls): async def test_browsing_hls(hass: HomeAssistant, mock_camera_hls) -> None:
"""Test browsing camera media source.""" """Test browsing camera media source."""
item = await media_source.async_browse_media(hass, "media-source://camera") item = await media_source.async_browse_media(hass, "media-source://camera")
assert item is not None assert item is not None
@ -32,7 +33,7 @@ async def test_browsing_hls(hass, mock_camera_hls):
assert item.children[0].media_content_type == FORMAT_CONTENT_TYPE["hls"] assert item.children[0].media_content_type == FORMAT_CONTENT_TYPE["hls"]
async def test_browsing_mjpeg(hass, mock_camera): async def test_browsing_mjpeg(hass: HomeAssistant, mock_camera) -> None:
"""Test browsing camera media source.""" """Test browsing camera media source."""
item = await media_source.async_browse_media(hass, "media-source://camera") item = await media_source.async_browse_media(hass, "media-source://camera")
assert item is not None assert item is not None
@ -43,7 +44,9 @@ async def test_browsing_mjpeg(hass, mock_camera):
assert item.children[1].media_content_type == "image/png" assert item.children[1].media_content_type == "image/png"
async def test_browsing_filter_web_rtc(hass, mock_camera_web_rtc): async def test_browsing_filter_web_rtc(
hass: HomeAssistant, mock_camera_web_rtc
) -> None:
"""Test browsing camera media source hides non-HLS cameras.""" """Test browsing camera media source hides non-HLS cameras."""
item = await media_source.async_browse_media(hass, "media-source://camera") item = await media_source.async_browse_media(hass, "media-source://camera")
assert item is not None assert item is not None
@ -52,7 +55,7 @@ async def test_browsing_filter_web_rtc(hass, mock_camera_web_rtc):
assert item.not_shown == 2 assert item.not_shown == 2
async def test_resolving(hass, mock_camera_hls): async def test_resolving(hass: HomeAssistant, mock_camera_hls) -> None:
"""Test resolving.""" """Test resolving."""
# Adding stream enables HLS camera # Adding stream enables HLS camera
hass.config.components.add("stream") hass.config.components.add("stream")
@ -69,7 +72,7 @@ async def test_resolving(hass, mock_camera_hls):
assert item.mime_type == FORMAT_CONTENT_TYPE["hls"] assert item.mime_type == FORMAT_CONTENT_TYPE["hls"]
async def test_resolving_errors(hass, mock_camera_hls): async def test_resolving_errors(hass: HomeAssistant, mock_camera_hls) -> None:
"""Test resolving.""" """Test resolving."""
with pytest.raises(media_source.Unresolvable) as exc_info: with pytest.raises(media_source.Unresolvable) as exc_info:

View File

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

View File

@ -16,13 +16,17 @@ from homeassistant.const import (
STATE_ALARM_DISARMED, STATE_ALARM_DISARMED,
STATE_UNKNOWN, STATE_UNKNOWN,
) )
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.entity_component import async_update_entity from homeassistant.helpers.entity_component import async_update_entity
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from . import mock_device, mock_location, mock_mode from . import mock_device, mock_location, mock_mode
async def test_alarm_control_panel(hass, canary, entity_registry) -> None: async def test_alarm_control_panel(
hass: HomeAssistant, canary, entity_registry: er.EntityRegistry
) -> None:
"""Test the creation and values of the alarm_control_panel for Canary.""" """Test the creation and values of the alarm_control_panel for Canary."""
online_device_at_home = mock_device(20, "Dining Room", True, "Canary Pro") online_device_at_home = mock_device(20, "Dining Room", True, "Canary Pro")
@ -104,7 +108,7 @@ async def test_alarm_control_panel(hass, canary, entity_registry) -> None:
assert state.state == STATE_ALARM_ARMED_NIGHT assert state.state == STATE_ALARM_ARMED_NIGHT
async def test_alarm_control_panel_services(hass, canary) -> None: async def test_alarm_control_panel_services(hass: HomeAssistant, canary) -> None:
"""Test the services of the alarm_control_panel for Canary.""" """Test the services of the alarm_control_panel for Canary."""
online_device_at_home = mock_device(20, "Dining Room", True, "Canary Pro") online_device_at_home = mock_device(20, "Dining Room", True, "Canary Pro")

View File

@ -11,12 +11,13 @@ from homeassistant.components.canary.const import (
) )
from homeassistant.config_entries import SOURCE_USER from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_TIMEOUT from homeassistant.const import CONF_TIMEOUT
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType from homeassistant.data_entry_flow import FlowResultType
from . import USER_INPUT, _patch_async_setup, _patch_async_setup_entry, init_integration from . import USER_INPUT, _patch_async_setup, _patch_async_setup_entry, init_integration
async def test_user_form(hass, canary_config_flow): async def test_user_form(hass: HomeAssistant, canary_config_flow) -> None:
"""Test we get the user initiated form.""" """Test we get the user initiated form."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
@ -40,7 +41,9 @@ async def test_user_form(hass, canary_config_flow):
assert len(mock_setup_entry.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
async def test_user_form_cannot_connect(hass, canary_config_flow): async def test_user_form_cannot_connect(
hass: HomeAssistant, canary_config_flow
) -> None:
"""Test we handle errors that should trigger the cannot connect error.""" """Test we handle errors that should trigger the cannot connect error."""
canary_config_flow.side_effect = HTTPError() canary_config_flow.side_effect = HTTPError()
@ -67,7 +70,9 @@ async def test_user_form_cannot_connect(hass, canary_config_flow):
assert result["errors"] == {"base": "cannot_connect"} assert result["errors"] == {"base": "cannot_connect"}
async def test_user_form_unexpected_exception(hass, canary_config_flow): async def test_user_form_unexpected_exception(
hass: HomeAssistant, canary_config_flow
) -> None:
"""Test we handle unexpected exception.""" """Test we handle unexpected exception."""
canary_config_flow.side_effect = Exception() canary_config_flow.side_effect = Exception()
@ -84,7 +89,9 @@ async def test_user_form_unexpected_exception(hass, canary_config_flow):
assert result["reason"] == "unknown" assert result["reason"] == "unknown"
async def test_user_form_single_instance_allowed(hass, canary_config_flow): async def test_user_form_single_instance_allowed(
hass: HomeAssistant, canary_config_flow
) -> None:
"""Test that configuring more than one instance is rejected.""" """Test that configuring more than one instance is rejected."""
await init_integration(hass, skip_entry_setup=True) await init_integration(hass, skip_entry_setup=True)
@ -97,7 +104,7 @@ async def test_user_form_single_instance_allowed(hass, canary_config_flow):
assert result["reason"] == "single_instance_allowed" assert result["reason"] == "single_instance_allowed"
async def test_options_flow(hass, canary): async def test_options_flow(hass: HomeAssistant, canary) -> None:
"""Test updating options.""" """Test updating options."""
with patch("homeassistant.components.canary.PLATFORMS", []): with patch("homeassistant.components.canary.PLATFORMS", []):
entry = await init_integration(hass) entry = await init_integration(hass)

View File

@ -7,12 +7,13 @@ from homeassistant.components.camera import DOMAIN as CAMERA_DOMAIN
from homeassistant.components.canary.const import CONF_FFMPEG_ARGUMENTS, DOMAIN from homeassistant.components.canary.const import CONF_FFMPEG_ARGUMENTS, DOMAIN
from homeassistant.config_entries import ConfigEntryState from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from . import YAML_CONFIG, init_integration from . import YAML_CONFIG, init_integration
async def test_import_from_yaml(hass, canary) -> None: async def test_import_from_yaml(hass: HomeAssistant, canary) -> None:
"""Test import from YAML.""" """Test import from YAML."""
with patch( with patch(
"homeassistant.components.canary.async_setup_entry", "homeassistant.components.canary.async_setup_entry",
@ -29,7 +30,7 @@ async def test_import_from_yaml(hass, canary) -> None:
assert entries[0].data[CONF_TIMEOUT] == 5 assert entries[0].data[CONF_TIMEOUT] == 5
async def test_import_from_yaml_ffmpeg(hass, canary) -> None: async def test_import_from_yaml_ffmpeg(hass: HomeAssistant, canary) -> None:
"""Test import from YAML with ffmpeg arguments.""" """Test import from YAML with ffmpeg arguments."""
with patch( with patch(
"homeassistant.components.canary.async_setup_entry", "homeassistant.components.canary.async_setup_entry",
@ -54,7 +55,7 @@ async def test_import_from_yaml_ffmpeg(hass, canary) -> None:
assert entries[0].data.get(CONF_FFMPEG_ARGUMENTS) == "-v" assert entries[0].data.get(CONF_FFMPEG_ARGUMENTS) == "-v"
async def test_unload_entry(hass, canary): async def test_unload_entry(hass: HomeAssistant, canary) -> None:
"""Test successful unload of entry.""" """Test successful unload of entry."""
entry = await init_integration(hass) entry = await init_integration(hass)
@ -69,7 +70,7 @@ async def test_unload_entry(hass, canary):
assert not hass.data.get(DOMAIN) assert not hass.data.get(DOMAIN)
async def test_async_setup_raises_entry_not_ready(hass, canary): async def test_async_setup_raises_entry_not_ready(hass: HomeAssistant, canary) -> None:
"""Test that it throws ConfigEntryNotReady when exception occurs during setup.""" """Test that it throws ConfigEntryNotReady when exception occurs during setup."""
canary.side_effect = ConnectTimeout() canary.side_effect = ConnectTimeout()

View File

@ -16,6 +16,8 @@ from homeassistant.const import (
SIGNAL_STRENGTH_DECIBELS_MILLIWATT, SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
UnitOfTemperature, UnitOfTemperature,
) )
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.entity_component import async_update_entity from homeassistant.helpers.entity_component import async_update_entity
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from homeassistant.util.dt import utcnow from homeassistant.util.dt import utcnow
@ -25,7 +27,12 @@ from . import mock_device, mock_location, mock_reading
from tests.common import async_fire_time_changed from tests.common import async_fire_time_changed
async def test_sensors_pro(hass, canary, device_registry, entity_registry) -> None: async def test_sensors_pro(
hass: HomeAssistant,
canary,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test the creation and values of the sensors for Canary Pro.""" """Test the creation and values of the sensors for Canary Pro."""
online_device_at_home = mock_device(20, "Dining Room", True, "Canary Pro") online_device_at_home = mock_device(20, "Dining Room", True, "Canary Pro")
@ -88,7 +95,7 @@ async def test_sensors_pro(hass, canary, device_registry, entity_registry) -> No
assert device.model == "Canary Pro" assert device.model == "Canary Pro"
async def test_sensors_attributes_pro(hass, canary) -> None: async def test_sensors_attributes_pro(hass: HomeAssistant, canary) -> None:
"""Test the creation and values of the sensors attributes for Canary Pro.""" """Test the creation and values of the sensors attributes for Canary Pro."""
online_device_at_home = mock_device(20, "Dining Room", True, "Canary Pro") online_device_at_home = mock_device(20, "Dining Room", True, "Canary Pro")
@ -148,7 +155,12 @@ async def test_sensors_attributes_pro(hass, canary) -> None:
assert state3.attributes[ATTR_AIR_QUALITY] == STATE_AIR_QUALITY_NORMAL assert state3.attributes[ATTR_AIR_QUALITY] == STATE_AIR_QUALITY_NORMAL
async def test_sensors_flex(hass, canary, device_registry, entity_registry) -> None: async def test_sensors_flex(
hass: HomeAssistant,
canary,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test the creation and values of the sensors for Canary Flex.""" """Test the creation and values of the sensors for Canary Flex."""
online_device_at_home = mock_device(20, "Dining Room", True, "Canary Flex") online_device_at_home = mock_device(20, "Dining Room", True, "Canary Flex")

View File

@ -44,7 +44,7 @@ async def test_creating_entry_sets_up_media_player(hass: HomeAssistant) -> None:
config_entries.SOURCE_ZEROCONF, config_entries.SOURCE_ZEROCONF,
], ],
) )
async def test_single_instance(hass, source): async def test_single_instance(hass: HomeAssistant, source) -> None:
"""Test we only allow a single config flow.""" """Test we only allow a single config flow."""
MockConfigEntry(domain="cast").add_to_hass(hass) MockConfigEntry(domain="cast").add_to_hass(hass)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -173,7 +173,7 @@ def get_suggested(schema, key):
), ),
], ],
) )
async def test_option_flow(hass, parameter_data): async def test_option_flow(hass: HomeAssistant, parameter_data) -> None:
"""Test config flow options.""" """Test config flow options."""
basic_parameters = ["known_hosts"] basic_parameters = ["known_hosts"]
advanced_parameters = ["ignore_cec", "uuid"] advanced_parameters = ["ignore_cec", "uuid"]
@ -267,7 +267,7 @@ async def test_option_flow(hass, parameter_data):
assert dict(config_entry.data) == expected_data assert dict(config_entry.data) == expected_data
async def test_known_hosts(hass, castbrowser_mock): async def test_known_hosts(hass: HomeAssistant, castbrowser_mock) -> None:
"""Test known hosts is passed to pychromecasts.""" """Test known hosts is passed to pychromecasts."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
"cast", context={"source": config_entries.SOURCE_USER} "cast", context={"source": config_entries.SOURCE_USER}

View File

@ -10,8 +10,10 @@ from homeassistant.components.cast.helpers import (
PlaylistSupported, PlaylistSupported,
parse_playlist, parse_playlist,
) )
from homeassistant.core import HomeAssistant
from tests.common import load_fixture from tests.common import load_fixture
from tests.test_util.aiohttp import AiohttpClientMocker
@pytest.mark.parametrize( @pytest.mark.parametrize(
@ -34,7 +36,9 @@ from tests.common import load_fixture
), ),
), ),
) )
async def test_hls_playlist_supported(hass, aioclient_mock, url, fixture, content_type): async def test_hls_playlist_supported(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, url, fixture, content_type
) -> None:
"""Test playlist parsing of HLS playlist.""" """Test playlist parsing of HLS playlist."""
headers = {"content-type": content_type} headers = {"content-type": content_type}
aioclient_mock.get(url, text=load_fixture(fixture, "cast"), headers=headers) aioclient_mock.get(url, text=load_fixture(fixture, "cast"), headers=headers)
@ -96,8 +100,13 @@ async def test_hls_playlist_supported(hass, aioclient_mock, url, fixture, conten
), ),
) )
async def test_parse_playlist( async def test_parse_playlist(
hass, aioclient_mock, url, fixture, content_type, expected_playlist hass: HomeAssistant,
): aioclient_mock: AiohttpClientMocker,
url,
fixture,
content_type,
expected_playlist,
) -> None:
"""Test playlist parsing of HLS playlist.""" """Test playlist parsing of HLS playlist."""
headers = {"content-type": content_type} headers = {"content-type": content_type}
aioclient_mock.get(url, text=load_fixture(fixture, "cast"), headers=headers) aioclient_mock.get(url, text=load_fixture(fixture, "cast"), headers=headers)
@ -120,7 +129,9 @@ async def test_parse_playlist(
("https://sverigesradio.se/209-hi-mp3.m3u", "empty.m3u"), ("https://sverigesradio.se/209-hi-mp3.m3u", "empty.m3u"),
), ),
) )
async def test_parse_bad_playlist(hass, aioclient_mock, url, fixture): async def test_parse_bad_playlist(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, url, fixture
) -> None:
"""Test playlist parsing of HLS playlist.""" """Test playlist parsing of HLS playlist."""
aioclient_mock.get(url, text=load_fixture(fixture, "cast")) aioclient_mock.get(url, text=load_fixture(fixture, "cast"))
with pytest.raises(PlaylistError): with pytest.raises(PlaylistError):
@ -134,7 +145,9 @@ async def test_parse_bad_playlist(hass, aioclient_mock, url, fixture):
("http://sverigesradio.se/164-hi-aac.pls", client_exceptions.ClientError), ("http://sverigesradio.se/164-hi-aac.pls", client_exceptions.ClientError),
), ),
) )
async def test_parse_http_error(hass, aioclient_mock, url, exc): async def test_parse_http_error(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, url, exc
) -> None:
"""Test playlist parsing of HLS playlist when aioclient raises.""" """Test playlist parsing of HLS playlist when aioclient raises."""
aioclient_mock.get(url, text="", exc=exc) aioclient_mock.get(url, text="", exc=exc)
with pytest.raises(PlaylistError): with pytest.raises(PlaylistError):

View File

@ -1,17 +1,17 @@
"""Test Home Assistant Cast.""" """Test Home Assistant Cast."""
from unittest.mock import patch from unittest.mock import patch
import pytest import pytest
from homeassistant.components.cast import home_assistant_cast from homeassistant.components.cast import home_assistant_cast
from homeassistant.config import async_process_ha_core_config from homeassistant.config import async_process_ha_core_config
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from tests.common import MockConfigEntry, async_mock_signal from tests.common import MockConfigEntry, async_mock_signal
async def test_service_show_view(hass, mock_zeroconf): async def test_service_show_view(hass: HomeAssistant, mock_zeroconf: None) -> None:
"""Test showing a view.""" """Test showing a view."""
await home_assistant_cast.async_setup_ha_cast(hass, MockConfigEntry()) await home_assistant_cast.async_setup_ha_cast(hass, MockConfigEntry())
calls = async_mock_signal(hass, home_assistant_cast.SIGNAL_HASS_CAST_SHOW_VIEW) calls = async_mock_signal(hass, home_assistant_cast.SIGNAL_HASS_CAST_SHOW_VIEW)
@ -48,7 +48,9 @@ async def test_service_show_view(hass, mock_zeroconf):
assert url_path is None assert url_path is None
async def test_service_show_view_dashboard(hass, mock_zeroconf): async def test_service_show_view_dashboard(
hass: HomeAssistant, mock_zeroconf: None
) -> None:
"""Test casting a specific dashboard.""" """Test casting a specific dashboard."""
await async_process_ha_core_config( await async_process_ha_core_config(
hass, hass,
@ -75,7 +77,7 @@ async def test_service_show_view_dashboard(hass, mock_zeroconf):
assert url_path == "mock-dashboard" assert url_path == "mock-dashboard"
async def test_use_cloud_url(hass, mock_zeroconf): async def test_use_cloud_url(hass: HomeAssistant, mock_zeroconf: None) -> None:
"""Test that we fall back to cloud url.""" """Test that we fall back to cloud url."""
await async_process_ha_core_config( await async_process_ha_core_config(
hass, hass,
@ -102,7 +104,7 @@ async def test_use_cloud_url(hass, mock_zeroconf):
assert controller.hass_url == "https://something.nabu.casa" assert controller.hass_url == "https://something.nabu.casa"
async def test_remove_entry(hass, mock_zeroconf): async def test_remove_entry(hass: HomeAssistant, mock_zeroconf: None) -> None:
"""Test removing config entry removes user.""" """Test removing config entry removes user."""
entry = MockConfigEntry( entry = MockConfigEntry(
data={}, data={},

View File

@ -1,5 +1,4 @@
"""The tests for the Cast Media player platform.""" """The tests for the Cast Media player platform."""
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
@ -40,6 +39,8 @@ from tests.common import (
mock_platform, mock_platform,
) )
from tests.components.media_player import common from tests.components.media_player import common
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import WebSocketGenerator
# pylint: disable=invalid-name # pylint: disable=invalid-name
FakeUUID = UUID("57355bce-9364-4aa6-ac1e-eb849dccf9e2") FakeUUID = UUID("57355bce-9364-4aa6-ac1e-eb849dccf9e2")
@ -255,7 +256,9 @@ def get_status_callbacks(chromecast_mock, mz_mock=None):
return cast_status_cb, conn_status_cb, media_status_cb, group_media_status_cb return cast_status_cb, conn_status_cb, media_status_cb, group_media_status_cb
async def test_start_discovery_called_once(hass, castbrowser_mock): async def test_start_discovery_called_once(
hass: HomeAssistant, castbrowser_mock
) -> None:
"""Test pychromecast.start_discovery called exactly once.""" """Test pychromecast.start_discovery called exactly once."""
await async_setup_cast(hass) await async_setup_cast(hass)
assert castbrowser_mock.return_value.start_discovery.call_count == 1 assert castbrowser_mock.return_value.start_discovery.call_count == 1
@ -265,8 +268,8 @@ async def test_start_discovery_called_once(hass, castbrowser_mock):
async def test_internal_discovery_callback_fill_out_group_fail( async def test_internal_discovery_callback_fill_out_group_fail(
hass, get_multizone_status_mock hass: HomeAssistant, get_multizone_status_mock
): ) -> None:
"""Test internal discovery automatically filling out information.""" """Test internal discovery automatically filling out information."""
discover_cast, _, _ = await async_setup_cast_internal_discovery(hass) discover_cast, _, _ = await async_setup_cast_internal_discovery(hass)
info = get_fake_chromecast_info(host="host1", port=12345, service=FAKE_MDNS_SERVICE) info = get_fake_chromecast_info(host="host1", port=12345, service=FAKE_MDNS_SERVICE)
@ -306,8 +309,8 @@ async def test_internal_discovery_callback_fill_out_group_fail(
async def test_internal_discovery_callback_fill_out_group( async def test_internal_discovery_callback_fill_out_group(
hass, get_multizone_status_mock hass: HomeAssistant, get_multizone_status_mock
): ) -> None:
"""Test internal discovery automatically filling out information.""" """Test internal discovery automatically filling out information."""
discover_cast, _, _ = await async_setup_cast_internal_discovery(hass) discover_cast, _, _ = await async_setup_cast_internal_discovery(hass)
info = get_fake_chromecast_info(host="host1", port=12345, service=FAKE_MDNS_SERVICE) info = get_fake_chromecast_info(host="host1", port=12345, service=FAKE_MDNS_SERVICE)
@ -347,8 +350,8 @@ async def test_internal_discovery_callback_fill_out_group(
async def test_internal_discovery_callback_fill_out_cast_type_manufacturer( async def test_internal_discovery_callback_fill_out_cast_type_manufacturer(
hass, get_cast_type_mock, caplog hass: HomeAssistant, get_cast_type_mock, caplog: pytest.LogCaptureFixture
): ) -> None:
"""Test internal discovery automatically filling out information.""" """Test internal discovery automatically filling out information."""
discover_cast, _, _ = await async_setup_cast_internal_discovery(hass) discover_cast, _, _ = await async_setup_cast_internal_discovery(hass)
info = get_fake_chromecast_info( info = get_fake_chromecast_info(
@ -434,7 +437,9 @@ async def test_internal_discovery_callback_fill_out_cast_type_manufacturer(
assert discover == full_info2 assert discover == full_info2
async def test_stop_discovery_called_on_stop(hass, castbrowser_mock): async def test_stop_discovery_called_on_stop(
hass: HomeAssistant, castbrowser_mock
) -> None:
"""Test pychromecast.stop_discovery called on shutdown.""" """Test pychromecast.stop_discovery called on shutdown."""
# start_discovery should be called with empty config # start_discovery should be called with empty config
await async_setup_cast(hass, {}) await async_setup_cast(hass, {})
@ -546,8 +551,11 @@ async def test_auto_cast_chromecasts(hass: HomeAssistant) -> None:
async def test_discover_dynamic_group( async def test_discover_dynamic_group(
hass, get_multizone_status_mock, get_chromecast_mock, caplog hass: HomeAssistant,
): get_multizone_status_mock,
get_chromecast_mock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test dynamic group does not create device or entity.""" """Test dynamic group does not create device or entity."""
cast_1 = get_fake_chromecast_info(host="host_1", port=23456, uuid=FakeUUID) cast_1 = get_fake_chromecast_info(host="host_1", port=23456, uuid=FakeUUID)
cast_2 = get_fake_chromecast_info(host="host_2", port=34567, uuid=FakeUUID2) cast_2 = get_fake_chromecast_info(host="host_2", port=34567, uuid=FakeUUID2)
@ -704,7 +712,7 @@ async def test_update_cast_chromecasts(hass: HomeAssistant) -> None:
assert add_dev1.call_count == 1 assert add_dev1.call_count == 1
async def test_entity_availability(hass: HomeAssistant): async def test_entity_availability(hass: HomeAssistant) -> None:
"""Test handling of connection status.""" """Test handling of connection status."""
entity_id = "media_player.speaker" entity_id = "media_player.speaker"
info = get_fake_chromecast_info() info = get_fake_chromecast_info()
@ -753,7 +761,9 @@ async def test_entity_availability(hass: HomeAssistant):
@pytest.mark.parametrize("port,entry_type", ((8009, None), (12345, None))) @pytest.mark.parametrize("port,entry_type", ((8009, None), (12345, None)))
async def test_device_registry(hass: HomeAssistant, hass_ws_client, port, entry_type): async def test_device_registry(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, port, entry_type
) -> None:
"""Test device registry integration.""" """Test device registry integration."""
assert await async_setup_component(hass, "config", {}) assert await async_setup_component(hass, "config", {})
@ -806,7 +816,7 @@ async def test_device_registry(hass: HomeAssistant, hass_ws_client, port, entry_
assert dev_reg.async_get(entity_entry.device_id) is None assert dev_reg.async_get(entity_entry.device_id) is None
async def test_entity_cast_status(hass: HomeAssistant): async def test_entity_cast_status(hass: HomeAssistant) -> None:
"""Test handling of cast status.""" """Test handling of cast status."""
entity_id = "media_player.speaker" entity_id = "media_player.speaker"
reg = er.async_get(hass) reg = er.async_get(hass)
@ -934,7 +944,7 @@ async def test_entity_cast_status(hass: HomeAssistant):
) )
async def test_supported_features( async def test_supported_features(
hass: HomeAssistant, cast_type, supported_features, supported_features_no_media hass: HomeAssistant, cast_type, supported_features, supported_features_no_media
): ) -> None:
"""Test supported features.""" """Test supported features."""
entity_id = "media_player.speaker" entity_id = "media_player.speaker"
@ -964,7 +974,9 @@ async def test_supported_features(
assert state.attributes.get("supported_features") == supported_features assert state.attributes.get("supported_features") == supported_features
async def test_entity_browse_media(hass: HomeAssistant, hass_ws_client): async def test_entity_browse_media(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test we can browse media.""" """Test we can browse media."""
await async_setup_component(hass, "media_source", {"media_source": {}}) await async_setup_component(hass, "media_source", {"media_source": {}})
@ -1020,8 +1032,8 @@ async def test_entity_browse_media(hass: HomeAssistant, hass_ws_client):
[pychromecast.const.CAST_TYPE_AUDIO, pychromecast.const.CAST_TYPE_GROUP], [pychromecast.const.CAST_TYPE_AUDIO, pychromecast.const.CAST_TYPE_GROUP],
) )
async def test_entity_browse_media_audio_only( async def test_entity_browse_media_audio_only(
hass: HomeAssistant, hass_ws_client, cast_type hass: HomeAssistant, hass_ws_client: WebSocketGenerator, cast_type
): ) -> None:
"""Test we can browse media.""" """Test we can browse media."""
await async_setup_component(hass, "media_source", {"media_source": {}}) await async_setup_component(hass, "media_source", {"media_source": {}})
@ -1073,7 +1085,7 @@ async def test_entity_browse_media_audio_only(
assert expected_child_2 in response["result"]["children"] assert expected_child_2 in response["result"]["children"]
async def test_entity_play_media(hass: HomeAssistant, quick_play_mock): async def test_entity_play_media(hass: HomeAssistant, quick_play_mock) -> None:
"""Test playing media.""" """Test playing media."""
entity_id = "media_player.speaker" entity_id = "media_player.speaker"
reg = er.async_get(hass) reg = er.async_get(hass)
@ -1119,7 +1131,7 @@ async def test_entity_play_media(hass: HomeAssistant, quick_play_mock):
) )
async def test_entity_play_media_cast(hass: HomeAssistant, quick_play_mock): async def test_entity_play_media_cast(hass: HomeAssistant, quick_play_mock) -> None:
"""Test playing media with cast special features.""" """Test playing media with cast special features."""
entity_id = "media_player.speaker" entity_id = "media_player.speaker"
reg = er.async_get(hass) reg = er.async_get(hass)
@ -1161,7 +1173,9 @@ async def test_entity_play_media_cast(hass: HomeAssistant, quick_play_mock):
) )
async def test_entity_play_media_cast_invalid(hass, caplog, quick_play_mock): async def test_entity_play_media_cast_invalid(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, quick_play_mock
) -> None:
"""Test playing media.""" """Test playing media."""
entity_id = "media_player.speaker" entity_id = "media_player.speaker"
reg = er.async_get(hass) reg = er.async_get(hass)
@ -1204,7 +1218,7 @@ async def test_entity_play_media_cast_invalid(hass, caplog, quick_play_mock):
assert "App unknown not supported" in caplog.text assert "App unknown not supported" in caplog.text
async def test_entity_play_media_sign_URL(hass: HomeAssistant, quick_play_mock): async def test_entity_play_media_sign_URL(hass: HomeAssistant, quick_play_mock) -> None:
"""Test playing media.""" """Test playing media."""
entity_id = "media_player.speaker" entity_id = "media_player.speaker"
@ -1284,8 +1298,13 @@ async def test_entity_play_media_sign_URL(hass: HomeAssistant, quick_play_mock):
), ),
) )
async def test_entity_play_media_playlist( async def test_entity_play_media_playlist(
hass: HomeAssistant, aioclient_mock, quick_play_mock, url, fixture, playlist_item hass: HomeAssistant,
): aioclient_mock: AiohttpClientMocker,
quick_play_mock,
url,
fixture,
playlist_item,
) -> None:
"""Test playing media.""" """Test playing media."""
entity_id = "media_player.speaker" entity_id = "media_player.speaker"
aioclient_mock.get(url, text=load_fixture(fixture, "cast")) aioclient_mock.get(url, text=load_fixture(fixture, "cast"))
@ -1314,7 +1333,7 @@ async def test_entity_play_media_playlist(
) )
async def test_entity_media_content_type(hass: HomeAssistant): async def test_entity_media_content_type(hass: HomeAssistant) -> None:
"""Test various content types.""" """Test various content types."""
entity_id = "media_player.speaker" entity_id = "media_player.speaker"
reg = er.async_get(hass) reg = er.async_get(hass)
@ -1365,7 +1384,7 @@ async def test_entity_media_content_type(hass: HomeAssistant):
assert state.attributes.get("media_content_type") == "movie" assert state.attributes.get("media_content_type") == "movie"
async def test_entity_control(hass: HomeAssistant, quick_play_mock): async def test_entity_control(hass: HomeAssistant, quick_play_mock) -> None:
"""Test various device and media controls.""" """Test various device and media controls."""
entity_id = "media_player.speaker" entity_id = "media_player.speaker"
reg = er.async_get(hass) reg = er.async_get(hass)
@ -1494,7 +1513,7 @@ async def test_entity_control(hass: HomeAssistant, quick_play_mock):
"app_id, state_no_media", "app_id, state_no_media",
[(pychromecast.APP_YOUTUBE, "idle"), ("Netflix", "playing")], [(pychromecast.APP_YOUTUBE, "idle"), ("Netflix", "playing")],
) )
async def test_entity_media_states(hass: HomeAssistant, app_id, state_no_media): async def test_entity_media_states(hass: HomeAssistant, app_id, state_no_media) -> None:
"""Test various entity media states.""" """Test various entity media states."""
entity_id = "media_player.speaker" entity_id = "media_player.speaker"
reg = er.async_get(hass) reg = er.async_get(hass)
@ -1573,7 +1592,7 @@ async def test_entity_media_states(hass: HomeAssistant, app_id, state_no_media):
assert state.state == "unknown" assert state.state == "unknown"
async def test_entity_media_states_lovelace_app(hass: HomeAssistant): async def test_entity_media_states_lovelace_app(hass: HomeAssistant) -> None:
"""Test various entity media states when the lovelace app is active.""" """Test various entity media states when the lovelace app is active."""
entity_id = "media_player.speaker" entity_id = "media_player.speaker"
reg = er.async_get(hass) reg = er.async_get(hass)
@ -1644,7 +1663,7 @@ async def test_entity_media_states_lovelace_app(hass: HomeAssistant):
assert state.state == "unknown" assert state.state == "unknown"
async def test_group_media_states(hass, mz_mock): async def test_group_media_states(hass: HomeAssistant, mz_mock) -> None:
"""Test media states are read from group if entity has no state.""" """Test media states are read from group if entity has no state."""
entity_id = "media_player.speaker" entity_id = "media_player.speaker"
reg = er.async_get(hass) reg = er.async_get(hass)
@ -1701,7 +1720,7 @@ async def test_group_media_states(hass, mz_mock):
assert state.state == "playing" assert state.state == "playing"
async def test_group_media_states_early(hass, mz_mock): async def test_group_media_states_early(hass: HomeAssistant, mz_mock) -> None:
"""Test media states are read from group if entity has no state. """Test media states are read from group if entity has no state.
This tests case asserts group state is polled when the player is created. This tests case asserts group state is polled when the player is created.
@ -1754,7 +1773,9 @@ async def test_group_media_states_early(hass, mz_mock):
assert hass.states.get(entity_id).state == "playing" assert hass.states.get(entity_id).state == "playing"
async def test_group_media_control(hass, mz_mock, quick_play_mock): async def test_group_media_control(
hass: HomeAssistant, mz_mock, quick_play_mock
) -> None:
"""Test media controls are handled by group if entity has no state.""" """Test media controls are handled by group if entity has no state."""
entity_id = "media_player.speaker" entity_id = "media_player.speaker"
reg = er.async_get(hass) reg = er.async_get(hass)
@ -1956,7 +1977,7 @@ async def test_failed_cast_tts_base_url(
) )
async def test_disconnect_on_stop(hass: HomeAssistant): async def test_disconnect_on_stop(hass: HomeAssistant) -> None:
"""Test cast device disconnects socket on stop.""" """Test cast device disconnects socket on stop."""
info = get_fake_chromecast_info() info = get_fake_chromecast_info()
@ -1967,7 +1988,7 @@ async def test_disconnect_on_stop(hass: HomeAssistant):
assert chromecast.disconnect.call_count == 1 assert chromecast.disconnect.call_count == 1
async def test_entry_setup_no_config(hass: HomeAssistant): async def test_entry_setup_no_config(hass: HomeAssistant) -> None:
"""Test deprecated empty yaml config..""" """Test deprecated empty yaml config.."""
await async_setup_component(hass, "cast", {}) await async_setup_component(hass, "cast", {})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -1975,7 +1996,7 @@ async def test_entry_setup_no_config(hass: HomeAssistant):
assert not hass.config_entries.async_entries("cast") assert not hass.config_entries.async_entries("cast")
async def test_entry_setup_empty_config(hass: HomeAssistant): async def test_entry_setup_empty_config(hass: HomeAssistant) -> None:
"""Test deprecated empty yaml config..""" """Test deprecated empty yaml config.."""
await async_setup_component(hass, "cast", {"cast": {}}) await async_setup_component(hass, "cast", {"cast": {}})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -1985,7 +2006,7 @@ async def test_entry_setup_empty_config(hass: HomeAssistant):
assert config_entry.data["ignore_cec"] == [] assert config_entry.data["ignore_cec"] == []
async def test_entry_setup_single_config(hass: HomeAssistant): async def test_entry_setup_single_config(hass: HomeAssistant) -> None:
"""Test deprecated yaml config with a single config media_player.""" """Test deprecated yaml config with a single config media_player."""
await async_setup_component( await async_setup_component(
hass, "cast", {"cast": {"media_player": {"uuid": "bla", "ignore_cec": "cast1"}}} hass, "cast", {"cast": {"media_player": {"uuid": "bla", "ignore_cec": "cast1"}}}
@ -1999,7 +2020,7 @@ async def test_entry_setup_single_config(hass: HomeAssistant):
assert ["cast1"] == pychromecast.IGNORE_CEC assert ["cast1"] == pychromecast.IGNORE_CEC
async def test_entry_setup_list_config(hass: HomeAssistant): async def test_entry_setup_list_config(hass: HomeAssistant) -> None:
"""Test deprecated yaml config with multiple media_players.""" """Test deprecated yaml config with multiple media_players."""
await async_setup_component( await async_setup_component(
hass, hass,
@ -2021,7 +2042,9 @@ async def test_entry_setup_list_config(hass: HomeAssistant):
assert set(pychromecast.IGNORE_CEC) == {"cast1", "cast2", "cast3"} assert set(pychromecast.IGNORE_CEC) == {"cast1", "cast2", "cast3"}
async def test_invalid_cast_platform(hass: HomeAssistant, caplog): async def test_invalid_cast_platform(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test we can play media through a cast platform.""" """Test we can play media through a cast platform."""
cast_platform_mock = Mock() cast_platform_mock = Mock()
del cast_platform_mock.async_get_media_browser_root_object del cast_platform_mock.async_get_media_browser_root_object
@ -2038,7 +2061,9 @@ async def test_invalid_cast_platform(hass: HomeAssistant, caplog):
assert "Invalid cast platform <Mock id" in caplog.text assert "Invalid cast platform <Mock id" in caplog.text
async def test_cast_platform_play_media(hass: HomeAssistant, quick_play_mock, caplog): async def test_cast_platform_play_media(
hass: HomeAssistant, quick_play_mock, caplog: pytest.LogCaptureFixture
) -> None:
"""Test we can play media through a cast platform.""" """Test we can play media through a cast platform."""
entity_id = "media_player.speaker" entity_id = "media_player.speaker"
@ -2115,7 +2140,9 @@ async def test_cast_platform_play_media(hass: HomeAssistant, quick_play_mock, ca
quick_play_mock.assert_called() quick_play_mock.assert_called()
async def test_cast_platform_browse_media(hass: HomeAssistant, hass_ws_client): async def test_cast_platform_browse_media(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test we can play media through a cast platform.""" """Test we can play media through a cast platform."""
cast_platform_mock = Mock( cast_platform_mock = Mock(
async_get_media_browser_root_object=AsyncMock( async_get_media_browser_root_object=AsyncMock(
@ -2209,8 +2236,8 @@ async def test_cast_platform_browse_media(hass: HomeAssistant, hass_ws_client):
async def test_cast_platform_play_media_local_media( async def test_cast_platform_play_media_local_media(
hass: HomeAssistant, quick_play_mock, caplog hass: HomeAssistant, quick_play_mock, caplog: pytest.LogCaptureFixture
): ) -> None:
"""Test we process data when playing local media.""" """Test we process data when playing local media."""
entity_id = "media_player.speaker" entity_id = "media_player.speaker"
info = get_fake_chromecast_info() info = get_fake_chromecast_info()

View File

@ -74,7 +74,7 @@ async def test_update_unique_id(hass: HomeAssistant) -> None:
@patch("homeassistant.util.dt.utcnow", return_value=static_datetime()) @patch("homeassistant.util.dt.utcnow", return_value=static_datetime())
async def test_unload_config_entry(mock_now, hass): async def test_unload_config_entry(mock_now, hass: HomeAssistant) -> None:
"""Test unloading a config entry.""" """Test unloading a config entry."""
assert hass.state is CoreState.running assert hass.state is CoreState.running

View File

@ -16,7 +16,7 @@ from tests.common import MockConfigEntry, async_fire_time_changed
@patch("homeassistant.util.dt.utcnow", return_value=static_datetime()) @patch("homeassistant.util.dt.utcnow", return_value=static_datetime())
async def test_async_setup_entry(mock_now, hass): async def test_async_setup_entry(mock_now, hass: HomeAssistant) -> None:
"""Test async_setup_entry.""" """Test async_setup_entry."""
assert hass.state is CoreState.running assert hass.state is CoreState.running

View File

@ -53,7 +53,9 @@ async def setup_notify(hass):
await hass.async_block_till_done() await hass.async_block_till_done()
async def test_no_notify_service(hass, mock_clicksend_tts_notify, caplog): async def test_no_notify_service(
hass: HomeAssistant, mock_clicksend_tts_notify, caplog: pytest.LogCaptureFixture
) -> None:
"""Test missing platform notify service instance.""" """Test missing platform notify service instance."""
caplog.set_level(logging.ERROR) caplog.set_level(logging.ERROR)
mock_clicksend_tts_notify.return_value = None mock_clicksend_tts_notify.return_value = None

View File

@ -7,7 +7,11 @@ from homeassistant.components.climate import DOMAIN, HVACMode, const, device_act
from homeassistant.components.device_automation import DeviceAutomationType from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.const import EntityCategory from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv, device_registry as dr from homeassistant.helpers import (
config_validation as cv,
device_registry as dr,
entity_registry as er,
)
from homeassistant.helpers.entity_registry import RegistryEntryHider from homeassistant.helpers.entity_registry import RegistryEntryHider
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -40,14 +44,14 @@ from tests.components.blueprint.conftest import stub_blueprint_populate # noqa:
], ],
) )
async def test_get_actions( async def test_get_actions(
hass, hass: HomeAssistant,
device_registry, device_registry: dr.DeviceRegistry,
entity_registry, entity_registry: er.EntityRegistry,
set_state, set_state,
features_reg, features_reg,
features_state, features_state,
expected_action_types, expected_action_types,
): ) -> None:
"""Test we get the expected actions from a climate.""" """Test we get the expected actions from a climate."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -96,12 +100,12 @@ async def test_get_actions(
), ),
) )
async def test_get_actions_hidden_auxiliary( async def test_get_actions_hidden_auxiliary(
hass, hass: HomeAssistant,
device_registry, device_registry: dr.DeviceRegistry,
entity_registry, entity_registry: er.EntityRegistry,
hidden_by, hidden_by,
entity_category, entity_category,
): ) -> None:
"""Test we get the expected actions from a hidden or auxiliary entity.""" """Test we get the expected actions from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -257,15 +261,15 @@ async def test_action(hass: HomeAssistant) -> None:
], ],
) )
async def test_capabilities( async def test_capabilities(
hass, hass: HomeAssistant,
device_registry, device_registry: dr.DeviceRegistry,
entity_registry, entity_registry: er.EntityRegistry,
set_state, set_state,
capabilities_reg, capabilities_reg,
capabilities_state, capabilities_state,
action, action,
expected_capabilities, expected_capabilities,
): ) -> None:
"""Test getting capabilities.""" """Test getting capabilities."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -311,7 +315,9 @@ async def test_capabilities(
"action,capability_name", "action,capability_name",
[("set_hvac_mode", "hvac_mode"), ("set_preset_mode", "preset_mode")], [("set_hvac_mode", "hvac_mode"), ("set_preset_mode", "preset_mode")],
) )
async def test_capabilities_missing_entity(hass, action, capability_name): async def test_capabilities_missing_entity(
hass: HomeAssistant, action, capability_name
) -> None:
"""Test getting capabilities.""" """Test getting capabilities."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)

View File

@ -6,7 +6,12 @@ import homeassistant.components.automation as automation
from homeassistant.components.climate import DOMAIN, HVACMode, const, device_condition from homeassistant.components.climate import DOMAIN, HVACMode, const, device_condition
from homeassistant.components.device_automation import DeviceAutomationType from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.const import EntityCategory from homeassistant.const import EntityCategory
from homeassistant.helpers import config_validation as cv, device_registry as dr from homeassistant.core import HomeAssistant
from homeassistant.helpers import (
config_validation as cv,
device_registry as dr,
entity_registry as er,
)
from homeassistant.helpers.entity_registry import RegistryEntryHider from homeassistant.helpers.entity_registry import RegistryEntryHider
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -45,14 +50,14 @@ def calls(hass):
], ],
) )
async def test_get_conditions( async def test_get_conditions(
hass, hass: HomeAssistant,
device_registry, device_registry: dr.DeviceRegistry,
entity_registry, entity_registry: er.EntityRegistry,
set_state, set_state,
features_reg, features_reg,
features_state, features_state,
expected_condition_types, expected_condition_types,
): ) -> None:
"""Test we get the expected conditions from a climate.""" """Test we get the expected conditions from a climate."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -99,12 +104,12 @@ async def test_get_conditions(
), ),
) )
async def test_get_conditions_hidden_auxiliary( async def test_get_conditions_hidden_auxiliary(
hass, hass: HomeAssistant,
device_registry, device_registry: dr.DeviceRegistry,
entity_registry, entity_registry: er.EntityRegistry,
hidden_by, hidden_by,
entity_category, entity_category,
): ) -> None:
"""Test we get the expected conditions from a hidden or auxiliary entity.""" """Test we get the expected conditions from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -137,7 +142,7 @@ async def test_get_conditions_hidden_auxiliary(
assert_lists_same(conditions, expected_conditions) assert_lists_same(conditions, expected_conditions)
async def test_if_state(hass, calls): async def test_if_state(hass: HomeAssistant, calls) -> None:
"""Test for turn_on and turn_off conditions.""" """Test for turn_on and turn_off conditions."""
assert await async_setup_component( assert await async_setup_component(
hass, hass,
@ -305,15 +310,15 @@ async def test_if_state(hass, calls):
], ],
) )
async def test_capabilities( async def test_capabilities(
hass, hass: HomeAssistant,
device_registry, device_registry: dr.DeviceRegistry,
entity_registry, entity_registry: er.EntityRegistry,
set_state, set_state,
capabilities_reg, capabilities_reg,
capabilities_state, capabilities_state,
condition, condition,
expected_capabilities, expected_capabilities,
): ) -> None:
"""Test getting capabilities.""" """Test getting capabilities."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -360,7 +365,9 @@ async def test_capabilities(
"condition,capability_name", "condition,capability_name",
[("is_hvac_mode", "hvac_mode"), ("is_preset_mode", "preset_mode")], [("is_hvac_mode", "hvac_mode"), ("is_preset_mode", "preset_mode")],
) )
async def test_capabilities_missing_entity(hass, condition, capability_name): async def test_capabilities_missing_entity(
hass: HomeAssistant, condition, capability_name
) -> None:
"""Test getting capabilities.""" """Test getting capabilities."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)

View File

@ -13,7 +13,11 @@ from homeassistant.components.climate import (
from homeassistant.components.device_automation import DeviceAutomationType from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.const import EntityCategory, UnitOfTemperature from homeassistant.const import EntityCategory, UnitOfTemperature
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv, device_registry as dr from homeassistant.helpers import (
config_validation as cv,
device_registry as dr,
entity_registry as er,
)
from homeassistant.helpers.entity_registry import RegistryEntryHider from homeassistant.helpers.entity_registry import RegistryEntryHider
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -32,7 +36,11 @@ def calls(hass):
return async_mock_service(hass, "test", "automation") return async_mock_service(hass, "test", "automation")
async def test_get_triggers(hass, device_registry, entity_registry): async def test_get_triggers(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected triggers from a climate device.""" """Test we get the expected triggers from a climate device."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -84,12 +92,12 @@ async def test_get_triggers(hass, device_registry, entity_registry):
), ),
) )
async def test_get_triggers_hidden_auxiliary( async def test_get_triggers_hidden_auxiliary(
hass, hass: HomeAssistant,
device_registry, device_registry: dr.DeviceRegistry,
entity_registry, entity_registry: er.EntityRegistry,
hidden_by, hidden_by,
entity_category, entity_category,
): ) -> None:
"""Test we get the expected triggers from a hidden or auxiliary entity.""" """Test we get the expected triggers from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={}) config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -136,7 +144,7 @@ async def test_get_triggers_hidden_auxiliary(
assert_lists_same(triggers, expected_triggers) assert_lists_same(triggers, expected_triggers)
async def test_if_fires_on_state_change(hass, calls): async def test_if_fires_on_state_change(hass: HomeAssistant, calls) -> None:
"""Test for turn_on and turn_off triggers firing.""" """Test for turn_on and turn_off triggers firing."""
hass.states.async_set( hass.states.async_set(
"climate.entity", "climate.entity",
@ -280,7 +288,7 @@ async def test_get_trigger_capabilities_hvac_mode(hass: HomeAssistant) -> None:
@pytest.mark.parametrize( @pytest.mark.parametrize(
"type", ["current_temperature_changed", "current_humidity_changed"] "type", ["current_temperature_changed", "current_humidity_changed"]
) )
async def test_get_trigger_capabilities_temp_humid(hass, type): async def test_get_trigger_capabilities_temp_humid(hass: HomeAssistant, type) -> None:
"""Test we get the expected capabilities from a climate trigger.""" """Test we get the expected capabilities from a climate trigger."""
capabilities = await device_trigger.async_get_trigger_capabilities( capabilities = await device_trigger.async_get_trigger_capabilities(
hass, hass,

View File

@ -15,10 +15,11 @@ from homeassistant.components.climate import (
ATTR_SWING_MODES, ATTR_SWING_MODES,
ATTR_TARGET_TEMP_STEP, ATTR_TARGET_TEMP_STEP,
) )
from homeassistant.components.recorder import Recorder
from homeassistant.components.recorder.db_schema import StateAttributes, States from homeassistant.components.recorder.db_schema import StateAttributes, States
from homeassistant.components.recorder.util import session_scope from homeassistant.components.recorder.util import session_scope
from homeassistant.const import ATTR_FRIENDLY_NAME from homeassistant.const import ATTR_FRIENDLY_NAME
from homeassistant.core import State from homeassistant.core import HomeAssistant, State
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
@ -26,7 +27,7 @@ from tests.common import async_fire_time_changed
from tests.components.recorder.common import async_wait_recording_done from tests.components.recorder.common import async_wait_recording_done
async def test_exclude_attributes(recorder_mock, hass): async def test_exclude_attributes(recorder_mock: Recorder, hass: HomeAssistant) -> None:
"""Test climate registered attributes to be excluded.""" """Test climate registered attributes to be excluded."""
await async_setup_component( await async_setup_component(
hass, climate.DOMAIN, {climate.DOMAIN: {"platform": "demo"}} hass, climate.DOMAIN, {climate.DOMAIN: {"platform": "demo"}}

View File

@ -30,7 +30,7 @@ ENTITY_2 = "climate.test2"
@pytest.mark.parametrize("state", [HVACMode.AUTO, HVACMode.HEAT, HVACMode.OFF]) @pytest.mark.parametrize("state", [HVACMode.AUTO, HVACMode.HEAT, HVACMode.OFF])
async def test_with_hvac_mode(hass, state): async def test_with_hvac_mode(hass: HomeAssistant, state) -> None:
"""Test that state different hvac states.""" """Test that state different hvac states."""
calls = async_mock_service(hass, DOMAIN, SERVICE_SET_HVAC_MODE) calls = async_mock_service(hass, DOMAIN, SERVICE_SET_HVAC_MODE)
@ -105,7 +105,7 @@ async def test_state_with_context(hass: HomeAssistant) -> None:
(SERVICE_SET_TEMPERATURE, ATTR_TARGET_TEMP_LOW), (SERVICE_SET_TEMPERATURE, ATTR_TARGET_TEMP_LOW),
], ],
) )
async def test_attribute(hass, service, attribute): async def test_attribute(hass: HomeAssistant, service, attribute) -> None:
"""Test that service call is made for each attribute.""" """Test that service call is made for each attribute."""
calls_1 = async_mock_service(hass, DOMAIN, service) calls_1 = async_mock_service(hass, DOMAIN, service)

View File

@ -166,7 +166,9 @@ async def test_get_services_error(hass: HomeAssistant) -> None:
assert account_link.DATA_SERVICES not in hass.data assert account_link.DATA_SERVICES not in hass.data
async def test_implementation(hass, flow_handler, current_request_with_host): async def test_implementation(
hass: HomeAssistant, flow_handler, current_request_with_host: None
) -> None:
"""Test Cloud OAuth2 implementation.""" """Test Cloud OAuth2 implementation."""
hass.data["cloud"] = None hass.data["cloud"] = None

View File

@ -7,10 +7,12 @@ import pytest
from homeassistant.components.alexa import errors from homeassistant.components.alexa import errors
from homeassistant.components.cloud import ALEXA_SCHEMA, alexa_config from homeassistant.components.cloud import ALEXA_SCHEMA, alexa_config
from homeassistant.const import EntityCategory from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
from tests.common import async_fire_time_changed from tests.common import async_fire_time_changed
from tests.test_util.aiohttp import AiohttpClientMocker
@pytest.fixture @pytest.fixture
@ -20,8 +22,8 @@ def cloud_stub():
async def test_alexa_config_expose_entity_prefs( async def test_alexa_config_expose_entity_prefs(
hass, cloud_prefs, cloud_stub, entity_registry hass: HomeAssistant, cloud_prefs, cloud_stub, entity_registry: er.EntityRegistry
): ) -> None:
"""Test Alexa config should expose using prefs.""" """Test Alexa config should expose using prefs."""
entity_entry1 = entity_registry.async_get_or_create( entity_entry1 = entity_registry.async_get_or_create(
"light", "light",
@ -95,7 +97,9 @@ async def test_alexa_config_expose_entity_prefs(
assert not conf.should_expose("light.kitchen") assert not conf.should_expose("light.kitchen")
async def test_alexa_config_report_state(hass, cloud_prefs, cloud_stub): async def test_alexa_config_report_state(
hass: HomeAssistant, cloud_prefs, cloud_stub
) -> None:
"""Test Alexa config should expose using prefs.""" """Test Alexa config should expose using prefs."""
await cloud_prefs.async_update( await cloud_prefs.async_update(
alexa_report_state=False, alexa_report_state=False,
@ -126,7 +130,9 @@ async def test_alexa_config_report_state(hass, cloud_prefs, cloud_stub):
assert conf.is_reporting_states is False assert conf.is_reporting_states is False
async def test_alexa_config_invalidate_token(hass, cloud_prefs, aioclient_mock): async def test_alexa_config_invalidate_token(
hass: HomeAssistant, cloud_prefs, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test Alexa config should expose using prefs.""" """Test Alexa config should expose using prefs."""
aioclient_mock.post( aioclient_mock.post(
"https://example/access_token", "https://example/access_token",
@ -172,12 +178,12 @@ async def test_alexa_config_invalidate_token(hass, cloud_prefs, aioclient_mock):
], ],
) )
async def test_alexa_config_fail_refresh_token( async def test_alexa_config_fail_refresh_token(
hass, hass: HomeAssistant,
cloud_prefs, cloud_prefs,
aioclient_mock, aioclient_mock: AiohttpClientMocker,
reject_reason, reject_reason,
expected_exception, expected_exception,
): ) -> None:
"""Test Alexa config failing to refresh token.""" """Test Alexa config failing to refresh token."""
aioclient_mock.post( aioclient_mock.post(
@ -285,7 +291,9 @@ def patch_sync_helper():
yield to_update, to_remove yield to_update, to_remove
async def test_alexa_update_expose_trigger_sync(hass, cloud_prefs, cloud_stub): async def test_alexa_update_expose_trigger_sync(
hass: HomeAssistant, cloud_prefs, cloud_stub
) -> None:
"""Test Alexa config responds to updating exposed entities.""" """Test Alexa config responds to updating exposed entities."""
hass.states.async_set("binary_sensor.door", "on") hass.states.async_set("binary_sensor.door", "on")
hass.states.async_set( hass.states.async_set(
@ -345,7 +353,9 @@ async def test_alexa_update_expose_trigger_sync(hass, cloud_prefs, cloud_stub):
assert to_remove == ["binary_sensor.door", "sensor.temp", "light.kitchen"] assert to_remove == ["binary_sensor.door", "sensor.temp", "light.kitchen"]
async def test_alexa_entity_registry_sync(hass, mock_cloud_login, cloud_prefs): async def test_alexa_entity_registry_sync(
hass: HomeAssistant, mock_cloud_login, cloud_prefs
) -> None:
"""Test Alexa config responds to entity registry.""" """Test Alexa config responds to entity registry."""
await alexa_config.CloudAlexaConfig( await alexa_config.CloudAlexaConfig(
hass, ALEXA_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data["cloud"] hass, ALEXA_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data["cloud"]
@ -397,7 +407,9 @@ async def test_alexa_entity_registry_sync(hass, mock_cloud_login, cloud_prefs):
assert to_remove == [] assert to_remove == []
async def test_alexa_update_report_state(hass, cloud_prefs, cloud_stub): async def test_alexa_update_report_state(
hass: HomeAssistant, cloud_prefs, cloud_stub
) -> None:
"""Test Alexa config responds to reporting state.""" """Test Alexa config responds to reporting state."""
await cloud_prefs.async_update( await cloud_prefs.async_update(
alexa_report_state=False, alexa_report_state=False,
@ -419,7 +431,9 @@ async def test_alexa_update_report_state(hass, cloud_prefs, cloud_stub):
assert len(mock_sync.mock_calls) == 1 assert len(mock_sync.mock_calls) == 1
def test_enabled_requires_valid_sub(hass, mock_expired_cloud_login, cloud_prefs): def test_enabled_requires_valid_sub(
hass: HomeAssistant, mock_expired_cloud_login, cloud_prefs
) -> None:
"""Test that alexa config enabled requires a valid Cloud sub.""" """Test that alexa config enabled requires a valid Cloud sub."""
assert cloud_prefs.alexa_enabled assert cloud_prefs.alexa_enabled
assert hass.data["cloud"].is_logged_in assert hass.data["cloud"].is_logged_in
@ -432,7 +446,9 @@ def test_enabled_requires_valid_sub(hass, mock_expired_cloud_login, cloud_prefs)
assert not config.enabled assert not config.enabled
async def test_alexa_handle_logout(hass, cloud_prefs, cloud_stub): async def test_alexa_handle_logout(
hass: HomeAssistant, cloud_prefs, cloud_stub
) -> None:
"""Test Alexa config responds to logging out.""" """Test Alexa config responds to logging out."""
aconf = alexa_config.CloudAlexaConfig( aconf = alexa_config.CloudAlexaConfig(
hass, ALEXA_SCHEMA({}), "mock-user-id", cloud_prefs, cloud_stub hass, ALEXA_SCHEMA({}), "mock-user-id", cloud_prefs, cloud_stub

View File

@ -69,7 +69,7 @@ async def test_handler_alexa(hass: HomeAssistant) -> None:
assert device["manufacturerName"] == "Home Assistant" assert device["manufacturerName"] == "Home Assistant"
async def test_handler_alexa_disabled(hass, mock_cloud_fixture): async def test_handler_alexa_disabled(hass: HomeAssistant, mock_cloud_fixture) -> None:
"""Test handler Alexa when user has disabled it.""" """Test handler Alexa when user has disabled it."""
mock_cloud_fixture._prefs[PREF_ENABLE_ALEXA] = False mock_cloud_fixture._prefs[PREF_ENABLE_ALEXA] = False
cloud = hass.data["cloud"] cloud = hass.data["cloud"]
@ -142,8 +142,8 @@ async def test_handler_google_actions(hass: HomeAssistant) -> None:
], ],
) )
async def test_handler_google_actions_disabled( async def test_handler_google_actions_disabled(
hass, mock_cloud_fixture, intent, response_payload hass: HomeAssistant, mock_cloud_fixture, intent, response_payload
): ) -> None:
"""Test handler Google Actions when user has disabled it.""" """Test handler Google Actions when user has disabled it."""
mock_cloud_fixture._prefs[PREF_ENABLE_GOOGLE] = False mock_cloud_fixture._prefs[PREF_ENABLE_GOOGLE] = False
@ -241,7 +241,9 @@ async def test_webhook_msg(
assert '{"nonexisting": "payload"}' in caplog.text assert '{"nonexisting": "payload"}' in caplog.text
async def test_google_config_expose_entity(hass, mock_cloud_setup, mock_cloud_login): async def test_google_config_expose_entity(
hass: HomeAssistant, mock_cloud_setup, mock_cloud_login
) -> None:
"""Test Google config exposing entity method uses latest config.""" """Test Google config exposing entity method uses latest config."""
cloud_client = hass.data[DOMAIN].client cloud_client = hass.data[DOMAIN].client
state = State("light.kitchen", "on") state = State("light.kitchen", "on")
@ -256,7 +258,9 @@ async def test_google_config_expose_entity(hass, mock_cloud_setup, mock_cloud_lo
assert not gconf.should_expose(state) assert not gconf.should_expose(state)
async def test_google_config_should_2fa(hass, mock_cloud_setup, mock_cloud_login): async def test_google_config_should_2fa(
hass: HomeAssistant, mock_cloud_setup, mock_cloud_login
) -> None:
"""Test Google config disabling 2FA method uses latest config.""" """Test Google config disabling 2FA method uses latest config."""
cloud_client = hass.data[DOMAIN].client cloud_client = hass.data[DOMAIN].client
gconf = await cloud_client.get_google_config() gconf = await cloud_client.get_google_config()

View File

@ -9,7 +9,7 @@ from homeassistant.components.cloud import GACTIONS_SCHEMA
from homeassistant.components.cloud.google_config import CloudGoogleConfig from homeassistant.components.cloud.google_config import CloudGoogleConfig
from homeassistant.components.google_assistant import helpers as ga_helpers from homeassistant.components.google_assistant import helpers as ga_helpers
from homeassistant.const import EVENT_HOMEASSISTANT_STARTED, EntityCategory from homeassistant.const import EVENT_HOMEASSISTANT_STARTED, EntityCategory
from homeassistant.core import CoreState, State from homeassistant.core import CoreState, HomeAssistant, State
from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.util.dt import utcnow from homeassistant.util.dt import utcnow
@ -28,7 +28,9 @@ def mock_conf(hass, cloud_prefs):
) )
async def test_google_update_report_state(mock_conf, hass, cloud_prefs): async def test_google_update_report_state(
mock_conf, hass: HomeAssistant, cloud_prefs
) -> None:
"""Test Google config responds to updating preference.""" """Test Google config responds to updating preference."""
await mock_conf.async_initialize() await mock_conf.async_initialize()
await mock_conf.async_connect_agent_user("mock-user-id") await mock_conf.async_connect_agent_user("mock-user-id")
@ -46,8 +48,8 @@ async def test_google_update_report_state(mock_conf, hass, cloud_prefs):
async def test_google_update_report_state_subscription_expired( async def test_google_update_report_state_subscription_expired(
mock_conf, hass, cloud_prefs mock_conf, hass: HomeAssistant, cloud_prefs
): ) -> None:
"""Test Google config not reporting state when subscription has expired.""" """Test Google config not reporting state when subscription has expired."""
await mock_conf.async_initialize() await mock_conf.async_initialize()
await mock_conf.async_connect_agent_user("mock-user-id") await mock_conf.async_connect_agent_user("mock-user-id")
@ -64,7 +66,7 @@ async def test_google_update_report_state_subscription_expired(
assert len(mock_report_state.mock_calls) == 0 assert len(mock_report_state.mock_calls) == 0
async def test_sync_entities(mock_conf, hass, cloud_prefs): async def test_sync_entities(mock_conf, hass: HomeAssistant, cloud_prefs) -> None:
"""Test sync devices.""" """Test sync devices."""
await mock_conf.async_initialize() await mock_conf.async_initialize()
await mock_conf.async_connect_agent_user("mock-user-id") await mock_conf.async_connect_agent_user("mock-user-id")
@ -82,7 +84,9 @@ async def test_sync_entities(mock_conf, hass, cloud_prefs):
assert len(mock_request_sync.mock_calls) == 1 assert len(mock_request_sync.mock_calls) == 1
async def test_google_update_expose_trigger_sync(hass, cloud_prefs): async def test_google_update_expose_trigger_sync(
hass: HomeAssistant, cloud_prefs
) -> None:
"""Test Google config responds to updating exposed entities.""" """Test Google config responds to updating exposed entities."""
with freeze_time(utcnow()): with freeze_time(utcnow()):
config = CloudGoogleConfig( config = CloudGoogleConfig(
@ -126,7 +130,9 @@ async def test_google_update_expose_trigger_sync(hass, cloud_prefs):
assert len(mock_sync.mock_calls) == 1 assert len(mock_sync.mock_calls) == 1
async def test_google_entity_registry_sync(hass, mock_cloud_login, cloud_prefs): async def test_google_entity_registry_sync(
hass: HomeAssistant, mock_cloud_login, cloud_prefs
) -> None:
"""Test Google config responds to entity registry.""" """Test Google config responds to entity registry."""
config = CloudGoogleConfig( config = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data["cloud"] hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data["cloud"]
@ -190,7 +196,9 @@ async def test_google_entity_registry_sync(hass, mock_cloud_login, cloud_prefs):
assert len(mock_sync.mock_calls) == 3 assert len(mock_sync.mock_calls) == 3
async def test_google_device_registry_sync(hass, mock_cloud_login, cloud_prefs): async def test_google_device_registry_sync(
hass: HomeAssistant, mock_cloud_login, cloud_prefs
) -> None:
"""Test Google config responds to device registry.""" """Test Google config responds to device registry."""
config = CloudGoogleConfig( config = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data["cloud"] hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data["cloud"]
@ -249,7 +257,9 @@ async def test_google_device_registry_sync(hass, mock_cloud_login, cloud_prefs):
assert len(mock_sync.mock_calls) == 1 assert len(mock_sync.mock_calls) == 1
async def test_sync_google_when_started(hass, mock_cloud_login, cloud_prefs): async def test_sync_google_when_started(
hass: HomeAssistant, mock_cloud_login, cloud_prefs
) -> None:
"""Test Google config syncs on init.""" """Test Google config syncs on init."""
config = CloudGoogleConfig( config = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data["cloud"] hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data["cloud"]
@ -261,7 +271,9 @@ async def test_sync_google_when_started(hass, mock_cloud_login, cloud_prefs):
assert len(mock_sync.mock_calls) == 1 assert len(mock_sync.mock_calls) == 1
async def test_sync_google_on_home_assistant_start(hass, mock_cloud_login, cloud_prefs): async def test_sync_google_on_home_assistant_start(
hass: HomeAssistant, mock_cloud_login, cloud_prefs
) -> None:
"""Test Google config syncs when home assistant started.""" """Test Google config syncs when home assistant started."""
config = CloudGoogleConfig( config = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data["cloud"] hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data["cloud"]
@ -278,8 +290,8 @@ async def test_sync_google_on_home_assistant_start(hass, mock_cloud_login, cloud
async def test_google_config_expose_entity_prefs( async def test_google_config_expose_entity_prefs(
hass, mock_conf, cloud_prefs, entity_registry hass: HomeAssistant, mock_conf, cloud_prefs, entity_registry: er.EntityRegistry
): ) -> None:
"""Test Google config should expose using prefs.""" """Test Google config should expose using prefs."""
entity_entry1 = entity_registry.async_get_or_create( entity_entry1 = entity_registry.async_get_or_create(
"light", "light",
@ -350,7 +362,9 @@ async def test_google_config_expose_entity_prefs(
assert not mock_conf.should_expose(state) assert not mock_conf.should_expose(state)
def test_enabled_requires_valid_sub(hass, mock_expired_cloud_login, cloud_prefs): def test_enabled_requires_valid_sub(
hass: HomeAssistant, mock_expired_cloud_login, cloud_prefs
) -> None:
"""Test that google config enabled requires a valid Cloud sub.""" """Test that google config enabled requires a valid Cloud sub."""
assert cloud_prefs.google_enabled assert cloud_prefs.google_enabled
assert hass.data["cloud"].is_logged_in assert hass.data["cloud"].is_logged_in
@ -363,7 +377,7 @@ def test_enabled_requires_valid_sub(hass, mock_expired_cloud_login, cloud_prefs)
assert not config.enabled assert not config.enabled
async def test_setup_integration(hass, mock_conf, cloud_prefs): async def test_setup_integration(hass: HomeAssistant, mock_conf, cloud_prefs) -> None:
"""Test that we set up the integration if used.""" """Test that we set up the integration if used."""
mock_conf._cloud.subscription_expired = False mock_conf._cloud.subscription_expired = False
@ -380,7 +394,9 @@ async def test_setup_integration(hass, mock_conf, cloud_prefs):
assert "google_assistant" in hass.config.components assert "google_assistant" in hass.config.components
async def test_google_handle_logout(hass, cloud_prefs, mock_cloud_login): async def test_google_handle_logout(
hass: HomeAssistant, cloud_prefs, mock_cloud_login
) -> None:
"""Test Google config responds to logging out.""" """Test Google config responds to logging out."""
gconf = CloudGoogleConfig( gconf = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, Mock(is_logged_in=False) hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, Mock(is_logged_in=False)

View File

@ -20,6 +20,7 @@ from homeassistant.util.location import LocationInfo
from . import mock_cloud, mock_cloud_prefs from . import mock_cloud, mock_cloud_prefs
from tests.components.google_assistant import MockConfig from tests.components.google_assistant import MockConfig
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import WebSocketGenerator from tests.typing import WebSocketGenerator
SUBSCRIPTION_INFO_URL = "https://api-test.hass.io/payments/subscription_info" SUBSCRIPTION_INFO_URL = "https://api-test.hass.io/payments/subscription_info"
@ -75,7 +76,9 @@ def mock_cognito_fixture():
yield mock_cog() yield mock_cog()
async def test_google_actions_sync(mock_cognito, mock_cloud_login, cloud_client): async def test_google_actions_sync(
mock_cognito, mock_cloud_login, cloud_client
) -> None:
"""Test syncing Google Actions.""" """Test syncing Google Actions."""
with patch( with patch(
"hass_nabucasa.cloud_api.async_google_actions_request_sync", "hass_nabucasa.cloud_api.async_google_actions_request_sync",
@ -86,7 +89,9 @@ async def test_google_actions_sync(mock_cognito, mock_cloud_login, cloud_client)
assert len(mock_request_sync.mock_calls) == 1 assert len(mock_request_sync.mock_calls) == 1
async def test_google_actions_sync_fails(mock_cognito, mock_cloud_login, cloud_client): async def test_google_actions_sync_fails(
mock_cognito, mock_cloud_login, cloud_client
) -> None:
"""Test syncing Google Actions gone bad.""" """Test syncing Google Actions gone bad."""
with patch( with patch(
"hass_nabucasa.cloud_api.async_google_actions_request_sync", "hass_nabucasa.cloud_api.async_google_actions_request_sync",
@ -97,7 +102,7 @@ async def test_google_actions_sync_fails(mock_cognito, mock_cloud_login, cloud_c
assert len(mock_request_sync.mock_calls) == 1 assert len(mock_request_sync.mock_calls) == 1
async def test_login_view(hass, cloud_client): async def test_login_view(hass: HomeAssistant, cloud_client) -> None:
"""Test logging in.""" """Test logging in."""
hass.data["cloud"] = MagicMock(login=AsyncMock()) hass.data["cloud"] = MagicMock(login=AsyncMock())
@ -110,7 +115,7 @@ async def test_login_view(hass, cloud_client):
assert result == {"success": True} assert result == {"success": True}
async def test_login_view_random_exception(cloud_client): async def test_login_view_random_exception(cloud_client) -> None:
"""Try logging in with invalid JSON.""" """Try logging in with invalid JSON."""
with patch("hass_nabucasa.Cloud.login", side_effect=ValueError("Boom")): with patch("hass_nabucasa.Cloud.login", side_effect=ValueError("Boom")):
req = await cloud_client.post( req = await cloud_client.post(
@ -121,7 +126,7 @@ async def test_login_view_random_exception(cloud_client):
assert resp == {"code": "valueerror", "message": "Unexpected error: Boom"} assert resp == {"code": "valueerror", "message": "Unexpected error: Boom"}
async def test_login_view_invalid_json(cloud_client): async def test_login_view_invalid_json(cloud_client) -> None:
"""Try logging in with invalid JSON.""" """Try logging in with invalid JSON."""
with patch("hass_nabucasa.auth.CognitoAuth.async_login") as mock_login: with patch("hass_nabucasa.auth.CognitoAuth.async_login") as mock_login:
req = await cloud_client.post("/api/cloud/login", data="Not JSON") req = await cloud_client.post("/api/cloud/login", data="Not JSON")
@ -129,7 +134,7 @@ async def test_login_view_invalid_json(cloud_client):
assert len(mock_login.mock_calls) == 0 assert len(mock_login.mock_calls) == 0
async def test_login_view_invalid_schema(cloud_client): async def test_login_view_invalid_schema(cloud_client) -> None:
"""Try logging in with invalid schema.""" """Try logging in with invalid schema."""
with patch("hass_nabucasa.auth.CognitoAuth.async_login") as mock_login: with patch("hass_nabucasa.auth.CognitoAuth.async_login") as mock_login:
req = await cloud_client.post("/api/cloud/login", json={"invalid": "schema"}) req = await cloud_client.post("/api/cloud/login", json={"invalid": "schema"})
@ -137,7 +142,7 @@ async def test_login_view_invalid_schema(cloud_client):
assert len(mock_login.mock_calls) == 0 assert len(mock_login.mock_calls) == 0
async def test_login_view_request_timeout(cloud_client): async def test_login_view_request_timeout(cloud_client) -> None:
"""Test request timeout while trying to log in.""" """Test request timeout while trying to log in."""
with patch( with patch(
"hass_nabucasa.auth.CognitoAuth.async_login", side_effect=asyncio.TimeoutError "hass_nabucasa.auth.CognitoAuth.async_login", side_effect=asyncio.TimeoutError
@ -149,7 +154,7 @@ async def test_login_view_request_timeout(cloud_client):
assert req.status == HTTPStatus.BAD_GATEWAY assert req.status == HTTPStatus.BAD_GATEWAY
async def test_login_view_invalid_credentials(cloud_client): async def test_login_view_invalid_credentials(cloud_client) -> None:
"""Test logging in with invalid credentials.""" """Test logging in with invalid credentials."""
with patch( with patch(
"hass_nabucasa.auth.CognitoAuth.async_login", side_effect=Unauthenticated "hass_nabucasa.auth.CognitoAuth.async_login", side_effect=Unauthenticated
@ -161,7 +166,7 @@ async def test_login_view_invalid_credentials(cloud_client):
assert req.status == HTTPStatus.UNAUTHORIZED assert req.status == HTTPStatus.UNAUTHORIZED
async def test_login_view_unknown_error(cloud_client): async def test_login_view_unknown_error(cloud_client) -> None:
"""Test unknown error while logging in.""" """Test unknown error while logging in."""
with patch("hass_nabucasa.auth.CognitoAuth.async_login", side_effect=UnknownError): with patch("hass_nabucasa.auth.CognitoAuth.async_login", side_effect=UnknownError):
req = await cloud_client.post( req = await cloud_client.post(
@ -171,7 +176,7 @@ async def test_login_view_unknown_error(cloud_client):
assert req.status == HTTPStatus.BAD_GATEWAY assert req.status == HTTPStatus.BAD_GATEWAY
async def test_logout_view(hass, cloud_client): async def test_logout_view(hass: HomeAssistant, cloud_client) -> None:
"""Test logging out.""" """Test logging out."""
cloud = hass.data["cloud"] = MagicMock() cloud = hass.data["cloud"] = MagicMock()
cloud.logout = AsyncMock(return_value=None) cloud.logout = AsyncMock(return_value=None)
@ -182,7 +187,7 @@ async def test_logout_view(hass, cloud_client):
assert len(cloud.logout.mock_calls) == 1 assert len(cloud.logout.mock_calls) == 1
async def test_logout_view_request_timeout(hass, cloud_client): async def test_logout_view_request_timeout(hass: HomeAssistant, cloud_client) -> None:
"""Test timeout while logging out.""" """Test timeout while logging out."""
cloud = hass.data["cloud"] = MagicMock() cloud = hass.data["cloud"] = MagicMock()
cloud.logout.side_effect = asyncio.TimeoutError cloud.logout.side_effect = asyncio.TimeoutError
@ -190,7 +195,7 @@ async def test_logout_view_request_timeout(hass, cloud_client):
assert req.status == HTTPStatus.BAD_GATEWAY assert req.status == HTTPStatus.BAD_GATEWAY
async def test_logout_view_unknown_error(hass, cloud_client): async def test_logout_view_unknown_error(hass: HomeAssistant, cloud_client) -> None:
"""Test unknown error while logging out.""" """Test unknown error while logging out."""
cloud = hass.data["cloud"] = MagicMock() cloud = hass.data["cloud"] = MagicMock()
cloud.logout.side_effect = UnknownError cloud.logout.side_effect = UnknownError
@ -198,7 +203,7 @@ async def test_logout_view_unknown_error(hass, cloud_client):
assert req.status == HTTPStatus.BAD_GATEWAY assert req.status == HTTPStatus.BAD_GATEWAY
async def test_register_view_no_location(mock_cognito, cloud_client): async def test_register_view_no_location(mock_cognito, cloud_client) -> None:
"""Test register without location.""" """Test register without location."""
with patch( with patch(
"homeassistant.components.cloud.http_api.async_detect_location_info", "homeassistant.components.cloud.http_api.async_detect_location_info",
@ -217,7 +222,7 @@ async def test_register_view_no_location(mock_cognito, cloud_client):
assert call.kwargs["client_metadata"] is None assert call.kwargs["client_metadata"] is None
async def test_register_view_with_location(mock_cognito, cloud_client): async def test_register_view_with_location(mock_cognito, cloud_client) -> None:
"""Test register with location.""" """Test register with location."""
with patch( with patch(
"homeassistant.components.cloud.http_api.async_detect_location_info", "homeassistant.components.cloud.http_api.async_detect_location_info",
@ -254,7 +259,7 @@ async def test_register_view_with_location(mock_cognito, cloud_client):
} }
async def test_register_view_bad_data(mock_cognito, cloud_client): async def test_register_view_bad_data(mock_cognito, cloud_client) -> None:
"""Test logging out.""" """Test logging out."""
req = await cloud_client.post( req = await cloud_client.post(
"/api/cloud/register", json={"email": "hello@bla.com", "not_password": "falcon"} "/api/cloud/register", json={"email": "hello@bla.com", "not_password": "falcon"}
@ -263,7 +268,7 @@ async def test_register_view_bad_data(mock_cognito, cloud_client):
assert len(mock_cognito.logout.mock_calls) == 0 assert len(mock_cognito.logout.mock_calls) == 0
async def test_register_view_request_timeout(mock_cognito, cloud_client): async def test_register_view_request_timeout(mock_cognito, cloud_client) -> None:
"""Test timeout while logging out.""" """Test timeout while logging out."""
mock_cognito.register.side_effect = asyncio.TimeoutError mock_cognito.register.side_effect = asyncio.TimeoutError
req = await cloud_client.post( req = await cloud_client.post(
@ -272,7 +277,7 @@ async def test_register_view_request_timeout(mock_cognito, cloud_client):
assert req.status == HTTPStatus.BAD_GATEWAY assert req.status == HTTPStatus.BAD_GATEWAY
async def test_register_view_unknown_error(mock_cognito, cloud_client): async def test_register_view_unknown_error(mock_cognito, cloud_client) -> None:
"""Test unknown error while logging out.""" """Test unknown error while logging out."""
mock_cognito.register.side_effect = UnknownError mock_cognito.register.side_effect = UnknownError
req = await cloud_client.post( req = await cloud_client.post(
@ -281,7 +286,7 @@ async def test_register_view_unknown_error(mock_cognito, cloud_client):
assert req.status == HTTPStatus.BAD_GATEWAY assert req.status == HTTPStatus.BAD_GATEWAY
async def test_forgot_password_view(mock_cognito, cloud_client): async def test_forgot_password_view(mock_cognito, cloud_client) -> None:
"""Test logging out.""" """Test logging out."""
req = await cloud_client.post( req = await cloud_client.post(
"/api/cloud/forgot_password", json={"email": "hello@bla.com"} "/api/cloud/forgot_password", json={"email": "hello@bla.com"}
@ -290,7 +295,7 @@ async def test_forgot_password_view(mock_cognito, cloud_client):
assert len(mock_cognito.initiate_forgot_password.mock_calls) == 1 assert len(mock_cognito.initiate_forgot_password.mock_calls) == 1
async def test_forgot_password_view_bad_data(mock_cognito, cloud_client): async def test_forgot_password_view_bad_data(mock_cognito, cloud_client) -> None:
"""Test logging out.""" """Test logging out."""
req = await cloud_client.post( req = await cloud_client.post(
"/api/cloud/forgot_password", json={"not_email": "hello@bla.com"} "/api/cloud/forgot_password", json={"not_email": "hello@bla.com"}
@ -299,7 +304,7 @@ async def test_forgot_password_view_bad_data(mock_cognito, cloud_client):
assert len(mock_cognito.initiate_forgot_password.mock_calls) == 0 assert len(mock_cognito.initiate_forgot_password.mock_calls) == 0
async def test_forgot_password_view_request_timeout(mock_cognito, cloud_client): async def test_forgot_password_view_request_timeout(mock_cognito, cloud_client) -> None:
"""Test timeout while logging out.""" """Test timeout while logging out."""
mock_cognito.initiate_forgot_password.side_effect = asyncio.TimeoutError mock_cognito.initiate_forgot_password.side_effect = asyncio.TimeoutError
req = await cloud_client.post( req = await cloud_client.post(
@ -308,7 +313,7 @@ async def test_forgot_password_view_request_timeout(mock_cognito, cloud_client):
assert req.status == HTTPStatus.BAD_GATEWAY assert req.status == HTTPStatus.BAD_GATEWAY
async def test_forgot_password_view_unknown_error(mock_cognito, cloud_client): async def test_forgot_password_view_unknown_error(mock_cognito, cloud_client) -> None:
"""Test unknown error while logging out.""" """Test unknown error while logging out."""
mock_cognito.initiate_forgot_password.side_effect = UnknownError mock_cognito.initiate_forgot_password.side_effect = UnknownError
req = await cloud_client.post( req = await cloud_client.post(
@ -317,7 +322,7 @@ async def test_forgot_password_view_unknown_error(mock_cognito, cloud_client):
assert req.status == HTTPStatus.BAD_GATEWAY assert req.status == HTTPStatus.BAD_GATEWAY
async def test_forgot_password_view_aiohttp_error(mock_cognito, cloud_client): async def test_forgot_password_view_aiohttp_error(mock_cognito, cloud_client) -> None:
"""Test unknown error while logging out.""" """Test unknown error while logging out."""
mock_cognito.initiate_forgot_password.side_effect = aiohttp.ClientResponseError( mock_cognito.initiate_forgot_password.side_effect = aiohttp.ClientResponseError(
Mock(), Mock() Mock(), Mock()
@ -328,7 +333,7 @@ async def test_forgot_password_view_aiohttp_error(mock_cognito, cloud_client):
assert req.status == HTTPStatus.INTERNAL_SERVER_ERROR assert req.status == HTTPStatus.INTERNAL_SERVER_ERROR
async def test_resend_confirm_view(mock_cognito, cloud_client): async def test_resend_confirm_view(mock_cognito, cloud_client) -> None:
"""Test logging out.""" """Test logging out."""
req = await cloud_client.post( req = await cloud_client.post(
"/api/cloud/resend_confirm", json={"email": "hello@bla.com"} "/api/cloud/resend_confirm", json={"email": "hello@bla.com"}
@ -337,7 +342,7 @@ async def test_resend_confirm_view(mock_cognito, cloud_client):
assert len(mock_cognito.client.resend_confirmation_code.mock_calls) == 1 assert len(mock_cognito.client.resend_confirmation_code.mock_calls) == 1
async def test_resend_confirm_view_bad_data(mock_cognito, cloud_client): async def test_resend_confirm_view_bad_data(mock_cognito, cloud_client) -> None:
"""Test logging out.""" """Test logging out."""
req = await cloud_client.post( req = await cloud_client.post(
"/api/cloud/resend_confirm", json={"not_email": "hello@bla.com"} "/api/cloud/resend_confirm", json={"not_email": "hello@bla.com"}
@ -346,7 +351,7 @@ async def test_resend_confirm_view_bad_data(mock_cognito, cloud_client):
assert len(mock_cognito.client.resend_confirmation_code.mock_calls) == 0 assert len(mock_cognito.client.resend_confirmation_code.mock_calls) == 0
async def test_resend_confirm_view_request_timeout(mock_cognito, cloud_client): async def test_resend_confirm_view_request_timeout(mock_cognito, cloud_client) -> None:
"""Test timeout while logging out.""" """Test timeout while logging out."""
mock_cognito.client.resend_confirmation_code.side_effect = asyncio.TimeoutError mock_cognito.client.resend_confirmation_code.side_effect = asyncio.TimeoutError
req = await cloud_client.post( req = await cloud_client.post(
@ -355,7 +360,7 @@ async def test_resend_confirm_view_request_timeout(mock_cognito, cloud_client):
assert req.status == HTTPStatus.BAD_GATEWAY assert req.status == HTTPStatus.BAD_GATEWAY
async def test_resend_confirm_view_unknown_error(mock_cognito, cloud_client): async def test_resend_confirm_view_unknown_error(mock_cognito, cloud_client) -> None:
"""Test unknown error while logging out.""" """Test unknown error while logging out."""
mock_cognito.client.resend_confirmation_code.side_effect = UnknownError mock_cognito.client.resend_confirmation_code.side_effect = UnknownError
req = await cloud_client.post( req = await cloud_client.post(
@ -365,8 +370,11 @@ async def test_resend_confirm_view_unknown_error(mock_cognito, cloud_client):
async def test_websocket_status( async def test_websocket_status(
hass, hass_ws_client, mock_cloud_fixture, mock_cloud_login hass: HomeAssistant,
): hass_ws_client: WebSocketGenerator,
mock_cloud_fixture,
mock_cloud_login,
) -> None:
"""Test querying the status.""" """Test querying the status."""
hass.data[DOMAIN].iot.state = STATE_CONNECTED hass.data[DOMAIN].iot.state = STATE_CONNECTED
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
@ -443,8 +451,12 @@ async def test_websocket_status_not_logged_in(
async def test_websocket_subscription_info( async def test_websocket_subscription_info(
hass, hass_ws_client, aioclient_mock, mock_auth, mock_cloud_login hass: HomeAssistant,
): hass_ws_client: WebSocketGenerator,
aioclient_mock: AiohttpClientMocker,
mock_auth,
mock_cloud_login,
) -> None:
"""Test querying the status and connecting because valid account.""" """Test querying the status and connecting because valid account."""
aioclient_mock.get(SUBSCRIPTION_INFO_URL, json={"provider": "stripe"}) aioclient_mock.get(SUBSCRIPTION_INFO_URL, json={"provider": "stripe"})
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
@ -457,8 +469,12 @@ async def test_websocket_subscription_info(
async def test_websocket_subscription_fail( async def test_websocket_subscription_fail(
hass, hass_ws_client, aioclient_mock, mock_auth, mock_cloud_login hass: HomeAssistant,
): hass_ws_client: WebSocketGenerator,
aioclient_mock: AiohttpClientMocker,
mock_auth,
mock_cloud_login,
) -> None:
"""Test querying the status.""" """Test querying the status."""
aioclient_mock.get(SUBSCRIPTION_INFO_URL, status=HTTPStatus.INTERNAL_SERVER_ERROR) aioclient_mock.get(SUBSCRIPTION_INFO_URL, status=HTTPStatus.INTERNAL_SERVER_ERROR)
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
@ -486,8 +502,12 @@ async def test_websocket_subscription_not_logged_in(
async def test_websocket_update_preferences( async def test_websocket_update_preferences(
hass, hass_ws_client, aioclient_mock, setup_api, mock_cloud_login hass: HomeAssistant,
): hass_ws_client: WebSocketGenerator,
aioclient_mock: AiohttpClientMocker,
setup_api,
mock_cloud_login,
) -> None:
"""Test updating preference.""" """Test updating preference."""
assert setup_api.google_enabled assert setup_api.google_enabled
assert setup_api.alexa_enabled assert setup_api.alexa_enabled
@ -517,8 +537,12 @@ async def test_websocket_update_preferences(
async def test_websocket_update_preferences_alexa_report_state( async def test_websocket_update_preferences_alexa_report_state(
hass, hass_ws_client, aioclient_mock, setup_api, mock_cloud_login hass: HomeAssistant,
): hass_ws_client: WebSocketGenerator,
aioclient_mock: AiohttpClientMocker,
setup_api,
mock_cloud_login,
) -> None:
"""Test updating alexa_report_state sets alexa authorized.""" """Test updating alexa_report_state sets alexa authorized."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
@ -541,8 +565,12 @@ async def test_websocket_update_preferences_alexa_report_state(
async def test_websocket_update_preferences_require_relink( async def test_websocket_update_preferences_require_relink(
hass, hass_ws_client, aioclient_mock, setup_api, mock_cloud_login hass: HomeAssistant,
): hass_ws_client: WebSocketGenerator,
aioclient_mock: AiohttpClientMocker,
setup_api,
mock_cloud_login,
) -> None:
"""Test updating preference requires relink.""" """Test updating preference requires relink."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
@ -567,8 +595,12 @@ async def test_websocket_update_preferences_require_relink(
async def test_websocket_update_preferences_no_token( async def test_websocket_update_preferences_no_token(
hass, hass_ws_client, aioclient_mock, setup_api, mock_cloud_login hass: HomeAssistant,
): hass_ws_client: WebSocketGenerator,
aioclient_mock: AiohttpClientMocker,
setup_api,
mock_cloud_login,
) -> None:
"""Test updating preference no token available.""" """Test updating preference no token available."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
@ -592,7 +624,9 @@ async def test_websocket_update_preferences_no_token(
assert response["error"]["code"] == "alexa_relink" assert response["error"]["code"] == "alexa_relink"
async def test_enabling_webhook(hass, hass_ws_client, setup_api, mock_cloud_login): async def test_enabling_webhook(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, setup_api, mock_cloud_login
) -> None:
"""Test we call right code to enable webhooks.""" """Test we call right code to enable webhooks."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
with patch( with patch(
@ -608,7 +642,9 @@ async def test_enabling_webhook(hass, hass_ws_client, setup_api, mock_cloud_logi
assert mock_enable.mock_calls[0][1][0] == "mock-webhook-id" assert mock_enable.mock_calls[0][1][0] == "mock-webhook-id"
async def test_disabling_webhook(hass, hass_ws_client, setup_api, mock_cloud_login): async def test_disabling_webhook(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, setup_api, mock_cloud_login
) -> None:
"""Test we call right code to disable webhooks.""" """Test we call right code to disable webhooks."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
with patch("hass_nabucasa.cloudhooks.Cloudhooks.async_delete") as mock_disable: with patch("hass_nabucasa.cloudhooks.Cloudhooks.async_delete") as mock_disable:
@ -622,7 +658,9 @@ async def test_disabling_webhook(hass, hass_ws_client, setup_api, mock_cloud_log
assert mock_disable.mock_calls[0][1][0] == "mock-webhook-id" assert mock_disable.mock_calls[0][1][0] == "mock-webhook-id"
async def test_enabling_remote(hass, hass_ws_client, setup_api, mock_cloud_login): async def test_enabling_remote(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, setup_api, mock_cloud_login
) -> None:
"""Test we call right code to enable remote UI.""" """Test we call right code to enable remote UI."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
cloud = hass.data[DOMAIN] cloud = hass.data[DOMAIN]
@ -644,7 +682,9 @@ async def test_enabling_remote(hass, hass_ws_client, setup_api, mock_cloud_login
assert len(mock_disconnect.mock_calls) == 1 assert len(mock_disconnect.mock_calls) == 1
async def test_list_google_entities(hass, hass_ws_client, setup_api, mock_cloud_login): async def test_list_google_entities(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, setup_api, mock_cloud_login
) -> None:
"""Test that we can list Google entities.""" """Test that we can list Google entities."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
entity = GoogleEntity( entity = GoogleEntity(
@ -676,7 +716,9 @@ async def test_list_google_entities(hass, hass_ws_client, setup_api, mock_cloud_
} }
async def test_update_google_entity(hass, hass_ws_client, setup_api, mock_cloud_login): async def test_update_google_entity(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, setup_api, mock_cloud_login
) -> None:
"""Test that we can update config of a Google entity.""" """Test that we can update config of a Google entity."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
await client.send_json( await client.send_json(
@ -721,7 +763,9 @@ async def test_update_google_entity(hass, hass_ws_client, setup_api, mock_cloud_
} }
async def test_list_alexa_entities(hass, hass_ws_client, setup_api, mock_cloud_login): async def test_list_alexa_entities(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, setup_api, mock_cloud_login
) -> None:
"""Test that we can list Alexa entities.""" """Test that we can list Alexa entities."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
entity = LightCapabilities( entity = LightCapabilities(
@ -743,7 +787,9 @@ async def test_list_alexa_entities(hass, hass_ws_client, setup_api, mock_cloud_l
} }
async def test_update_alexa_entity(hass, hass_ws_client, setup_api, mock_cloud_login): async def test_update_alexa_entity(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, setup_api, mock_cloud_login
) -> None:
"""Test that we can update config of an Alexa entity.""" """Test that we can update config of an Alexa entity."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
await client.send_json( await client.send_json(
@ -776,8 +822,8 @@ async def test_update_alexa_entity(hass, hass_ws_client, setup_api, mock_cloud_l
async def test_sync_alexa_entities_timeout( async def test_sync_alexa_entities_timeout(
hass, hass_ws_client, setup_api, mock_cloud_login hass: HomeAssistant, hass_ws_client: WebSocketGenerator, setup_api, mock_cloud_login
): ) -> None:
"""Test that timeout syncing Alexa entities.""" """Test that timeout syncing Alexa entities."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
with patch( with patch(
@ -795,8 +841,8 @@ async def test_sync_alexa_entities_timeout(
async def test_sync_alexa_entities_no_token( async def test_sync_alexa_entities_no_token(
hass, hass_ws_client, setup_api, mock_cloud_login hass: HomeAssistant, hass_ws_client: WebSocketGenerator, setup_api, mock_cloud_login
): ) -> None:
"""Test sync Alexa entities when we have no token.""" """Test sync Alexa entities when we have no token."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
with patch( with patch(
@ -814,8 +860,8 @@ async def test_sync_alexa_entities_no_token(
async def test_enable_alexa_state_report_fail( async def test_enable_alexa_state_report_fail(
hass, hass_ws_client, setup_api, mock_cloud_login hass: HomeAssistant, hass_ws_client: WebSocketGenerator, setup_api, mock_cloud_login
): ) -> None:
"""Test enable Alexa entities state reporting when no token available.""" """Test enable Alexa entities state reporting when no token available."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
with patch( with patch(
@ -832,7 +878,9 @@ async def test_enable_alexa_state_report_fail(
assert response["error"]["code"] == "alexa_relink" assert response["error"]["code"] == "alexa_relink"
async def test_thingtalk_convert(hass, hass_ws_client, setup_api): async def test_thingtalk_convert(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, setup_api
) -> None:
"""Test that we can convert a query.""" """Test that we can convert a query."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
@ -849,7 +897,9 @@ async def test_thingtalk_convert(hass, hass_ws_client, setup_api):
assert response["result"] == {"hello": "world"} assert response["result"] == {"hello": "world"}
async def test_thingtalk_convert_timeout(hass, hass_ws_client, setup_api): async def test_thingtalk_convert_timeout(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, setup_api
) -> None:
"""Test that we can convert a query.""" """Test that we can convert a query."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
@ -866,7 +916,9 @@ async def test_thingtalk_convert_timeout(hass, hass_ws_client, setup_api):
assert response["error"]["code"] == "timeout" assert response["error"]["code"] == "timeout"
async def test_thingtalk_convert_internal(hass, hass_ws_client, setup_api): async def test_thingtalk_convert_internal(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, setup_api
) -> None:
"""Test that we can convert a query.""" """Test that we can convert a query."""
client = await hass_ws_client(hass) client = await hass_ws_client(hass)
@ -884,7 +936,9 @@ async def test_thingtalk_convert_internal(hass, hass_ws_client, setup_api):
assert response["error"]["message"] == "Did not understand" assert response["error"]["message"] == "Did not understand"
async def test_tts_info(hass, hass_ws_client, setup_api): async def test_tts_info(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, setup_api
) -> None:
"""Test that we can get TTS info.""" """Test that we can get TTS info."""
# Verify the format is as expected # Verify the format is as expected
assert voice.MAP_VOICE[("en-US", voice.Gender.FEMALE)] == "JennyNeural" assert voice.MAP_VOICE[("en-US", voice.Gender.FEMALE)] == "JennyNeural"

View File

@ -11,6 +11,8 @@ from homeassistant.core import Context, HomeAssistant
from homeassistant.exceptions import Unauthorized from homeassistant.exceptions import Unauthorized
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import MockUser
async def test_constructor_loads_info_from_config(hass: HomeAssistant) -> None: async def test_constructor_loads_info_from_config(hass: HomeAssistant) -> None:
"""Test non-dev mode loads info from SERVERS constant.""" """Test non-dev mode loads info from SERVERS constant."""
@ -51,7 +53,9 @@ async def test_constructor_loads_info_from_config(hass: HomeAssistant) -> None:
assert cl.remotestate_server == "test-remotestate-server" assert cl.remotestate_server == "test-remotestate-server"
async def test_remote_services(hass, mock_cloud_fixture, hass_read_only_user): async def test_remote_services(
hass: HomeAssistant, mock_cloud_fixture, hass_read_only_user: MockUser
) -> None:
"""Setup cloud component and test services.""" """Setup cloud component and test services."""
cloud = hass.data[DOMAIN] cloud = hass.data[DOMAIN]
@ -92,7 +96,7 @@ async def test_remote_services(hass, mock_cloud_fixture, hass_read_only_user):
assert mock_disconnect.called is False assert mock_disconnect.called is False
async def test_startup_shutdown_events(hass, mock_cloud_fixture): async def test_startup_shutdown_events(hass: HomeAssistant, mock_cloud_fixture) -> None:
"""Test if the cloud will start on startup event.""" """Test if the cloud will start on startup event."""
with patch("hass_nabucasa.Cloud.stop") as mock_stop: with patch("hass_nabucasa.Cloud.stop") as mock_stop:
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
@ -101,7 +105,7 @@ async def test_startup_shutdown_events(hass, mock_cloud_fixture):
assert mock_stop.called assert mock_stop.called
async def test_setup_existing_cloud_user(hass, hass_storage): async def test_setup_existing_cloud_user(hass: HomeAssistant, hass_storage) -> None:
"""Test setup with API push default data.""" """Test setup with API push default data."""
user = await hass.auth.async_create_system_user("Cloud test") user = await hass.auth.async_create_system_user("Cloud test")
hass_storage[STORAGE_KEY] = {"version": 1, "data": {"cloud_user": user.id}} hass_storage[STORAGE_KEY] = {"version": 1, "data": {"cloud_user": user.id}}
@ -125,7 +129,7 @@ async def test_setup_existing_cloud_user(hass, hass_storage):
assert hass_storage[STORAGE_KEY]["data"]["cloud_user"] == user.id assert hass_storage[STORAGE_KEY]["data"]["cloud_user"] == user.id
async def test_on_connect(hass, mock_cloud_fixture): async def test_on_connect(hass: HomeAssistant, mock_cloud_fixture) -> None:
"""Test cloud on connect triggers.""" """Test cloud on connect triggers."""
cl = hass.data["cloud"] cl = hass.data["cloud"]
@ -165,7 +169,7 @@ async def test_on_connect(hass, mock_cloud_fixture):
assert cloud_states[-1] == cloud.CloudConnectionState.CLOUD_DISCONNECTED assert cloud_states[-1] == cloud.CloudConnectionState.CLOUD_DISCONNECTED
async def test_remote_ui_url(hass, mock_cloud_fixture): async def test_remote_ui_url(hass: HomeAssistant, mock_cloud_fixture) -> None:
"""Test getting remote ui url.""" """Test getting remote ui url."""
cl = hass.data["cloud"] cl = hass.data["cloud"]

View File

@ -40,7 +40,7 @@ async def test_set_username_migration(hass: HomeAssistant) -> None:
assert not prefs.google_enabled assert not prefs.google_enabled
async def test_set_new_username(hass, hass_storage): async def test_set_new_username(hass: HomeAssistant, hass_storage) -> None:
"""Test if setting new username returns true.""" """Test if setting new username returns true."""
hass_storage[STORAGE_KEY] = {"version": 1, "data": {"username": "old-user"}} hass_storage[STORAGE_KEY] = {"version": 1, "data": {"username": "old-user"}}
@ -52,7 +52,7 @@ async def test_set_new_username(hass, hass_storage):
assert await prefs.async_set_username("new-user") assert await prefs.async_set_username("new-user")
async def test_load_invalid_cloud_user(hass, hass_storage): async def test_load_invalid_cloud_user(hass: HomeAssistant, hass_storage) -> None:
"""Test loading cloud user with invalid storage.""" """Test loading cloud user with invalid storage."""
hass_storage[STORAGE_KEY] = {"version": 1, "data": {"cloud_user": "non-existing"}} hass_storage[STORAGE_KEY] = {"version": 1, "data": {"cloud_user": "non-existing"}}
@ -71,7 +71,7 @@ async def test_load_invalid_cloud_user(hass, hass_storage):
assert cloud_user.groups[0].id == GROUP_ID_ADMIN assert cloud_user.groups[0].id == GROUP_ID_ADMIN
async def test_setup_remove_cloud_user(hass, hass_storage): async def test_setup_remove_cloud_user(hass: HomeAssistant, hass_storage) -> None:
"""Test creating and removing cloud user.""" """Test creating and removing cloud user."""
hass_storage[STORAGE_KEY] = {"version": 1, "data": {"cloud_user": None}} hass_storage[STORAGE_KEY] = {"version": 1, "data": {"cloud_user": None}}

View File

@ -21,7 +21,7 @@ from tests.typing import ClientSessionGenerator
async def test_do_not_create_repair_issues_at_startup_if_not_logged_in( async def test_do_not_create_repair_issues_at_startup_if_not_logged_in(
hass: HomeAssistant, hass: HomeAssistant,
): ) -> None:
"""Test that we create repair issue at startup if we are logged in.""" """Test that we create repair issue at startup if we are logged in."""
issue_registry: ir.IssueRegistry = ir.async_get(hass) issue_registry: ir.IssueRegistry = ir.async_get(hass)
@ -61,7 +61,7 @@ async def test_create_repair_issues_at_startup_if_logged_in(
async def test_legacy_subscription_delete_issue_if_no_longer_legacy( async def test_legacy_subscription_delete_issue_if_no_longer_legacy(
hass: HomeAssistant, hass: HomeAssistant,
): ) -> None:
"""Test that we delete the legacy subscription issue if no longer legacy.""" """Test that we delete the legacy subscription issue if no longer legacy."""
issue_registry: ir.IssueRegistry = ir.async_get(hass) issue_registry: ir.IssueRegistry = ir.async_get(hass)
cloud_repairs.async_manage_legacy_subscription_issue(hass, {"provider": "legacy"}) cloud_repairs.async_manage_legacy_subscription_issue(hass, {"provider": "legacy"})

View File

@ -29,7 +29,7 @@ async def test_fetching_subscription_with_timeout_error(
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
mocked_cloud: Cloud, mocked_cloud: Cloud,
): ) -> None:
"""Test that we handle timeout error.""" """Test that we handle timeout error."""
aioclient_mock.get( aioclient_mock.get(
"https://accounts.nabucasa.com/payments/subscription_info", "https://accounts.nabucasa.com/payments/subscription_info",
@ -47,7 +47,7 @@ async def test_migrate_paypal_agreement_with_timeout_error(
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
mocked_cloud: Cloud, mocked_cloud: Cloud,
): ) -> None:
"""Test that we handle timeout error.""" """Test that we handle timeout error."""
aioclient_mock.post( aioclient_mock.post(
"https://accounts.nabucasa.com/payments/migrate_paypal_agreement", "https://accounts.nabucasa.com/payments/migrate_paypal_agreement",

View File

@ -6,6 +6,7 @@ import pytest
import voluptuous as vol import voluptuous as vol
from homeassistant.components.cloud import const, tts from homeassistant.components.cloud import const, tts
from homeassistant.core import HomeAssistant
@pytest.fixture @pytest.fixture
@ -41,7 +42,9 @@ def test_schema() -> None:
tts.PLATFORM_SCHEMA({"platform": "cloud"}) tts.PLATFORM_SCHEMA({"platform": "cloud"})
async def test_prefs_default_voice(hass, cloud_with_prefs, cloud_prefs): async def test_prefs_default_voice(
hass: HomeAssistant, cloud_with_prefs, cloud_prefs
) -> None:
"""Test cloud provider uses the preferences.""" """Test cloud provider uses the preferences."""
assert cloud_prefs.tts_default_voice == ("en-US", "female") assert cloud_prefs.tts_default_voice == ("en-US", "female")
@ -68,7 +71,7 @@ async def test_prefs_default_voice(hass, cloud_with_prefs, cloud_prefs):
assert provider_conf.default_options == {"gender": "female"} assert provider_conf.default_options == {"gender": "female"}
async def test_provider_properties(cloud_with_prefs): async def test_provider_properties(cloud_with_prefs) -> None:
"""Test cloud provider.""" """Test cloud provider."""
provider = await tts.async_get_engine( provider = await tts.async_get_engine(
Mock(data={const.DOMAIN: cloud_with_prefs}), None, {} Mock(data={const.DOMAIN: cloud_with_prefs}), None, {}
@ -77,7 +80,7 @@ async def test_provider_properties(cloud_with_prefs):
assert "nl-NL" in provider.supported_languages assert "nl-NL" in provider.supported_languages
async def test_get_tts_audio(cloud_with_prefs): async def test_get_tts_audio(cloud_with_prefs) -> None:
"""Test cloud provider.""" """Test cloud provider."""
provider = await tts.async_get_engine( provider = await tts.async_get_engine(
Mock(data={const.DOMAIN: cloud_with_prefs}), None, {} Mock(data={const.DOMAIN: cloud_with_prefs}), None, {}

View File

@ -22,7 +22,7 @@ from . import (
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
async def test_user_form(hass, cfupdate_flow): async def test_user_form(hass: HomeAssistant, cfupdate_flow) -> None:
"""Test we get the user initiated form.""" """Test we get the user initiated form."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
@ -73,7 +73,7 @@ async def test_user_form(hass, cfupdate_flow):
assert len(mock_setup_entry.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
async def test_user_form_cannot_connect(hass, cfupdate_flow): async def test_user_form_cannot_connect(hass: HomeAssistant, cfupdate_flow) -> None:
"""Test we handle cannot connect error.""" """Test we handle cannot connect error."""
instance = cfupdate_flow.return_value instance = cfupdate_flow.return_value
@ -91,7 +91,7 @@ async def test_user_form_cannot_connect(hass, cfupdate_flow):
assert result["errors"] == {"base": "cannot_connect"} assert result["errors"] == {"base": "cannot_connect"}
async def test_user_form_invalid_auth(hass, cfupdate_flow): async def test_user_form_invalid_auth(hass: HomeAssistant, cfupdate_flow) -> None:
"""Test we handle invalid auth error.""" """Test we handle invalid auth error."""
instance = cfupdate_flow.return_value instance = cfupdate_flow.return_value
@ -109,7 +109,7 @@ async def test_user_form_invalid_auth(hass, cfupdate_flow):
assert result["errors"] == {"base": "invalid_auth"} assert result["errors"] == {"base": "invalid_auth"}
async def test_user_form_invalid_zone(hass, cfupdate_flow): async def test_user_form_invalid_zone(hass: HomeAssistant, cfupdate_flow) -> None:
"""Test we handle invalid zone error.""" """Test we handle invalid zone error."""
instance = cfupdate_flow.return_value instance = cfupdate_flow.return_value
@ -127,7 +127,9 @@ async def test_user_form_invalid_zone(hass, cfupdate_flow):
assert result["errors"] == {"base": "invalid_zone"} assert result["errors"] == {"base": "invalid_zone"}
async def test_user_form_unexpected_exception(hass, cfupdate_flow): async def test_user_form_unexpected_exception(
hass: HomeAssistant, cfupdate_flow
) -> None:
"""Test we handle unexpected exception.""" """Test we handle unexpected exception."""
instance = cfupdate_flow.return_value instance = cfupdate_flow.return_value
@ -159,7 +161,7 @@ async def test_user_form_single_instance_allowed(hass: HomeAssistant) -> None:
assert result["reason"] == "single_instance_allowed" assert result["reason"] == "single_instance_allowed"
async def test_reauth_flow(hass, cfupdate_flow): async def test_reauth_flow(hass: HomeAssistant, cfupdate_flow) -> None:
"""Test the reauthentication configuration flow.""" """Test the reauthentication configuration flow."""
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_CONFIG) entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_CONFIG)
entry.add_to_hass(hass) entry.add_to_hass(hass)

View File

@ -10,6 +10,7 @@ import pytest
from homeassistant.components.cloudflare.const import DOMAIN, SERVICE_UPDATE_RECORDS from homeassistant.components.cloudflare.const import DOMAIN, SERVICE_UPDATE_RECORDS
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.util.location import LocationInfo from homeassistant.util.location import LocationInfo
@ -18,7 +19,7 @@ from . import ENTRY_CONFIG, init_integration
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
async def test_unload_entry(hass, cfupdate): async def test_unload_entry(hass: HomeAssistant, cfupdate) -> None:
"""Test successful unload of entry.""" """Test successful unload of entry."""
entry = await init_integration(hass) entry = await init_integration(hass)
@ -39,7 +40,9 @@ async def test_unload_entry(hass, cfupdate):
CloudflareZoneException(), CloudflareZoneException(),
), ),
) )
async def test_async_setup_raises_entry_not_ready(hass, cfupdate, side_effect): async def test_async_setup_raises_entry_not_ready(
hass: HomeAssistant, cfupdate, side_effect
) -> None:
"""Test that it throws ConfigEntryNotReady when exception occurs during setup.""" """Test that it throws ConfigEntryNotReady when exception occurs during setup."""
instance = cfupdate.return_value instance = cfupdate.return_value
@ -52,7 +55,9 @@ async def test_async_setup_raises_entry_not_ready(hass, cfupdate, side_effect):
assert entry.state is ConfigEntryState.SETUP_RETRY assert entry.state is ConfigEntryState.SETUP_RETRY
async def test_async_setup_raises_entry_auth_failed(hass, cfupdate): async def test_async_setup_raises_entry_auth_failed(
hass: HomeAssistant, cfupdate
) -> None:
"""Test that it throws ConfigEntryAuthFailed when exception occurs during setup.""" """Test that it throws ConfigEntryAuthFailed when exception occurs during setup."""
instance = cfupdate.return_value instance = cfupdate.return_value
@ -76,7 +81,7 @@ async def test_async_setup_raises_entry_auth_failed(hass, cfupdate):
assert flow["context"]["entry_id"] == entry.entry_id assert flow["context"]["entry_id"] == entry.entry_id
async def test_integration_services(hass, cfupdate): async def test_integration_services(hass: HomeAssistant, cfupdate) -> None:
"""Test integration services.""" """Test integration services."""
instance = cfupdate.return_value instance = cfupdate.return_value
@ -110,7 +115,7 @@ async def test_integration_services(hass, cfupdate):
instance.update_records.assert_called_once() instance.update_records.assert_called_once()
async def test_integration_services_with_issue(hass, cfupdate): async def test_integration_services_with_issue(hass: HomeAssistant, cfupdate) -> None:
"""Test integration services with issue.""" """Test integration services with issue."""
instance = cfupdate.return_value instance = cfupdate.return_value

View File

@ -1,7 +1,8 @@
"""Test the Coinbase diagnostics.""" """Test the Coinbase diagnostics."""
from unittest.mock import patch from unittest.mock import patch
from homeassistant.core import HomeAssistant
from .common import ( from .common import (
init_mock_coinbase, init_mock_coinbase,
mock_get_current_user, mock_get_current_user,
@ -14,7 +15,9 @@ from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator from tests.typing import ClientSessionGenerator
async def test_entry_diagnostics(hass, hass_client: ClientSessionGenerator): async def test_entry_diagnostics(
hass: HomeAssistant, hass_client: ClientSessionGenerator
) -> None:
"""Test we handle a and redact a diagnostics request.""" """Test we handle a and redact a diagnostics request."""
with patch( with patch(

View File

@ -49,7 +49,7 @@ async def test_unload_entry(hass: HomeAssistant) -> None:
assert not hass.data.get(DOMAIN) assert not hass.data.get(DOMAIN)
async def test_option_updates(hass: HomeAssistant): async def test_option_updates(hass: HomeAssistant) -> None:
"""Test handling option updates.""" """Test handling option updates."""
with patch( with patch(
@ -127,7 +127,7 @@ async def test_option_updates(hass: HomeAssistant):
assert rates == [GOOD_EXCHANGE_RATE] assert rates == [GOOD_EXCHANGE_RATE]
async def test_ignore_vaults_wallets(hass: HomeAssistant): async def test_ignore_vaults_wallets(hass: HomeAssistant) -> None:
"""Test vaults are ignored in wallet sensors.""" """Test vaults are ignored in wallet sensors."""
with patch( with patch(