Add typing to tests with single hass argument (#87631)

This commit is contained in:
epenet 2023-02-07 15:01:16 +01:00 committed by GitHub
parent fe9f6823c3
commit 59ca7780fa
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
33 changed files with 104 additions and 75 deletions

View file

@ -7,6 +7,7 @@ from homeassistant.auth.permissions.entities import (
compile_entities, compile_entities,
) )
from homeassistant.auth.permissions.models import PermissionLookup from homeassistant.auth.permissions.models import PermissionLookup
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceEntry from homeassistant.helpers.device_registry import DeviceEntry
from homeassistant.helpers.entity_registry import RegistryEntry from homeassistant.helpers.entity_registry import RegistryEntry
@ -149,7 +150,7 @@ def test_entities_all_control() -> None:
assert compiled("switch.kitchen", "control") is True assert compiled("switch.kitchen", "control") is True
def test_entities_device_id_boolean(hass): def test_entities_device_id_boolean(hass: HomeAssistant) -> None:
"""Test entity ID policy applying control on device id.""" """Test entity ID policy applying control on device id."""
entity_registry = mock_registry( entity_registry = mock_registry(
hass, hass,
@ -189,7 +190,7 @@ def test_entities_areas_true() -> None:
assert compiled("light.kitchen", "read") is True assert compiled("light.kitchen", "read") is True
def test_entities_areas_area_true(hass): def test_entities_areas_area_true(hass: HomeAssistant) -> None:
"""Test entity ID policy for areas with specific area.""" """Test entity ID policy for areas with specific area."""
entity_registry = mock_registry( entity_registry = mock_registry(
hass, hass,

View file

@ -12,7 +12,7 @@ from homeassistant.components.media_player import MediaPlayerEntityFeature
import homeassistant.components.vacuum as vacuum import homeassistant.components.vacuum as vacuum
from homeassistant.config import async_process_ha_core_config from homeassistant.config import async_process_ha_core_config
from homeassistant.const import STATE_UNKNOWN, UnitOfTemperature from homeassistant.const import STATE_UNKNOWN, UnitOfTemperature
from homeassistant.core import Context from homeassistant.core import Context, HomeAssistant
from homeassistant.helpers import entityfilter from homeassistant.helpers import entityfilter
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM
@ -54,7 +54,7 @@ async def mock_stream(hass):
await hass.async_block_till_done() await hass.async_block_till_done()
def test_create_api_message_defaults(hass): def test_create_api_message_defaults(hass: HomeAssistant) -> None:
"""Create an API message response of a request with defaults.""" """Create an API message response of a request with defaults."""
request = get_new_request("Alexa.PowerController", "TurnOn", "switch#xy") request = get_new_request("Alexa.PowerController", "TurnOn", "switch#xy")
directive_header = request["directive"]["header"] directive_header = request["directive"]["header"]

View file

@ -41,6 +41,7 @@ from homeassistant.const import (
STATE_OFF, STATE_OFF,
STATE_ON, STATE_ON,
) )
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from homeassistant.util.unit_system import METRIC_SYSTEM from homeassistant.util.unit_system import METRIC_SYSTEM
@ -57,7 +58,7 @@ async def setup_demo_climate(hass):
await hass.async_block_till_done() await hass.async_block_till_done()
def test_setup_params(hass): def test_setup_params(hass: HomeAssistant) -> None:
"""Test the initial parameters.""" """Test the initial parameters."""
state = hass.states.get(ENTITY_CLIMATE) state = hass.states.get(ENTITY_CLIMATE)
assert state.state == HVACMode.COOL assert state.state == HVACMode.COOL
@ -78,7 +79,7 @@ def test_setup_params(hass):
] ]
def test_default_setup_params(hass): def test_default_setup_params(hass: HomeAssistant) -> None:
"""Test the setup with default parameters.""" """Test the setup with default parameters."""
state = hass.states.get(ENTITY_CLIMATE) state = hass.states.get(ENTITY_CLIMATE)
assert state.attributes.get(ATTR_MIN_TEMP) == 7 assert state.attributes.get(ATTR_MIN_TEMP) == 7

View file

@ -21,6 +21,7 @@ from homeassistant.const import (
STATE_OFF, STATE_OFF,
STATE_ON, STATE_ON,
) )
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
ENTITY_DEHUMIDIFIER = "humidifier.dehumidifier" ENTITY_DEHUMIDIFIER = "humidifier.dehumidifier"
@ -37,14 +38,14 @@ async def setup_demo_humidifier(hass):
await hass.async_block_till_done() await hass.async_block_till_done()
def test_setup_params(hass): def test_setup_params(hass: HomeAssistant) -> None:
"""Test the initial parameters.""" """Test the initial parameters."""
state = hass.states.get(ENTITY_DEHUMIDIFIER) state = hass.states.get(ENTITY_DEHUMIDIFIER)
assert state.state == STATE_ON assert state.state == STATE_ON
assert state.attributes.get(ATTR_HUMIDITY) == 54 assert state.attributes.get(ATTR_HUMIDITY) == 54
def test_default_setup_params(hass): def test_default_setup_params(hass: HomeAssistant) -> None:
"""Test the setup with default parameters.""" """Test the setup with default parameters."""
state = hass.states.get(ENTITY_DEHUMIDIFIER) state = hass.states.get(ENTITY_DEHUMIDIFIER)
assert state.attributes.get(ATTR_MIN_HUMIDITY) == 0 assert state.attributes.get(ATTR_MIN_HUMIDITY) == 0

View file

@ -13,6 +13,7 @@ from homeassistant.components.number import (
NumberMode, NumberMode,
) )
from homeassistant.const import ATTR_ENTITY_ID, ATTR_MODE from homeassistant.const import ATTR_ENTITY_ID, ATTR_MODE
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
ENTITY_VOLUME = "number.volume" ENTITY_VOLUME = "number.volume"
@ -28,13 +29,13 @@ async def setup_demo_number(hass):
await hass.async_block_till_done() await hass.async_block_till_done()
def test_setup_params(hass): def test_setup_params(hass: HomeAssistant) -> None:
"""Test the initial parameters.""" """Test the initial parameters."""
state = hass.states.get(ENTITY_VOLUME) state = hass.states.get(ENTITY_VOLUME)
assert state.state == "42.0" assert state.state == "42.0"
def test_default_setup_params(hass): def test_default_setup_params(hass: HomeAssistant) -> None:
"""Test the setup with default parameters.""" """Test the setup with default parameters."""
state = hass.states.get(ENTITY_VOLUME) state = hass.states.get(ENTITY_VOLUME)
assert state.attributes.get(ATTR_MIN) == 0.0 assert state.attributes.get(ATTR_MIN) == 0.0

View file

@ -17,6 +17,7 @@ from homeassistant.const import (
STATE_OFF, STATE_OFF,
STATE_ON, STATE_ON,
) )
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
ENTITY_SIREN = "siren.siren" ENTITY_SIREN = "siren.siren"
@ -30,14 +31,14 @@ async def setup_demo_siren(hass):
await hass.async_block_till_done() await hass.async_block_till_done()
def test_setup_params(hass): def test_setup_params(hass: HomeAssistant) -> None:
"""Test the initial parameters.""" """Test the initial parameters."""
state = hass.states.get(ENTITY_SIREN) state = hass.states.get(ENTITY_SIREN)
assert state.state == STATE_ON assert state.state == STATE_ON
assert ATTR_AVAILABLE_TONES not in state.attributes assert ATTR_AVAILABLE_TONES not in state.attributes
def test_all_setup_params(hass): def test_all_setup_params(hass: HomeAssistant) -> None:
"""Test the setup with all parameters.""" """Test the setup with all parameters."""
state = hass.states.get(ENTITY_SIREN_WITH_ALL_FEATURES) state = hass.states.get(ENTITY_SIREN_WITH_ALL_FEATURES)
assert state.attributes.get(ATTR_AVAILABLE_TONES) == ["fire", "alarm"] assert state.attributes.get(ATTR_AVAILABLE_TONES) == ["fire", "alarm"]

View file

@ -10,6 +10,7 @@ from homeassistant.components.text import (
SERVICE_SET_VALUE, SERVICE_SET_VALUE,
) )
from homeassistant.const import ATTR_ENTITY_ID, ATTR_MODE, MAX_LENGTH_STATE_STATE from homeassistant.const import ATTR_ENTITY_ID, ATTR_MODE, MAX_LENGTH_STATE_STATE
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
ENTITY_TEXT = "text.text" ENTITY_TEXT = "text.text"
@ -22,7 +23,7 @@ async def setup_demo_text(hass):
await hass.async_block_till_done() await hass.async_block_till_done()
def test_setup_params(hass): def test_setup_params(hass: HomeAssistant) -> None:
"""Test the initial parameters.""" """Test the initial parameters."""
state = hass.states.get(ENTITY_TEXT) state = hass.states.get(ENTITY_TEXT)
assert state.state == "Hello world" assert state.state == "Hello world"

View file

@ -1,10 +1,11 @@
"""Test the Eight Sleep config flow.""" """Test the Eight Sleep config flow."""
from homeassistant import config_entries from homeassistant import config_entries
from homeassistant.components.eight_sleep.const import DOMAIN from homeassistant.components.eight_sleep.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType from homeassistant.data_entry_flow import FlowResultType
async def test_form(hass) -> None: async def test_form(hass: HomeAssistant) -> 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(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -48,7 +49,7 @@ async def test_form_invalid_auth(hass, token_error) -> None:
assert result2["errors"] == {"base": "cannot_connect"} assert result2["errors"] == {"base": "cannot_connect"}
async def test_import(hass) -> None: async def test_import(hass: HomeAssistant) -> None:
"""Test import works.""" """Test import works."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,

View file

@ -34,6 +34,7 @@ from homeassistant.const import (
CONF_VERIFY_SSL, CONF_VERIFY_SSL,
HTTP_BASIC_AUTHENTICATION, HTTP_BASIC_AUTHENTICATION,
) )
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry from homeassistant.helpers import entity_registry
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
@ -736,7 +737,7 @@ async def test_unload_entry(hass, fakeimg_png):
assert mock_entry.state is config_entries.ConfigEntryState.NOT_LOADED assert mock_entry.state is config_entries.ConfigEntryState.NOT_LOADED
async def test_reload_on_title_change(hass) -> None: async def test_reload_on_title_change(hass: HomeAssistant) -> None:
"""Test the integration gets reloaded when the title is updated.""" """Test the integration gets reloaded when the title is updated."""
test_data = TESTDATA_OPTIONS test_data = TESTDATA_OPTIONS
@ -758,7 +759,7 @@ async def test_reload_on_title_change(hass) -> None:
assert hass.states.get("camera.my_title").attributes["friendly_name"] == "New Title" assert hass.states.get("camera.my_title").attributes["friendly_name"] == "New Title"
async def test_migrate_existing_ids(hass) -> None: async def test_migrate_existing_ids(hass: HomeAssistant) -> None:
"""Test that existing ids are migrated for issue #70568.""" """Test that existing ids are migrated for issue #70568."""
registry = entity_registry.async_get(hass) registry = entity_registry.async_get(hass)

View file

@ -6,6 +6,7 @@ from aiohttp import StreamReader
import pytest import pytest
from homeassistant.components.hassio.http import _need_auth from homeassistant.components.hassio.http import _need_auth
from homeassistant.core import HomeAssistant
async def test_forward_request(hassio_client, aioclient_mock): async def test_forward_request(hassio_client, aioclient_mock):
@ -170,7 +171,7 @@ async def test_backup_download_headers(hassio_client, aioclient_mock):
assert resp.headers["Content-Disposition"] == content_disposition assert resp.headers["Content-Disposition"] == content_disposition
def test_need_auth(hass): def test_need_auth(hass: HomeAssistant) -> None:
"""Test if the requested path needs authentication.""" """Test if the requested path needs authentication."""
assert not _need_auth(hass, "addons/test/logo") assert not _need_auth(hass, "addons/test/logo")
assert _need_auth(hass, "backups/new/upload") assert _need_auth(hass, "backups/new/upload")

View file

@ -20,7 +20,7 @@ import homeassistant.util.dt as dt_util
from tests.common import mock_restore_cache from tests.common import mock_restore_cache
async def test_state(hass) -> None: async def test_state(hass: HomeAssistant) -> None:
"""Test integration sensor state.""" """Test integration sensor state."""
config = { config = {
"sensor": { "sensor": {

View file

@ -2,6 +2,7 @@
from unittest.mock import MagicMock from unittest.mock import MagicMock
from homeassistant.components.kira import remote as kira from homeassistant.components.kira import remote as kira
from homeassistant.core import HomeAssistant
SERVICE_SEND_COMMAND = "send_command" SERVICE_SEND_COMMAND = "send_command"
@ -18,7 +19,7 @@ def add_entities(devices):
DEVICES.append(device) DEVICES.append(device)
def test_service_call(hass): def test_service_call(hass: HomeAssistant) -> None:
"""Test Kira's ability to send commands.""" """Test Kira's ability to send commands."""
mock_kira = MagicMock() mock_kira = MagicMock()
hass.data[kira.DOMAIN] = {kira.CONF_REMOTE: {}} hass.data[kira.DOMAIN] = {kira.CONF_REMOTE: {}}

View file

@ -5,13 +5,14 @@ import pytest
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS
from homeassistant.const import ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, ATTR_ICON from homeassistant.const import ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, ATTR_ICON
from homeassistant.core import HomeAssistant
from homeassistant.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 . import init_integration from . import init_integration
async def test_button_setup_non_electric_vehicle(hass) -> None: async def test_button_setup_non_electric_vehicle(hass: HomeAssistant) -> None:
"""Test creation of button entities.""" """Test creation of button entities."""
await init_integration(hass) await init_integration(hass)
@ -58,7 +59,7 @@ async def test_button_setup_non_electric_vehicle(hass) -> None:
assert state is None assert state is None
async def test_button_setup_electric_vehicle(hass) -> None: async def test_button_setup_electric_vehicle(hass: HomeAssistant) -> None:
"""Test creation of button entities for an electric vehicle.""" """Test creation of button entities for an electric vehicle."""
await init_integration(hass, electric_vehicle=True) await init_integration(hass, electric_vehicle=True)
@ -133,7 +134,7 @@ async def test_button_press(hass, entity_id_suffix, api_method_name) -> None:
api_method.assert_called_once_with(12345) api_method.assert_called_once_with(12345)
async def test_button_press_error(hass) -> None: async def test_button_press_error(hass: HomeAssistant) -> None:
"""Test the Mazda API raising an error when a button entity is pressed.""" """Test the Mazda API raising an error when a button entity is pressed."""
client_mock = await init_integration(hass) client_mock = await init_integration(hass)

View file

@ -172,7 +172,7 @@ async def test_controlling_validation_state_via_topic(
assert state.state == "no" assert state.state == "no"
async def test_attribute_validation_max_greater_then_min(hass) -> None: async def test_attribute_validation_max_greater_then_min(hass: HomeAssistant) -> None:
"""Test the validation of min and max configuration attributes.""" """Test the validation of min and max configuration attributes."""
assert not await async_setup_component( assert not await async_setup_component(
hass, hass,
@ -190,7 +190,9 @@ async def test_attribute_validation_max_greater_then_min(hass) -> None:
) )
async def test_attribute_validation_max_not_greater_then_max_state_length(hass) -> None: async def test_attribute_validation_max_not_greater_then_max_state_length(
hass: HomeAssistant,
) -> None:
"""Test the max value of of max configuration attribute.""" """Test the max value of of max configuration attribute."""
assert not await async_setup_component( assert not await async_setup_component(
hass, hass,

View file

@ -6,6 +6,7 @@ import pytest
import requests import requests
from homeassistant.components.nx584 import binary_sensor as nx584 from homeassistant.components.nx584 import binary_sensor as nx584
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
DEFAULT_CONFIG = { DEFAULT_CONFIG = {
@ -133,7 +134,7 @@ async def test_nx584_sensor_setup_version_too_old(hass):
@pytest.mark.usefixtures("client") @pytest.mark.usefixtures("client")
def test_nx584_sensor_setup_no_zones(hass): def test_nx584_sensor_setup_no_zones(hass: HomeAssistant) -> None:
"""Test the setup with no zones.""" """Test the setup with no zones."""
nx584_client.Client.return_value.list_zones.return_value = [] nx584_client.Client.return_value.list_zones.return_value = []
add_entities = mock.MagicMock() add_entities = mock.MagicMock()

View file

@ -7,6 +7,7 @@ from unittest.mock import patch
from voluptuous import MultipleInvalid from voluptuous import MultipleInvalid
from homeassistant.components import pilight from homeassistant.components import pilight
from homeassistant.core import HomeAssistant
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
@ -388,7 +389,7 @@ async def test_call_rate_delay_throttle_enabled(hass):
assert runs == exp assert runs == exp
def test_call_rate_delay_throttle_disabled(hass): def test_call_rate_delay_throttle_disabled(hass: HomeAssistant) -> None:
"""Test that the limiter is a noop if no delay set.""" """Test that the limiter is a noop if no delay set."""
runs = [] runs = []

View file

@ -10,7 +10,7 @@ from homeassistant.const import (
STATE_PROBLEM, STATE_PROBLEM,
STATE_UNAVAILABLE, STATE_UNAVAILABLE,
) )
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 tests.components.recorder.common import async_wait_recording_done from tests.components.recorder.common import async_wait_recording_done
@ -192,13 +192,13 @@ async def test_brightness_history(hass):
assert state.state == STATE_OK assert state.state == STATE_OK
def test_daily_history_no_data(hass): def test_daily_history_no_data(hass: HomeAssistant) -> None:
"""Test with empty history.""" """Test with empty history."""
dh = plant.DailyHistory(3) dh = plant.DailyHistory(3)
assert dh.max is None assert dh.max is None
def test_daily_history_one_day(hass): def test_daily_history_one_day(hass: HomeAssistant) -> None:
"""Test storing data for the same day.""" """Test storing data for the same day."""
dh = plant.DailyHistory(3) dh = plant.DailyHistory(3)
values = [-2, 10, 0, 5, 20] values = [-2, 10, 0, 5, 20]
@ -209,7 +209,7 @@ def test_daily_history_one_day(hass):
assert dh.max == max_value assert dh.max == max_value
def test_daily_history_multiple_days(hass): def test_daily_history_multiple_days(hass: HomeAssistant) -> None:
"""Test storing data for different days.""" """Test storing data for different days."""
dh = plant.DailyHistory(3) dh = plant.DailyHistory(3)
today = datetime.now() today = datetime.now()

View file

@ -12,6 +12,7 @@ from homeassistant import config_entries
from homeassistant.components import dhcp from homeassistant.components import dhcp
from homeassistant.components.powerwall.const import DOMAIN from homeassistant.components.powerwall.const import DOMAIN
from homeassistant.const import CONF_IP_ADDRESS, CONF_PASSWORD from homeassistant.const import CONF_IP_ADDRESS, CONF_PASSWORD
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType from homeassistant.data_entry_flow import FlowResultType
from .mocks import ( from .mocks import (
@ -507,7 +508,9 @@ async def test_dhcp_discovery_updates_unique_id_when_entry_is_failed(hass):
assert entry.unique_id == MOCK_GATEWAY_DIN assert entry.unique_id == MOCK_GATEWAY_DIN
async def test_discovered_wifi_does_not_update_ip_if_is_still_online(hass) -> None: async def test_discovered_wifi_does_not_update_ip_if_is_still_online(
hass: HomeAssistant,
) -> None:
"""Test a discovery does not update the ip unless the powerwall at the old ip is offline.""" """Test a discovery does not update the ip unless the powerwall at the old ip is offline."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,

View file

@ -25,6 +25,7 @@ from homeassistant.const import (
CONF_REGION, CONF_REGION,
CONF_TOKEN, CONF_TOKEN,
) )
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from homeassistant.util import location from homeassistant.util import location
@ -195,7 +196,7 @@ async def setup_mock_component(hass):
await hass.async_block_till_done() await hass.async_block_till_done()
def test_games_reformat_to_dict(hass): def test_games_reformat_to_dict(hass: HomeAssistant) -> None:
"""Test old data format is converted to new format.""" """Test old data format is converted to new format."""
with patch( with patch(
"homeassistant.components.ps4.load_json", "homeassistant.components.ps4.load_json",
@ -218,7 +219,7 @@ def test_games_reformat_to_dict(hass):
assert mock_data[ATTR_MEDIA_CONTENT_TYPE] == MediaType.GAME assert mock_data[ATTR_MEDIA_CONTENT_TYPE] == MediaType.GAME
def test_load_games(hass): def test_load_games(hass: HomeAssistant) -> None:
"""Test that games are loaded correctly.""" """Test that games are loaded correctly."""
with patch( with patch(
"homeassistant.components.ps4.load_json", return_value=MOCK_GAMES "homeassistant.components.ps4.load_json", return_value=MOCK_GAMES
@ -237,7 +238,7 @@ def test_load_games(hass):
assert mock_data[ATTR_MEDIA_CONTENT_TYPE] == MediaType.GAME assert mock_data[ATTR_MEDIA_CONTENT_TYPE] == MediaType.GAME
def test_loading_games_returns_dict(hass): def test_loading_games_returns_dict(hass: HomeAssistant) -> None:
"""Test that loading games always returns a dict.""" """Test that loading games always returns a dict."""
with patch( with patch(
"homeassistant.components.ps4.load_json", side_effect=HomeAssistantError "homeassistant.components.ps4.load_json", side_effect=HomeAssistantError

View file

@ -729,7 +729,7 @@ def test_saving_state_with_oversized_attributes(hass_recorder, caplog):
assert states[1].attributes == {} assert states[1].attributes == {}
def test_recorder_setup_failure(hass): def test_recorder_setup_failure(hass: HomeAssistant) -> None:
"""Test some exceptions.""" """Test some exceptions."""
recorder_helper.async_initialize_recorder(hass) recorder_helper.async_initialize_recorder(hass)
with patch.object(Recorder, "_setup_connection") as setup, patch( with patch.object(Recorder, "_setup_connection") as setup, patch(
@ -744,7 +744,7 @@ def test_recorder_setup_failure(hass):
hass.stop() hass.stop()
def test_recorder_validate_schema_failure(hass): def test_recorder_validate_schema_failure(hass: HomeAssistant) -> None:
"""Test some exceptions.""" """Test some exceptions."""
recorder_helper.async_initialize_recorder(hass) recorder_helper.async_initialize_recorder(hass)
with patch( with patch(
@ -761,7 +761,7 @@ def test_recorder_validate_schema_failure(hass):
hass.stop() hass.stop()
def test_recorder_setup_failure_without_event_listener(hass): def test_recorder_setup_failure_without_event_listener(hass: HomeAssistant) -> None:
"""Test recorder setup failure when the event listener is not setup.""" """Test recorder setup failure when the event listener is not setup."""
recorder_helper.async_initialize_recorder(hass) recorder_helper.async_initialize_recorder(hass)
with patch.object(Recorder, "_setup_connection") as setup, patch( with patch.object(Recorder, "_setup_connection") as setup, patch(

View file

@ -27,6 +27,7 @@ from homeassistant.components.recorder.db_schema import (
States, States,
) )
from homeassistant.components.recorder.util import session_scope from homeassistant.components.recorder.util import session_scope
from homeassistant.core import HomeAssistant
from homeassistant.helpers import recorder as recorder_helper from homeassistant.helpers import recorder as recorder_helper
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
@ -365,7 +366,7 @@ async def test_schema_migrate(hass, start_version, live):
assert recorder.util.async_migration_in_progress(hass) is not True assert recorder.util.async_migration_in_progress(hass) is not True
def test_invalid_update(hass): def test_invalid_update(hass: HomeAssistant) -> None:
"""Test that an invalid new version raises an exception.""" """Test that an invalid new version raises an exception."""
with pytest.raises(ValueError): with pytest.raises(ValueError):
migration._apply_update(hass, Mock(), Mock(), -1, 0) migration._apply_update(hass, Mock(), Mock(), -1, 0)

View file

@ -2,11 +2,12 @@
from unittest.mock import Mock, mock_open, patch from unittest.mock import Mock, mock_open, patch
import homeassistant.components.remember_the_milk as rtm import homeassistant.components.remember_the_milk as rtm
from homeassistant.core import HomeAssistant
from .const import JSON_STRING, PROFILE, TOKEN from .const import JSON_STRING, PROFILE, TOKEN
def test_create_new(hass): def test_create_new(hass: HomeAssistant) -> None:
"""Test creating a new config file.""" """Test creating a new config file."""
with patch("builtins.open", mock_open()), patch( with patch("builtins.open", mock_open()), patch(
"os.path.isfile", Mock(return_value=False) "os.path.isfile", Mock(return_value=False)
@ -16,7 +17,7 @@ def test_create_new(hass):
assert config.get_token(PROFILE) == TOKEN assert config.get_token(PROFILE) == TOKEN
def test_load_config(hass): def test_load_config(hass: HomeAssistant) -> None:
"""Test loading an existing token from the file.""" """Test loading an existing token from the file."""
with patch("builtins.open", mock_open(read_data=JSON_STRING)), patch( with patch("builtins.open", mock_open(read_data=JSON_STRING)), patch(
"os.path.isfile", Mock(return_value=True) "os.path.isfile", Mock(return_value=True)
@ -25,7 +26,7 @@ def test_load_config(hass):
assert config.get_token(PROFILE) == TOKEN assert config.get_token(PROFILE) == TOKEN
def test_invalid_data(hass): def test_invalid_data(hass: HomeAssistant) -> None:
"""Test starts with invalid data and should not raise an exception.""" """Test starts with invalid data and should not raise an exception."""
with patch("builtins.open", mock_open(read_data="random characters")), patch( with patch("builtins.open", mock_open(read_data="random characters")), patch(
"os.path.isfile", Mock(return_value=True) "os.path.isfile", Mock(return_value=True)
@ -34,7 +35,7 @@ def test_invalid_data(hass):
assert config is not None assert config is not None
def test_id_map(hass): def test_id_map(hass: HomeAssistant) -> None:
"""Test the hass to rtm task is mapping.""" """Test the hass to rtm task is mapping."""
hass_id = "hass-id-1234" hass_id = "hass-id-1234"
list_id = "mylist" list_id = "mylist"
@ -52,7 +53,7 @@ def test_id_map(hass):
assert config.get_rtm_id(PROFILE, hass_id) is None assert config.get_rtm_id(PROFILE, hass_id) is None
def test_load_key_map(hass): def test_load_key_map(hass: HomeAssistant) -> None:
"""Test loading an existing key map from the file.""" """Test loading an existing key map from the file."""
with patch("builtins.open", mock_open(read_data=JSON_STRING)), patch( with patch("builtins.open", mock_open(read_data=JSON_STRING)), patch(
"os.path.isfile", Mock(return_value=True) "os.path.isfile", Mock(return_value=True)

View file

@ -14,6 +14,7 @@ from homeassistant.const import (
CONF_SSL, CONF_SSL,
CONF_URL, CONF_URL,
) )
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType from homeassistant.data_entry_flow import FlowResultType
VALID_CONFIG = { VALID_CONFIG = {
@ -77,7 +78,7 @@ async def test_auth_error(hass):
assert result["errors"] == {"base": "cannot_connect"} assert result["errors"] == {"base": "cannot_connect"}
async def test_import_flow(hass) -> None: async def test_import_flow(hass: HomeAssistant) -> None:
"""Test the import configuration flow.""" """Test the import configuration flow."""
with patch( with patch(
"homeassistant.components.sabnzbd.sab.SabnzbdApi.check_available", "homeassistant.components.sabnzbd.sab.SabnzbdApi.check_available",

View file

@ -21,6 +21,7 @@ from homeassistant.components.unifi_direct.device_tracker import (
get_scanner, get_scanner,
) )
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PLATFORM, CONF_USERNAME from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PLATFORM, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import assert_setup_component, load_fixture, mock_component from tests.common import assert_setup_component, load_fixture, mock_component
@ -130,13 +131,13 @@ async def test_to_get_update(mock_sendline, mock_prompt, mock_login, mock_logout
assert devices is None assert devices is None
def test_good_response_parses(hass): def test_good_response_parses(hass: HomeAssistant) -> None:
"""Test that the response form the AP parses to JSON correctly.""" """Test that the response form the AP parses to JSON correctly."""
response = _response_to_json(load_fixture("data.txt", "unifi_direct")) response = _response_to_json(load_fixture("data.txt", "unifi_direct"))
assert response != {} assert response != {}
def test_bad_response_returns_none(hass): def test_bad_response_returns_none(hass: HomeAssistant) -> None:
"""Test that a bad response form the AP parses to JSON correctly.""" """Test that a bad response form the AP parses to JSON correctly."""
assert _response_to_json("{(}") == {} assert _response_to_json("{(}") == {}

View file

@ -7,6 +7,7 @@ from homeassistant import config_entries, data_entry_flow
from homeassistant.components import dhcp from homeassistant.components import dhcp
from homeassistant.components.vicare.const import DOMAIN from homeassistant.components.vicare.const import DOMAIN
from homeassistant.const import CONF_CLIENT_ID, CONF_PASSWORD, CONF_USERNAME from homeassistant.const import CONF_CLIENT_ID, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from . import ENTRY_CONFIG, MOCK_MAC from . import ENTRY_CONFIG, MOCK_MAC
@ -44,7 +45,7 @@ async def test_form(hass):
assert len(mock_setup_entry.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
async def test_invalid_login(hass) -> None: async def test_invalid_login(hass: HomeAssistant) -> None:
"""Test a flow with an invalid Vicare login.""" """Test a flow with an invalid Vicare login."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER} DOMAIN, context={"source": config_entries.SOURCE_USER}

View file

@ -11,6 +11,7 @@ import pytest
import voluptuous as vol import voluptuous as vol
import homeassistant import homeassistant
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv, selector, template from homeassistant.helpers import config_validation as cv, selector, template
@ -487,7 +488,7 @@ def test_slug() -> None:
schema(value) schema(value)
def test_string(hass): def test_string(hass: HomeAssistant) -> None:
"""Test string validation.""" """Test string validation."""
schema = vol.Schema(cv.string) schema = vol.Schema(cv.string)

View file

@ -6,7 +6,7 @@ from typing import NamedTuple
import pytest import pytest
from homeassistant import core from homeassistant.core import HomeAssistant, State
from homeassistant.helpers.json import ( from homeassistant.helpers.json import (
ExtendedJSONEncoder, ExtendedJSONEncoder,
JSONEncoder, JSONEncoder,
@ -22,7 +22,7 @@ from homeassistant.util.color import RGBColor
def test_json_encoder(hass, encoder): def test_json_encoder(hass, encoder):
"""Test the JSON encoders.""" """Test the JSON encoders."""
ha_json_enc = encoder() ha_json_enc = encoder()
state = core.State("test.test", "hello") state = State("test.test", "hello")
# Test serializing a datetime # Test serializing a datetime
now = dt_util.utcnow() now = dt_util.utcnow()
@ -36,7 +36,7 @@ def test_json_encoder(hass, encoder):
assert ha_json_enc.default(state) == state.as_dict() assert ha_json_enc.default(state) == state.as_dict()
def test_json_encoder_raises(hass): def test_json_encoder_raises(hass: HomeAssistant) -> None:
"""Test the JSON encoder raises on unsupported types.""" """Test the JSON encoder raises on unsupported types."""
ha_json_enc = JSONEncoder() ha_json_enc = JSONEncoder()
@ -45,7 +45,7 @@ def test_json_encoder_raises(hass):
ha_json_enc.default(1) ha_json_enc.default(1)
def test_extended_json_encoder(hass): def test_extended_json_encoder(hass: HomeAssistant) -> None:
"""Test the extended JSON encoder.""" """Test the extended JSON encoder."""
ha_json_enc = ExtendedJSONEncoder() ha_json_enc = ExtendedJSONEncoder()
# Test serializing a timedelta # Test serializing a timedelta

View file

@ -1,6 +1,6 @@
"""Tests Home Assistant location helpers.""" """Tests Home Assistant location helpers."""
from homeassistant.const import ATTR_FRIENDLY_NAME, ATTR_LATITUDE, ATTR_LONGITUDE from homeassistant.const import ATTR_FRIENDLY_NAME, ATTR_LATITUDE, ATTR_LONGITUDE
from homeassistant.core import State from homeassistant.core import HomeAssistant, State
from homeassistant.helpers import location from homeassistant.helpers import location
@ -101,7 +101,7 @@ async def test_coordinates_function_device_tracker_from_input_select(hass):
) )
def test_coordinates_function_returns_none_on_recursion(hass): def test_coordinates_function_returns_none_on_recursion(hass: HomeAssistant) -> None:
"""Test coordinates function.""" """Test coordinates function."""
hass.states.async_set( hass.states.async_set(
"test.first", "test.first",
@ -120,7 +120,7 @@ async def test_coordinates_function_returns_state_if_no_coords(hass):
assert location.find_coordinates(hass, "test.object") == "abc" assert location.find_coordinates(hass, "test.object") == "abc"
def test_coordinates_function_returns_input_if_no_coords(hass): def test_coordinates_function_returns_input_if_no_coords(hass: HomeAssistant) -> None:
"""Test test_coordinates function.""" """Test test_coordinates function."""
assert location.find_coordinates(hass, "test.abc") == "test.abc" assert location.find_coordinates(hass, "test.abc") == "test.abc"
assert location.find_coordinates(hass, "abc") == "abc" assert location.find_coordinates(hass, "abc") == "abc"

View file

@ -4,11 +4,12 @@ from datetime import datetime, timedelta
from unittest.mock import patch from unittest.mock import patch
from homeassistant.const import SUN_EVENT_SUNRISE, SUN_EVENT_SUNSET from homeassistant.const import SUN_EVENT_SUNRISE, SUN_EVENT_SUNSET
from homeassistant.core import HomeAssistant
import homeassistant.helpers.sun as sun import homeassistant.helpers.sun as sun
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
def test_next_events(hass): def test_next_events(hass: HomeAssistant) -> None:
"""Test retrieving next sun events.""" """Test retrieving next sun events."""
utc_now = datetime(2016, 11, 1, 8, 0, 0, tzinfo=dt_util.UTC) utc_now = datetime(2016, 11, 1, 8, 0, 0, tzinfo=dt_util.UTC)
from astral import LocationInfo from astral import LocationInfo
@ -83,7 +84,7 @@ def test_next_events(hass):
assert next_setting == sun.get_astral_event_next(hass, SUN_EVENT_SUNSET) assert next_setting == sun.get_astral_event_next(hass, SUN_EVENT_SUNSET)
def test_date_events(hass): def test_date_events(hass: HomeAssistant) -> None:
"""Test retrieving next sun events.""" """Test retrieving next sun events."""
utc_now = datetime(2016, 11, 1, 8, 0, 0, tzinfo=dt_util.UTC) utc_now = datetime(2016, 11, 1, 8, 0, 0, tzinfo=dt_util.UTC)
from astral import LocationInfo from astral import LocationInfo
@ -110,7 +111,7 @@ def test_date_events(hass):
assert sunset == sun.get_astral_event_date(hass, SUN_EVENT_SUNSET, utc_today) assert sunset == sun.get_astral_event_date(hass, SUN_EVENT_SUNSET, utc_today)
def test_date_events_default_date(hass): def test_date_events_default_date(hass: HomeAssistant) -> None:
"""Test retrieving next sun events.""" """Test retrieving next sun events."""
utc_now = datetime(2016, 11, 1, 8, 0, 0, tzinfo=dt_util.UTC) utc_now = datetime(2016, 11, 1, 8, 0, 0, tzinfo=dt_util.UTC)
from astral import LocationInfo from astral import LocationInfo
@ -138,7 +139,7 @@ def test_date_events_default_date(hass):
assert sunset == sun.get_astral_event_date(hass, SUN_EVENT_SUNSET, utc_today) assert sunset == sun.get_astral_event_date(hass, SUN_EVENT_SUNSET, utc_today)
def test_date_events_accepts_datetime(hass): def test_date_events_accepts_datetime(hass: HomeAssistant) -> None:
"""Test retrieving next sun events.""" """Test retrieving next sun events."""
utc_now = datetime(2016, 11, 1, 8, 0, 0, tzinfo=dt_util.UTC) utc_now = datetime(2016, 11, 1, 8, 0, 0, tzinfo=dt_util.UTC)
from astral import LocationInfo from astral import LocationInfo
@ -165,7 +166,7 @@ def test_date_events_accepts_datetime(hass):
assert sunset == sun.get_astral_event_date(hass, SUN_EVENT_SUNSET, utc_now) assert sunset == sun.get_astral_event_date(hass, SUN_EVENT_SUNSET, utc_now)
def test_is_up(hass): def test_is_up(hass: HomeAssistant) -> None:
"""Test retrieving next sun events.""" """Test retrieving next sun events."""
utc_now = datetime(2016, 11, 1, 12, 0, 0, tzinfo=dt_util.UTC) utc_now = datetime(2016, 11, 1, 12, 0, 0, tzinfo=dt_util.UTC)
with patch("homeassistant.helpers.condition.dt_util.utcnow", return_value=utc_now): with patch("homeassistant.helpers.condition.dt_util.utcnow", return_value=utc_now):
@ -176,7 +177,7 @@ def test_is_up(hass):
assert sun.is_up(hass) assert sun.is_up(hass)
def test_norway_in_june(hass): def test_norway_in_june(hass: HomeAssistant) -> None:
"""Test location in Norway where the sun doesn't set in summer.""" """Test location in Norway where the sun doesn't set in summer."""
hass.config.latitude = 69.6 hass.config.latitude = 69.6
hass.config.longitude = 18.8 hass.config.longitude = 18.8

View file

@ -8,12 +8,13 @@ from homeassistant.const import (
TEMP_CELSIUS, TEMP_CELSIUS,
TEMP_FAHRENHEIT, TEMP_FAHRENHEIT,
) )
from homeassistant.core import HomeAssistant
from homeassistant.helpers.temperature import display_temp from homeassistant.helpers.temperature import display_temp
TEMP = 24.636626 TEMP = 24.636626
def test_temperature_not_a_number(hass): def test_temperature_not_a_number(hass: HomeAssistant) -> None:
"""Test that temperature is a number.""" """Test that temperature is a number."""
temp = "Temperature" temp = "Temperature"
with pytest.raises(Exception) as exception: with pytest.raises(Exception) as exception:
@ -22,16 +23,16 @@ def test_temperature_not_a_number(hass):
assert f"Temperature is not a number: {temp}" in str(exception.value) assert f"Temperature is not a number: {temp}" in str(exception.value)
def test_celsius_halves(hass): def test_celsius_halves(hass: HomeAssistant) -> None:
"""Test temperature to celsius rounding to halves.""" """Test temperature to celsius rounding to halves."""
assert display_temp(hass, TEMP, TEMP_CELSIUS, PRECISION_HALVES) == 24.5 assert display_temp(hass, TEMP, TEMP_CELSIUS, PRECISION_HALVES) == 24.5
def test_celsius_tenths(hass): def test_celsius_tenths(hass: HomeAssistant) -> None:
"""Test temperature to celsius rounding to tenths.""" """Test temperature to celsius rounding to tenths."""
assert display_temp(hass, TEMP, TEMP_CELSIUS, PRECISION_TENTHS) == 24.6 assert display_temp(hass, TEMP, TEMP_CELSIUS, PRECISION_TENTHS) == 24.6
def test_fahrenheit_wholes(hass): def test_fahrenheit_wholes(hass: HomeAssistant) -> None:
"""Test temperature to fahrenheit rounding to wholes.""" """Test temperature to fahrenheit rounding to wholes."""
assert display_temp(hass, TEMP, TEMP_FAHRENHEIT, PRECISION_WHOLE) == -4 assert display_temp(hass, TEMP, TEMP_FAHRENHEIT, PRECISION_WHOLE) == -4

View file

@ -6,6 +6,7 @@ from unittest.mock import Mock, patch
import pytest import pytest
from homeassistant.core import HomeAssistant
from homeassistant.generated import config_flows from homeassistant.generated import config_flows
from homeassistant.helpers import translation from homeassistant.helpers import translation
from homeassistant.loader import async_get_integration from homeassistant.loader import async_get_integration
@ -75,7 +76,7 @@ async def test_component_translation_path(hass, enable_custom_integrations):
) )
def test_load_translations_files(hass): def test_load_translations_files(hass: HomeAssistant) -> None:
"""Test the load translation files function.""" """Test the load translation files function."""
# Test one valid and one invalid file # Test one valid and one invalid file
file1 = hass.config.path( file1 = hass.config.path(

View file

@ -339,7 +339,7 @@ def test_remove_lib_on_upgrade_94(mock_docker, mock_os, mock_shutil, hass):
assert mock_shutil.rmtree.call_args == mock.call(hass_path) assert mock_shutil.rmtree.call_args == mock.call(hass_path)
def test_process_config_upgrade(hass): def test_process_config_upgrade(hass: HomeAssistant) -> None:
"""Test update of version on upgrade.""" """Test update of version on upgrade."""
ha_version = "0.92.0" ha_version = "0.92.0"
@ -357,7 +357,7 @@ def test_process_config_upgrade(hass):
assert opened_file.write.call_args == mock.call("0.91.0") assert opened_file.write.call_args == mock.call("0.91.0")
def test_config_upgrade_same_version(hass): def test_config_upgrade_same_version(hass: HomeAssistant) -> None:
"""Test no update of version on no upgrade.""" """Test no update of version on no upgrade."""
ha_version = __version__ ha_version = __version__
@ -372,7 +372,7 @@ def test_config_upgrade_same_version(hass):
assert opened_file.write.call_count == 0 assert opened_file.write.call_count == 0
def test_config_upgrade_no_file(hass): def test_config_upgrade_no_file(hass: HomeAssistant) -> None:
"""Test update of version on upgrade, with no version file.""" """Test update of version on upgrade, with no version file."""
mock_open = mock.mock_open() mock_open = mock.mock_open()
mock_open.side_effect = [FileNotFoundError(), mock.DEFAULT, mock.DEFAULT] mock_open.side_effect = [FileNotFoundError(), mock.DEFAULT, mock.DEFAULT]

View file

@ -3,9 +3,10 @@ from unittest.mock import patch
import pytest import pytest
from homeassistant import core, loader from homeassistant import loader
from homeassistant.components import http, hue from homeassistant.components import http, hue
from homeassistant.components.hue import light as hue_light from homeassistant.components.hue import light as hue_light
from homeassistant.core import HomeAssistant, callback
from .common import MockModule, mock_integration from .common import MockModule, mock_integration
@ -41,14 +42,14 @@ async def test_component_dependencies(hass):
await loader._async_component_dependencies(hass, "mod_3", mod_3, set(), set()) await loader._async_component_dependencies(hass, "mod_3", mod_3, set(), set())
def test_component_loader(hass): def test_component_loader(hass: HomeAssistant) -> None:
"""Test loading components.""" """Test loading components."""
components = loader.Components(hass) components = loader.Components(hass)
assert components.http.CONFIG_SCHEMA is http.CONFIG_SCHEMA assert components.http.CONFIG_SCHEMA is http.CONFIG_SCHEMA
assert hass.components.http.CONFIG_SCHEMA is http.CONFIG_SCHEMA assert hass.components.http.CONFIG_SCHEMA is http.CONFIG_SCHEMA
def test_component_loader_non_existing(hass): def test_component_loader_non_existing(hass: HomeAssistant) -> None:
"""Test loading components.""" """Test loading components."""
components = loader.Components(hass) components = loader.Components(hass)
with pytest.raises(ImportError): with pytest.raises(ImportError):
@ -69,7 +70,7 @@ async def test_helpers_wrapper(hass):
result = [] result = []
@core.callback @callback
def discovery_callback(service, discovered): def discovery_callback(service, discovered):
"""Handle discovery callback.""" """Handle discovery callback."""
result.append(discovered) result.append(discovered)
@ -174,7 +175,7 @@ async def test_get_integration_custom_component(hass, enable_custom_integrations
assert integration.name == "Test Package" assert integration.name == "Test Package"
def test_integration_properties(hass): def test_integration_properties(hass: HomeAssistant) -> None:
"""Test integration properties.""" """Test integration properties."""
integration = loader.Integration( integration = loader.Integration(
hass, hass,