Add type hints to integration tests (part 16) (#88008)

This commit is contained in:
epenet 2023-02-15 10:50:02 +01:00 committed by GitHub
parent 09b509da94
commit 88444b2e0c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
50 changed files with 589 additions and 286 deletions

View file

@ -8,6 +8,7 @@ from homeassistant import data_entry_flow
from homeassistant.components.notion import DOMAIN from homeassistant.components.notion import DOMAIN
from homeassistant.config_entries import SOURCE_REAUTH, SOURCE_USER from homeassistant.config_entries import SOURCE_REAUTH, SOURCE_USER
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from .conftest import TEST_PASSWORD, TEST_USERNAME from .conftest import TEST_PASSWORD, TEST_USERNAME
@ -21,8 +22,13 @@ from .conftest import TEST_PASSWORD, TEST_USERNAME
], ],
) )
async def test_create_entry( async def test_create_entry(
hass, client, config, errors, get_client_with_exception, mock_aionotion hass: HomeAssistant,
): client,
config,
errors,
get_client_with_exception,
mock_aionotion,
) -> None:
"""Test creating an etry (including recovery from errors).""" """Test creating an etry (including recovery from errors)."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER} DOMAIN, context={"source": SOURCE_USER}
@ -52,7 +58,7 @@ async def test_create_entry(
} }
async def test_duplicate_error(hass, config, setup_config_entry): async def test_duplicate_error(hass: HomeAssistant, config, setup_config_entry) -> None:
"""Test that errors are shown when duplicates are added.""" """Test that errors are shown when duplicates are added."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=config DOMAIN, context={"source": SOURCE_USER}, data=config
@ -70,8 +76,13 @@ async def test_duplicate_error(hass, config, setup_config_entry):
], ],
) )
async def test_reauth( async def test_reauth(
hass, config, config_entry, errors, get_client_with_exception, setup_config_entry hass: HomeAssistant,
): config,
config_entry,
errors,
get_client_with_exception,
setup_config_entry,
) -> None:
"""Test that re-auth works.""" """Test that re-auth works."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,

View file

@ -1,10 +1,17 @@
"""Test Notion diagnostics.""" """Test Notion diagnostics."""
from homeassistant.components.diagnostics import REDACTED from homeassistant.components.diagnostics import REDACTED
from homeassistant.core import HomeAssistant
from tests.components.diagnostics import get_diagnostics_for_config_entry from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_entry_diagnostics(hass, config_entry, hass_client, setup_config_entry): async def test_entry_diagnostics(
hass: HomeAssistant,
config_entry,
hass_client: ClientSessionGenerator,
setup_config_entry,
) -> None:
"""Test config entry diagnostics.""" """Test config entry diagnostics."""
assert await get_diagnostics_for_config_entry(hass, hass_client, config_entry) == { assert await get_diagnostics_for_config_entry(hass, hass_client, config_entry) == {
"entry": { "entry": {

View file

@ -5,6 +5,7 @@ from nsw_fuel import FuelCheckError
from homeassistant.components import sensor from homeassistant.components import sensor
from homeassistant.components.nsw_fuel_station import DOMAIN from homeassistant.components.nsw_fuel_station import DOMAIN
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 from tests.common import assert_setup_component
@ -73,7 +74,7 @@ MOCK_FUEL_PRICES_RESPONSE = MockGetFuelPricesResponse(
"homeassistant.components.nsw_fuel_station.FuelCheckClient.get_fuel_prices", "homeassistant.components.nsw_fuel_station.FuelCheckClient.get_fuel_prices",
return_value=MOCK_FUEL_PRICES_RESPONSE, return_value=MOCK_FUEL_PRICES_RESPONSE,
) )
async def test_setup(get_fuel_prices, hass): async def test_setup(get_fuel_prices, hass: HomeAssistant) -> None:
"""Test the setup with custom settings.""" """Test the setup with custom settings."""
with assert_setup_component(1, sensor.DOMAIN): with assert_setup_component(1, sensor.DOMAIN):
assert await async_setup_component( assert await async_setup_component(
@ -95,7 +96,7 @@ def raise_fuel_check_error():
"homeassistant.components.nsw_fuel_station.FuelCheckClient.get_fuel_prices", "homeassistant.components.nsw_fuel_station.FuelCheckClient.get_fuel_prices",
side_effect=raise_fuel_check_error, side_effect=raise_fuel_check_error,
) )
async def test_setup_error(get_fuel_prices, hass): async def test_setup_error(get_fuel_prices, hass: HomeAssistant) -> None:
"""Test the setup with client throwing error.""" """Test the setup with client throwing error."""
with assert_setup_component(1, sensor.DOMAIN): with assert_setup_component(1, sensor.DOMAIN):
assert await async_setup_component( assert await async_setup_component(
@ -112,7 +113,7 @@ async def test_setup_error(get_fuel_prices, hass):
"homeassistant.components.nsw_fuel_station.FuelCheckClient.get_fuel_prices", "homeassistant.components.nsw_fuel_station.FuelCheckClient.get_fuel_prices",
return_value=MOCK_FUEL_PRICES_RESPONSE, return_value=MOCK_FUEL_PRICES_RESPONSE,
) )
async def test_setup_error_no_station(get_fuel_prices, hass): async def test_setup_error_no_station(get_fuel_prices, hass: HomeAssistant) -> None:
"""Test the setup with specified station not existing.""" """Test the setup with specified station not existing."""
with assert_setup_component(2, sensor.DOMAIN): with assert_setup_component(2, sensor.DOMAIN):
assert await async_setup_component( assert await async_setup_component(
@ -143,7 +144,7 @@ async def test_setup_error_no_station(get_fuel_prices, hass):
"homeassistant.components.nsw_fuel_station.FuelCheckClient.get_fuel_prices", "homeassistant.components.nsw_fuel_station.FuelCheckClient.get_fuel_prices",
return_value=MOCK_FUEL_PRICES_RESPONSE, return_value=MOCK_FUEL_PRICES_RESPONSE,
) )
async def test_sensor_values(get_fuel_prices, hass): async def test_sensor_values(get_fuel_prices, hass: HomeAssistant) -> None:
"""Test retrieval of sensor values.""" """Test retrieval of sensor values."""
assert await async_setup_component(hass, DOMAIN, {}) assert await async_setup_component(hass, DOMAIN, {})
assert await async_setup_component(hass, sensor.DOMAIN, {"sensor": VALID_CONFIG}) assert await async_setup_component(hass, sensor.DOMAIN, {"sensor": VALID_CONFIG})

View file

@ -1,5 +1,6 @@
"""Tests for the numato binary_sensor platform.""" """Tests for the numato binary_sensor platform."""
from homeassistant.const import Platform from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import discovery from homeassistant.helpers import discovery
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -12,7 +13,9 @@ MOCKUP_ENTITY_IDS = {
} }
async def test_failing_setups_no_entities(hass, numato_fixture, monkeypatch): async def test_failing_setups_no_entities(
hass: HomeAssistant, numato_fixture, monkeypatch
) -> None:
"""When port setup fails, no entity shall be created.""" """When port setup fails, no entity shall be created."""
monkeypatch.setattr(numato_fixture.NumatoDeviceMock, "setup", mockup_raise) monkeypatch.setattr(numato_fixture.NumatoDeviceMock, "setup", mockup_raise)
assert await async_setup_component(hass, "numato", NUMATO_CFG) assert await async_setup_component(hass, "numato", NUMATO_CFG)
@ -21,7 +24,9 @@ async def test_failing_setups_no_entities(hass, numato_fixture, monkeypatch):
assert entity_id not in hass.states.async_entity_ids() assert entity_id not in hass.states.async_entity_ids()
async def test_setup_callbacks(hass, numato_fixture, monkeypatch): async def test_setup_callbacks(
hass: HomeAssistant, numato_fixture, monkeypatch
) -> None:
"""During setup a callback shall be registered.""" """During setup a callback shall be registered."""
numato_fixture.discover() numato_fixture.discover()
@ -38,7 +43,9 @@ async def test_setup_callbacks(hass, numato_fixture, monkeypatch):
assert await async_setup_component(hass, "numato", NUMATO_CFG) assert await async_setup_component(hass, "numato", NUMATO_CFG)
async def test_hass_binary_sensor_notification(hass, numato_fixture): async def test_hass_binary_sensor_notification(
hass: HomeAssistant, numato_fixture
) -> None:
"""Test regular operations from within Home Assistant.""" """Test regular operations from within Home Assistant."""
assert await async_setup_component(hass, "numato", NUMATO_CFG) assert await async_setup_component(hass, "numato", NUMATO_CFG)
await hass.async_block_till_done() # wait until services are registered await hass.async_block_till_done() # wait until services are registered
@ -52,7 +59,9 @@ async def test_hass_binary_sensor_notification(hass, numato_fixture):
) )
async def test_binary_sensor_setup_without_discovery_info(hass, config, numato_fixture): async def test_binary_sensor_setup_without_discovery_info(
hass: HomeAssistant, config, numato_fixture
) -> None:
"""Test handling of empty discovery_info.""" """Test handling of empty discovery_info."""
numato_fixture.discover() numato_fixture.discover()
await discovery.async_load_platform( await discovery.async_load_platform(

View file

@ -3,12 +3,15 @@ from numato_gpio import NumatoGpioError
import pytest import pytest
from homeassistant.components import numato from homeassistant.components import numato
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from .common import NUMATO_CFG, mockup_raise, mockup_return from .common import NUMATO_CFG, mockup_raise, mockup_return
async def test_setup_no_devices(hass, numato_fixture, monkeypatch): async def test_setup_no_devices(
hass: HomeAssistant, numato_fixture, monkeypatch
) -> None:
"""Test handling of an 'empty' discovery. """Test handling of an 'empty' discovery.
Platform setups are expected to return after handling errors locally Platform setups are expected to return after handling errors locally
@ -19,7 +22,9 @@ async def test_setup_no_devices(hass, numato_fixture, monkeypatch):
assert len(numato_fixture.devices) == 0 assert len(numato_fixture.devices) == 0
async def test_fail_setup_raising_discovery(hass, numato_fixture, caplog, monkeypatch): async def test_fail_setup_raising_discovery(
hass: HomeAssistant, numato_fixture, caplog: pytest.LogCaptureFixture, monkeypatch
) -> None:
"""Test handling of an exception during discovery. """Test handling of an exception during discovery.
Setup shall return False. Setup shall return False.
@ -29,7 +34,9 @@ async def test_fail_setup_raising_discovery(hass, numato_fixture, caplog, monkey
await hass.async_block_till_done() await hass.async_block_till_done()
async def test_hass_numato_api_wrong_port_directions(hass, numato_fixture): async def test_hass_numato_api_wrong_port_directions(
hass: HomeAssistant, numato_fixture
) -> None:
"""Test handling of wrong port directions. """Test handling of wrong port directions.
This won't happen in the current platform implementation but would raise This won't happen in the current platform implementation but would raise
@ -46,7 +53,9 @@ async def test_hass_numato_api_wrong_port_directions(hass, numato_fixture):
api.write_output(0, 2, 1) # write to input api.write_output(0, 2, 1) # write to input
async def test_hass_numato_api_errors(hass, numato_fixture, monkeypatch): async def test_hass_numato_api_errors(
hass: HomeAssistant, numato_fixture, monkeypatch
) -> None:
"""Test whether Home Assistant numato API (re-)raises errors.""" """Test whether Home Assistant numato API (re-)raises errors."""
numato_fixture.discover() numato_fixture.discover()
monkeypatch.setattr(numato_fixture.devices[0], "setup", mockup_raise) monkeypatch.setattr(numato_fixture.devices[0], "setup", mockup_raise)
@ -61,7 +70,7 @@ async def test_hass_numato_api_errors(hass, numato_fixture, monkeypatch):
api.write_output(0, 2, 1) api.write_output(0, 2, 1)
async def test_invalid_port_number(hass, numato_fixture, config): async def test_invalid_port_number(hass: HomeAssistant, numato_fixture, config) -> None:
"""Test validation of ADC port number type.""" """Test validation of ADC port number type."""
sensorports_cfg = config["numato"]["devices"][0]["sensors"]["ports"] sensorports_cfg = config["numato"]["devices"][0]["sensors"]["ports"]
port1_config = sensorports_cfg["1"] port1_config = sensorports_cfg["1"]
@ -72,7 +81,9 @@ async def test_invalid_port_number(hass, numato_fixture, config):
assert not numato_fixture.devices assert not numato_fixture.devices
async def test_too_low_adc_port_number(hass, numato_fixture, config): async def test_too_low_adc_port_number(
hass: HomeAssistant, numato_fixture, config
) -> None:
"""Test handling of failing component setup. """Test handling of failing component setup.
Tries setting up an ADC on a port below (0) the allowed range. Tries setting up an ADC on a port below (0) the allowed range.
@ -84,7 +95,9 @@ async def test_too_low_adc_port_number(hass, numato_fixture, config):
assert not numato_fixture.devices assert not numato_fixture.devices
async def test_too_high_adc_port_number(hass, numato_fixture, config): async def test_too_high_adc_port_number(
hass: HomeAssistant, numato_fixture, config
) -> None:
"""Test handling of failing component setup. """Test handling of failing component setup.
Tries setting up an ADC on a port above (8) the allowed range. Tries setting up an ADC on a port above (8) the allowed range.
@ -95,7 +108,9 @@ async def test_too_high_adc_port_number(hass, numato_fixture, config):
assert not numato_fixture.devices assert not numato_fixture.devices
async def test_invalid_adc_range_value_type(hass, numato_fixture, config): async def test_invalid_adc_range_value_type(
hass: HomeAssistant, numato_fixture, config
) -> None:
"""Test validation of ADC range config's types. """Test validation of ADC range config's types.
Replaces the source range beginning by a string. Replaces the source range beginning by a string.
@ -106,7 +121,9 @@ async def test_invalid_adc_range_value_type(hass, numato_fixture, config):
assert not numato_fixture.devices assert not numato_fixture.devices
async def test_invalid_adc_source_range_length(hass, numato_fixture, config): async def test_invalid_adc_source_range_length(
hass: HomeAssistant, numato_fixture, config
) -> None:
"""Test validation of ADC range config's length. """Test validation of ADC range config's length.
Adds an element to the source range. Adds an element to the source range.
@ -117,7 +134,9 @@ async def test_invalid_adc_source_range_length(hass, numato_fixture, config):
assert not numato_fixture.devices assert not numato_fixture.devices
async def test_invalid_adc_source_range_order(hass, numato_fixture, config): async def test_invalid_adc_source_range_order(
hass: HomeAssistant, numato_fixture, config
) -> None:
"""Test validation of ADC range config's order. """Test validation of ADC range config's order.
Sets the source range to a decreasing [2, 1]. Sets the source range to a decreasing [2, 1].
@ -128,7 +147,9 @@ async def test_invalid_adc_source_range_order(hass, numato_fixture, config):
assert not numato_fixture.devices assert not numato_fixture.devices
async def test_invalid_adc_destination_range_value_type(hass, numato_fixture, config): async def test_invalid_adc_destination_range_value_type(
hass: HomeAssistant, numato_fixture, config
) -> None:
"""Test validation of ADC range . """Test validation of ADC range .
Replaces the destination range beginning by a string. Replaces the destination range beginning by a string.
@ -139,7 +160,9 @@ async def test_invalid_adc_destination_range_value_type(hass, numato_fixture, co
assert not numato_fixture.devices assert not numato_fixture.devices
async def test_invalid_adc_destination_range_length(hass, numato_fixture, config): async def test_invalid_adc_destination_range_length(
hass: HomeAssistant, numato_fixture, config
) -> None:
"""Test validation of ADC range config's length. """Test validation of ADC range config's length.
Adds an element to the destination range. Adds an element to the destination range.
@ -150,7 +173,9 @@ async def test_invalid_adc_destination_range_length(hass, numato_fixture, config
assert not numato_fixture.devices assert not numato_fixture.devices
async def test_invalid_adc_destination_range_order(hass, numato_fixture, config): async def test_invalid_adc_destination_range_order(
hass: HomeAssistant, numato_fixture, config
) -> None:
"""Test validation of ADC range config's order. """Test validation of ADC range config's order.
Sets the destination range to a decreasing [2, 1]. Sets the destination range to a decreasing [2, 1].

View file

@ -1,5 +1,6 @@
"""Tests for the numato sensor platform.""" """Tests for the numato sensor platform."""
from homeassistant.const import STATE_UNKNOWN, Platform from homeassistant.const import STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import discovery from homeassistant.helpers import discovery
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -10,7 +11,9 @@ MOCKUP_ENTITY_IDS = {
} }
async def test_failing_setups_no_entities(hass, numato_fixture, monkeypatch): async def test_failing_setups_no_entities(
hass: HomeAssistant, numato_fixture, monkeypatch
) -> None:
"""When port setup fails, no entity shall be created.""" """When port setup fails, no entity shall be created."""
monkeypatch.setattr(numato_fixture.NumatoDeviceMock, "setup", mockup_raise) monkeypatch.setattr(numato_fixture.NumatoDeviceMock, "setup", mockup_raise)
assert await async_setup_component(hass, "numato", NUMATO_CFG) assert await async_setup_component(hass, "numato", NUMATO_CFG)
@ -19,7 +22,9 @@ async def test_failing_setups_no_entities(hass, numato_fixture, monkeypatch):
assert entity_id not in hass.states.async_entity_ids() assert entity_id not in hass.states.async_entity_ids()
async def test_failing_sensor_update(hass, numato_fixture, monkeypatch): async def test_failing_sensor_update(
hass: HomeAssistant, numato_fixture, monkeypatch
) -> None:
"""Test condition when a sensor update fails.""" """Test condition when a sensor update fails."""
monkeypatch.setattr(numato_fixture.NumatoDeviceMock, "adc_read", mockup_raise) monkeypatch.setattr(numato_fixture.NumatoDeviceMock, "adc_read", mockup_raise)
assert await async_setup_component(hass, "numato", NUMATO_CFG) assert await async_setup_component(hass, "numato", NUMATO_CFG)
@ -27,7 +32,9 @@ async def test_failing_sensor_update(hass, numato_fixture, monkeypatch):
assert hass.states.get("sensor.numato_adc_mock_port1").state is STATE_UNKNOWN assert hass.states.get("sensor.numato_adc_mock_port1").state is STATE_UNKNOWN
async def test_sensor_setup_without_discovery_info(hass, config, numato_fixture): async def test_sensor_setup_without_discovery_info(
hass: HomeAssistant, config, numato_fixture
) -> None:
"""Test handling of empty discovery_info.""" """Test handling of empty discovery_info."""
numato_fixture.discover() numato_fixture.discover()
await discovery.async_load_platform(hass, Platform.SENSOR, "numato", None, config) await discovery.async_load_platform(hass, Platform.SENSOR, "numato", None, config)

View file

@ -6,6 +6,7 @@ from homeassistant.const import (
SERVICE_TURN_ON, SERVICE_TURN_ON,
Platform, Platform,
) )
from homeassistant.core import HomeAssistant
from homeassistant.helpers import discovery from homeassistant.helpers import discovery
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -17,7 +18,9 @@ MOCKUP_ENTITY_IDS = {
} }
async def test_failing_setups_no_entities(hass, numato_fixture, monkeypatch): async def test_failing_setups_no_entities(
hass: HomeAssistant, numato_fixture, monkeypatch
) -> None:
"""When port setup fails, no entity shall be created.""" """When port setup fails, no entity shall be created."""
monkeypatch.setattr(numato_fixture.NumatoDeviceMock, "setup", mockup_raise) monkeypatch.setattr(numato_fixture.NumatoDeviceMock, "setup", mockup_raise)
assert await async_setup_component(hass, "numato", NUMATO_CFG) assert await async_setup_component(hass, "numato", NUMATO_CFG)
@ -26,7 +29,7 @@ async def test_failing_setups_no_entities(hass, numato_fixture, monkeypatch):
assert entity_id not in hass.states.async_entity_ids() assert entity_id not in hass.states.async_entity_ids()
async def test_regular_hass_operations(hass, numato_fixture): async def test_regular_hass_operations(hass: HomeAssistant, numato_fixture) -> None:
"""Test regular operations from within Home Assistant.""" """Test regular operations from within Home Assistant."""
assert await async_setup_component(hass, "numato", NUMATO_CFG) assert await async_setup_component(hass, "numato", NUMATO_CFG)
await hass.async_block_till_done() # wait until services are registered await hass.async_block_till_done() # wait until services are registered
@ -64,7 +67,9 @@ async def test_regular_hass_operations(hass, numato_fixture):
assert numato_fixture.devices[0].values[6] == 0 assert numato_fixture.devices[0].values[6] == 0
async def test_failing_hass_operations(hass, numato_fixture, monkeypatch): async def test_failing_hass_operations(
hass: HomeAssistant, numato_fixture, monkeypatch
) -> None:
"""Test failing operations called from within Home Assistant. """Test failing operations called from within Home Assistant.
Switches remain in their initial 'off' state when the device can't Switches remain in their initial 'off' state when the device can't
@ -108,7 +113,9 @@ async def test_failing_hass_operations(hass, numato_fixture, monkeypatch):
assert not numato_fixture.devices[0].values[6] assert not numato_fixture.devices[0].values[6]
async def test_switch_setup_without_discovery_info(hass, config, numato_fixture): async def test_switch_setup_without_discovery_info(
hass: HomeAssistant, config, numato_fixture
) -> None:
"""Test handling of empty discovery_info.""" """Test handling of empty discovery_info."""
numato_fixture.discover() numato_fixture.discover()
await discovery.async_load_platform(hass, Platform.SWITCH, "numato", None, config) await discovery.async_load_platform(hass, Platform.SWITCH, "numato", None, config)

View file

@ -7,7 +7,11 @@ from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.number import DOMAIN, device_action from homeassistant.components.number import DOMAIN, device_action
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
@ -20,7 +24,11 @@ from tests.common import (
from tests.components.blueprint.conftest import stub_blueprint_populate # noqa: F401 from tests.components.blueprint.conftest import stub_blueprint_populate # noqa: F401
async def test_get_actions(hass, device_registry, entity_registry): async def test_get_actions(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected actions for an entity.""" """Test we get the expected actions for an 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)
@ -57,12 +65,12 @@ async def test_get_actions(hass, device_registry, entity_registry):
), ),
) )
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)
@ -95,7 +103,11 @@ async def test_get_actions_hidden_auxiliary(
assert_lists_same(actions, expected_actions) assert_lists_same(actions, expected_actions)
async def test_get_action_no_state(hass, device_registry, entity_registry): async def test_get_action_no_state(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected actions for an entity.""" """Test we get the expected actions for an 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)

View file

@ -1,4 +1,5 @@
"""The tests for the Number component.""" """The tests for the Number component."""
from typing import Any
from unittest.mock import MagicMock from unittest.mock import MagicMock
import pytest import pytest
@ -236,7 +237,9 @@ async def test_attributes(hass: HomeAssistant) -> None:
assert number_4.value is None assert number_4.value is None
async def test_deprecation_warnings(hass: HomeAssistant, caplog) -> None: async def test_deprecation_warnings(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test overriding the deprecated attributes is possible and warnings are logged.""" """Test overriding the deprecated attributes is possible and warnings are logged."""
number = MockDefaultNumberEntityDeprecated() number = MockDefaultNumberEntityDeprecated()
number.hass = hass number.hass = hass
@ -503,8 +506,8 @@ async def test_deprecated_methods(
], ],
) )
async def test_temperature_conversion( async def test_temperature_conversion(
hass, hass: HomeAssistant,
enable_custom_integrations, enable_custom_integrations: None,
unit_system, unit_system,
native_unit, native_unit,
state_unit, state_unit,
@ -518,7 +521,7 @@ async def test_temperature_conversion(
state_min_value, state_min_value,
native_step, native_step,
state_step, state_step,
): ) -> None:
"""Test temperature conversion.""" """Test temperature conversion."""
hass.config.units = unit_system hass.config.units = unit_system
platform = getattr(hass.components, f"test.{DOMAIN}") platform = getattr(hass.components, f"test.{DOMAIN}")
@ -596,10 +599,10 @@ RESTORE_DATA = {
async def test_restore_number_save_state( async def test_restore_number_save_state(
hass, hass: HomeAssistant,
hass_storage, hass_storage: dict[str, Any],
enable_custom_integrations, enable_custom_integrations: None,
): ) -> None:
"""Test RestoreNumber.""" """Test RestoreNumber."""
platform = getattr(hass.components, "test.number") platform = getattr(hass.components, "test.number")
platform.init(empty=True) platform.init(empty=True)
@ -659,9 +662,9 @@ async def test_restore_number_save_state(
], ],
) )
async def test_restore_number_restore_state( async def test_restore_number_restore_state(
hass, hass: HomeAssistant,
enable_custom_integrations, enable_custom_integrations: None,
hass_storage, hass_storage: dict[str, Any],
native_max_value, native_max_value,
native_min_value, native_min_value,
native_step, native_step,
@ -670,7 +673,7 @@ async def test_restore_number_restore_state(
extra_data, extra_data,
device_class, device_class,
uom, uom,
): ) -> None:
"""Test RestoreNumber.""" """Test RestoreNumber."""
mock_restore_cache_with_extra_data(hass, ((State("number.test", ""), extra_data),)) mock_restore_cache_with_extra_data(hass, ((State("number.test", ""), extra_data),))
@ -729,15 +732,15 @@ async def test_restore_number_restore_state(
], ],
) )
async def test_custom_unit( async def test_custom_unit(
hass, hass: HomeAssistant,
enable_custom_integrations, enable_custom_integrations: None,
device_class, device_class,
native_unit, native_unit,
custom_unit, custom_unit,
state_unit, state_unit,
native_value, native_value,
custom_value, custom_value,
): ) -> None:
"""Test custom unit.""" """Test custom unit."""
entity_registry = er.async_get(hass) entity_registry = er.async_get(hass)
@ -802,8 +805,8 @@ async def test_custom_unit(
], ],
) )
async def test_custom_unit_change( async def test_custom_unit_change(
hass, hass: HomeAssistant,
enable_custom_integrations, enable_custom_integrations: None,
native_unit, native_unit,
custom_unit, custom_unit,
used_custom_unit, used_custom_unit,
@ -811,7 +814,7 @@ async def test_custom_unit_change(
native_value, native_value,
custom_value, custom_value,
default_value, default_value,
): ) -> None:
"""Test custom unit changes are picked up.""" """Test custom unit changes are picked up."""
entity_registry = er.async_get(hass) entity_registry = er.async_get(hass)
platform = getattr(hass.components, "test.number") platform = getattr(hass.components, "test.number")

View file

@ -5,10 +5,11 @@ from datetime import timedelta
from homeassistant.components import number from homeassistant.components import number
from homeassistant.components.number import ATTR_MAX, ATTR_MIN, ATTR_MODE, ATTR_STEP from homeassistant.components.number import ATTR_MAX, ATTR_MIN, ATTR_MODE, ATTR_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
@ -16,7 +17,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 number registered attributes to be excluded.""" """Test number registered attributes to be excluded."""
await async_setup_component( await async_setup_component(
hass, number.DOMAIN, {number.DOMAIN: {"platform": "demo"}} hass, number.DOMAIN, {number.DOMAIN: {"platform": "demo"}}

View file

@ -5,8 +5,12 @@ from homeassistant.components.number.const import DOMAIN
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.typing import WebSocketGenerator
async def test_device_class_units(hass: HomeAssistant, hass_ws_client) -> None:
async def test_device_class_units(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test we can get supported units.""" """Test we can get supported units."""
assert await async_setup_component(hass, DOMAIN, {}) assert await async_setup_component(hass, DOMAIN, {})

View file

@ -5,9 +5,10 @@ import aiohttp
from homeassistant import config_entries from homeassistant import config_entries
from homeassistant.components.nws.const import DOMAIN from homeassistant.components.nws.const import DOMAIN
from homeassistant.core import HomeAssistant
async def test_form(hass, mock_simple_nws_config): async def test_form(hass: HomeAssistant, mock_simple_nws_config) -> None:
"""Test we get the form.""" """Test we get the form."""
hass.config.latitude = 35 hass.config.latitude = 35
hass.config.longitude = -90 hass.config.longitude = -90
@ -38,7 +39,7 @@ async def test_form(hass, mock_simple_nws_config):
assert len(mock_setup_entry.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
async def test_form_cannot_connect(hass, mock_simple_nws_config): async def test_form_cannot_connect(hass: HomeAssistant, mock_simple_nws_config) -> None:
"""Test we handle cannot connect error.""" """Test we handle cannot connect error."""
mock_instance = mock_simple_nws_config.return_value mock_instance = mock_simple_nws_config.return_value
mock_instance.set_station.side_effect = aiohttp.ClientError mock_instance.set_station.side_effect = aiohttp.ClientError
@ -56,7 +57,7 @@ async def test_form_cannot_connect(hass, mock_simple_nws_config):
assert result2["errors"] == {"base": "cannot_connect"} assert result2["errors"] == {"base": "cannot_connect"}
async def test_form_unknown_error(hass, mock_simple_nws_config): async def test_form_unknown_error(hass: HomeAssistant, mock_simple_nws_config) -> None:
"""Test we handle unknown error.""" """Test we handle unknown error."""
mock_instance = mock_simple_nws_config.return_value mock_instance = mock_simple_nws_config.return_value
mock_instance.set_station.side_effect = ValueError mock_instance.set_station.side_effect = ValueError
@ -74,7 +75,9 @@ async def test_form_unknown_error(hass, mock_simple_nws_config):
assert result2["errors"] == {"base": "unknown"} assert result2["errors"] == {"base": "unknown"}
async def test_form_already_configured(hass, mock_simple_nws_config): async def test_form_already_configured(
hass: HomeAssistant, mock_simple_nws_config
) -> None:
"""Test we handle duplicate entries.""" """Test we handle duplicate entries."""
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

@ -2,13 +2,14 @@
from homeassistant.components.nws.const import DOMAIN from homeassistant.components.nws.const import DOMAIN
from homeassistant.components.weather import DOMAIN as WEATHER_DOMAIN from homeassistant.components.weather import DOMAIN as WEATHER_DOMAIN
from homeassistant.const import STATE_UNAVAILABLE from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from .const import NWS_CONFIG from .const import NWS_CONFIG
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
async def test_unload_entry(hass, mock_simple_nws): async def test_unload_entry(hass: HomeAssistant, mock_simple_nws) -> None:
"""Test that nws setup with config yaml.""" """Test that nws setup with config yaml."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,

View file

@ -5,6 +5,7 @@ from homeassistant.components.nws.const import ATTRIBUTION, DOMAIN
from homeassistant.components.nws.sensor import SENSOR_TYPES from homeassistant.components.nws.sensor import SENSOR_TYPES
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.const import ATTR_ATTRIBUTION, STATE_UNKNOWN from homeassistant.const import ATTR_ATTRIBUTION, STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from homeassistant.util import slugify from homeassistant.util import slugify
from homeassistant.util.unit_system import METRIC_SYSTEM, US_CUSTOMARY_SYSTEM from homeassistant.util.unit_system import METRIC_SYSTEM, US_CUSTOMARY_SYSTEM
@ -33,8 +34,13 @@ from tests.common import MockConfigEntry
], ],
) )
async def test_imperial_metric( async def test_imperial_metric(
hass, units, result_observation, result_forecast, mock_simple_nws, no_weather hass: HomeAssistant,
): units,
result_observation,
result_forecast,
mock_simple_nws,
no_weather,
) -> None:
"""Test with imperial and metric units.""" """Test with imperial and metric units."""
registry = er.async_get(hass) registry = er.async_get(hass)
@ -64,7 +70,7 @@ async def test_imperial_metric(
assert state.attributes.get(ATTR_ATTRIBUTION) == ATTRIBUTION assert state.attributes.get(ATTR_ATTRIBUTION) == ATTRIBUTION
async def test_none_values(hass, mock_simple_nws, no_weather): async def test_none_values(hass: HomeAssistant, mock_simple_nws, no_weather) -> None:
"""Test with no values.""" """Test with no values."""
instance = mock_simple_nws.return_value instance = mock_simple_nws.return_value
instance.observation = NONE_OBSERVATION instance.observation = NONE_OBSERVATION

View file

@ -12,6 +12,7 @@ from homeassistant.components.weather import (
DOMAIN as WEATHER_DOMAIN, DOMAIN as WEATHER_DOMAIN,
) )
from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.core import HomeAssistant
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
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
@ -42,8 +43,13 @@ from tests.common import MockConfigEntry, async_fire_time_changed
], ],
) )
async def test_imperial_metric( async def test_imperial_metric(
hass, units, result_observation, result_forecast, mock_simple_nws, no_sensor hass: HomeAssistant,
): units,
result_observation,
result_forecast,
mock_simple_nws,
no_sensor,
) -> None:
"""Test with imperial and metric units.""" """Test with imperial and metric units."""
# enable the hourly entity # enable the hourly entity
registry = er.async_get(hass) registry = er.async_get(hass)
@ -91,7 +97,7 @@ async def test_imperial_metric(
assert forecast[0].get(key) == value assert forecast[0].get(key) == value
async def test_none_values(hass, mock_simple_nws, no_sensor): async def test_none_values(hass: HomeAssistant, mock_simple_nws, no_sensor) -> None:
"""Test with none values in observation and forecast dicts.""" """Test with none values in observation and forecast dicts."""
instance = mock_simple_nws.return_value instance = mock_simple_nws.return_value
instance.observation = NONE_OBSERVATION instance.observation = NONE_OBSERVATION
@ -116,7 +122,7 @@ async def test_none_values(hass, mock_simple_nws, no_sensor):
assert forecast[0].get(key) is None assert forecast[0].get(key) is None
async def test_none(hass, mock_simple_nws, no_sensor): async def test_none(hass: HomeAssistant, mock_simple_nws, no_sensor) -> None:
"""Test with None as observation and forecast.""" """Test with None as observation and forecast."""
instance = mock_simple_nws.return_value instance = mock_simple_nws.return_value
instance.observation = None instance.observation = None
@ -142,7 +148,7 @@ async def test_none(hass, mock_simple_nws, no_sensor):
assert forecast is None assert forecast is None
async def test_error_station(hass, mock_simple_nws, no_sensor): async def test_error_station(hass: HomeAssistant, mock_simple_nws, no_sensor) -> None:
"""Test error in setting station.""" """Test error in setting station."""
instance = mock_simple_nws.return_value instance = mock_simple_nws.return_value
@ -160,7 +166,7 @@ async def test_error_station(hass, mock_simple_nws, no_sensor):
assert hass.states.get("weather.abc_daynight") is None assert hass.states.get("weather.abc_daynight") is None
async def test_entity_refresh(hass, mock_simple_nws, no_sensor): async def test_entity_refresh(hass: HomeAssistant, mock_simple_nws, no_sensor) -> None:
"""Test manual refresh.""" """Test manual refresh."""
instance = mock_simple_nws.return_value instance = mock_simple_nws.return_value
@ -189,7 +195,9 @@ async def test_entity_refresh(hass, mock_simple_nws, no_sensor):
instance.update_forecast_hourly.assert_called_once() instance.update_forecast_hourly.assert_called_once()
async def test_error_observation(hass, mock_simple_nws, no_sensor): async def test_error_observation(
hass: HomeAssistant, mock_simple_nws, no_sensor
) -> None:
"""Test error during update observation.""" """Test error during update observation."""
utc_time = dt_util.utcnow() utc_time = dt_util.utcnow()
with patch("homeassistant.components.nws.utcnow") as mock_utc, patch( with patch("homeassistant.components.nws.utcnow") as mock_utc, patch(
@ -253,7 +261,7 @@ async def test_error_observation(hass, mock_simple_nws, no_sensor):
assert state.state == STATE_UNAVAILABLE assert state.state == STATE_UNAVAILABLE
async def test_error_forecast(hass, mock_simple_nws, no_sensor): async def test_error_forecast(hass: HomeAssistant, mock_simple_nws, no_sensor) -> None:
"""Test error during update forecast.""" """Test error during update forecast."""
instance = mock_simple_nws.return_value instance = mock_simple_nws.return_value
instance.update_forecast.side_effect = aiohttp.ClientError instance.update_forecast.side_effect = aiohttp.ClientError
@ -284,7 +292,9 @@ async def test_error_forecast(hass, mock_simple_nws, no_sensor):
assert state.state == ATTR_CONDITION_SUNNY assert state.state == ATTR_CONDITION_SUNNY
async def test_error_forecast_hourly(hass, mock_simple_nws, no_sensor): async def test_error_forecast_hourly(
hass: HomeAssistant, mock_simple_nws, no_sensor
) -> None:
"""Test error during update forecast hourly.""" """Test error during update forecast hourly."""
instance = mock_simple_nws.return_value instance = mock_simple_nws.return_value
instance.update_forecast_hourly.side_effect = aiohttp.ClientError instance.update_forecast_hourly.side_effect = aiohttp.ClientError
@ -325,7 +335,9 @@ async def test_error_forecast_hourly(hass, mock_simple_nws, no_sensor):
assert state.state == ATTR_CONDITION_SUNNY assert state.state == ATTR_CONDITION_SUNNY
async def test_forecast_hourly_disable_enable(hass, mock_simple_nws, no_sensor): async def test_forecast_hourly_disable_enable(
hass: HomeAssistant, mock_simple_nws, no_sensor
) -> None:
"""Test error during update forecast hourly.""" """Test error during update forecast hourly."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=nws.DOMAIN, domain=nws.DOMAIN,

View file

@ -56,7 +56,9 @@ def client(fake_zones):
@pytest.mark.usefixtures("client") @pytest.mark.usefixtures("client")
@mock.patch("homeassistant.components.nx584.binary_sensor.NX584Watcher") @mock.patch("homeassistant.components.nx584.binary_sensor.NX584Watcher")
@mock.patch("homeassistant.components.nx584.binary_sensor.NX584ZoneSensor") @mock.patch("homeassistant.components.nx584.binary_sensor.NX584ZoneSensor")
def test_nx584_sensor_setup_defaults(mock_nx, mock_watcher, hass, fake_zones): def test_nx584_sensor_setup_defaults(
mock_nx, mock_watcher, hass: HomeAssistant, fake_zones
) -> None:
"""Test the setup with no configuration.""" """Test the setup with no configuration."""
add_entities = mock.MagicMock() add_entities = mock.MagicMock()
config = DEFAULT_CONFIG config = DEFAULT_CONFIG
@ -70,7 +72,9 @@ def test_nx584_sensor_setup_defaults(mock_nx, mock_watcher, hass, fake_zones):
@pytest.mark.usefixtures("client") @pytest.mark.usefixtures("client")
@mock.patch("homeassistant.components.nx584.binary_sensor.NX584Watcher") @mock.patch("homeassistant.components.nx584.binary_sensor.NX584Watcher")
@mock.patch("homeassistant.components.nx584.binary_sensor.NX584ZoneSensor") @mock.patch("homeassistant.components.nx584.binary_sensor.NX584ZoneSensor")
def test_nx584_sensor_setup_full_config(mock_nx, mock_watcher, hass, fake_zones): def test_nx584_sensor_setup_full_config(
mock_nx, mock_watcher, hass: HomeAssistant, fake_zones
) -> None:
"""Test the setup with full configuration.""" """Test the setup with full configuration."""
config = { config = {
"host": "foo", "host": "foo",
@ -107,7 +111,7 @@ async def _test_assert_graceful_fail(hass, config):
({"zone_types": {"notazone": "motion"}}), ({"zone_types": {"notazone": "motion"}}),
], ],
) )
async def test_nx584_sensor_setup_bad_config(hass, config): async def test_nx584_sensor_setup_bad_config(hass: HomeAssistant, config) -> None:
"""Test the setup with bad configuration.""" """Test the setup with bad configuration."""
await _test_assert_graceful_fail(hass, config) await _test_assert_graceful_fail(hass, config)
@ -120,7 +124,9 @@ async def test_nx584_sensor_setup_bad_config(hass, config):
pytest.param(IndexError, id="no_partitions"), pytest.param(IndexError, id="no_partitions"),
], ],
) )
async def test_nx584_sensor_setup_with_exceptions(hass, exception_type): async def test_nx584_sensor_setup_with_exceptions(
hass: HomeAssistant, exception_type
) -> None:
"""Test the setup handles exceptions.""" """Test the setup handles exceptions."""
nx584_client.Client.return_value.list_zones.side_effect = exception_type nx584_client.Client.return_value.list_zones.side_effect = exception_type
await _test_assert_graceful_fail(hass, {}) await _test_assert_graceful_fail(hass, {})
@ -177,7 +183,7 @@ def test_nx584_zone_sensor_bypassed() -> None:
@mock.patch.object(nx584.NX584ZoneSensor, "schedule_update_ha_state") @mock.patch.object(nx584.NX584ZoneSensor, "schedule_update_ha_state")
def test_nx584_watcher_process_zone_event(mock_update): def test_nx584_watcher_process_zone_event(mock_update) -> None:
"""Test the processing of zone events.""" """Test the processing of zone events."""
zone1 = {"number": 1, "name": "foo", "state": True} zone1 = {"number": 1, "name": "foo", "state": True}
zone2 = {"number": 2, "name": "bar", "state": True} zone2 = {"number": 2, "name": "bar", "state": True}
@ -192,7 +198,7 @@ def test_nx584_watcher_process_zone_event(mock_update):
@mock.patch.object(nx584.NX584ZoneSensor, "schedule_update_ha_state") @mock.patch.object(nx584.NX584ZoneSensor, "schedule_update_ha_state")
def test_nx584_watcher_process_zone_event_missing_zone(mock_update): def test_nx584_watcher_process_zone_event_missing_zone(mock_update) -> None:
"""Test the processing of zone events with missing zones.""" """Test the processing of zone events with missing zones."""
watcher = nx584.NX584Watcher(None, {}) watcher = nx584.NX584Watcher(None, {})
watcher._process_zone_event({"zone": 1, "zone_state": False}) watcher._process_zone_event({"zone": 1, "zone_state": False})
@ -232,7 +238,7 @@ def test_nx584_watcher_run_with_zone_events() -> None:
@mock.patch("time.sleep") @mock.patch("time.sleep")
def test_nx584_watcher_run_retries_failures(mock_sleep): def test_nx584_watcher_run_retries_failures(mock_sleep) -> None:
"""Test the retries with failures.""" """Test the retries with failures."""
empty_me = [1, 2] empty_me = [1, 2]

View file

@ -124,7 +124,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_options_flow(hass, nzbget_api): async def test_options_flow(hass: HomeAssistant, nzbget_api) -> None:
"""Test updating options.""" """Test updating options."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,

View file

@ -12,7 +12,7 @@ from . import ENTRY_CONFIG, _patch_version, init_integration
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
async def test_unload_entry(hass, nzbget_api): async def test_unload_entry(hass: HomeAssistant, nzbget_api) -> None:
"""Test successful unload of entry.""" """Test successful unload of entry."""
entry = await init_integration(hass) entry = await init_integration(hass)

View file

@ -8,13 +8,14 @@ from homeassistant.const import (
UnitOfDataRate, UnitOfDataRate,
UnitOfInformation, UnitOfInformation,
) )
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
from . import init_integration from . import init_integration
async def test_sensors(hass, nzbget_api) -> None: async def test_sensors(hass: HomeAssistant, nzbget_api) -> None:
"""Test the creation and values of the sensors.""" """Test the creation and values of the sensors."""
now = dt_util.utcnow().replace(microsecond=0) now = dt_util.utcnow().replace(microsecond=0)
with patch("homeassistant.components.nzbget.sensor.utcnow", return_value=now): with patch("homeassistant.components.nzbget.sensor.utcnow", return_value=now):

View file

@ -7,13 +7,14 @@ from homeassistant.const import (
STATE_OFF, STATE_OFF,
STATE_ON, STATE_ON,
) )
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er 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 . import init_integration from . import init_integration
async def test_download_switch(hass, nzbget_api) -> None: async def test_download_switch(hass: HomeAssistant, nzbget_api) -> None:
"""Test the creation and values of the download switch.""" """Test the creation and values of the download switch."""
instance = nzbget_api.return_value instance = nzbget_api.return_value
@ -41,7 +42,7 @@ async def test_download_switch(hass, nzbget_api) -> None:
assert state.state == STATE_OFF assert state.state == STATE_OFF
async def test_download_switch_services(hass, nzbget_api) -> None: async def test_download_switch_services(hass: HomeAssistant, nzbget_api) -> None:
"""Test download switch services.""" """Test download switch services."""
instance = nzbget_api.return_value instance = nzbget_api.return_value

View file

@ -14,7 +14,7 @@ from homeassistant.core import HomeAssistant
from . import init_integration from . import init_integration
async def test_pause_job(hass: HomeAssistant): async def test_pause_job(hass: HomeAssistant) -> None:
"""Test the pause job button.""" """Test the pause job button."""
await init_integration(hass, BUTTON_DOMAIN) await init_integration(hass, BUTTON_DOMAIN)
@ -74,7 +74,7 @@ async def test_pause_job(hass: HomeAssistant):
) )
async def test_resume_job(hass: HomeAssistant): async def test_resume_job(hass: HomeAssistant) -> None:
"""Test the resume job button.""" """Test the resume job button."""
await init_integration(hass, BUTTON_DOMAIN) await init_integration(hass, BUTTON_DOMAIN)
@ -134,7 +134,7 @@ async def test_resume_job(hass: HomeAssistant):
) )
async def test_stop_job(hass: HomeAssistant): async def test_stop_job(hass: HomeAssistant) -> None:
"""Test the stop job button.""" """Test the stop job button."""
await init_integration(hass, BUTTON_DOMAIN) await init_integration(hass, BUTTON_DOMAIN)

View file

@ -1,4 +1,5 @@
"""Tests for the init.""" """Tests for the init."""
from typing import Any
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
from homeassistant.components import onboarding from homeassistant.components import onboarding
@ -12,7 +13,9 @@ from tests.common import MockUser, mock_coro
# Temporarily: if auth not active, always set onboarded=True # Temporarily: if auth not active, always set onboarded=True
async def test_not_setup_views_if_onboarded(hass, hass_storage): async def test_not_setup_views_if_onboarded(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test if onboarding is done, we don't setup views.""" """Test if onboarding is done, we don't setup views."""
mock_storage(hass_storage, {"done": onboarding.STEPS}) mock_storage(hass_storage, {"done": onboarding.STEPS})
@ -66,7 +69,9 @@ async def test_is_user_onboarded() -> None:
assert not onboarding.async_is_user_onboarded(hass) assert not onboarding.async_is_user_onboarded(hass)
async def test_having_owner_finishes_user_step(hass, hass_storage): async def test_having_owner_finishes_user_step(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""If owner user already exists, mark user step as complete.""" """If owner user already exists, mark user step as complete."""
MockUser(is_owner=True).add_to_hass(hass) MockUser(is_owner=True).add_to_hass(hass)
@ -83,7 +88,7 @@ async def test_having_owner_finishes_user_step(hass, hass_storage):
assert onboarding.STEP_USER in done assert onboarding.STEP_USER in done
async def test_migration(hass, hass_storage): async def test_migration(hass: HomeAssistant, hass_storage: dict[str, Any]) -> None:
"""Test migrating onboarding to new version.""" """Test migrating onboarding to new version."""
hass_storage[onboarding.STORAGE_KEY] = {"version": 1, "data": {"done": ["user"]}} hass_storage[onboarding.STORAGE_KEY] = {"version": 1, "data": {"done": ["user"]}}
assert await async_setup_component(hass, "onboarding", {}) assert await async_setup_component(hass, "onboarding", {})

View file

@ -2,18 +2,27 @@
import asyncio import asyncio
from http import HTTPStatus from http import HTTPStatus
import os import os
from typing import Any
from unittest.mock import patch from unittest.mock import patch
import pytest import pytest
from homeassistant.components import onboarding from homeassistant.components import onboarding
from homeassistant.components.onboarding import const, views from homeassistant.components.onboarding import const, views
from homeassistant.core import HomeAssistant
from homeassistant.helpers import area_registry as ar from homeassistant.helpers import area_registry as ar
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from . import mock_storage from . import mock_storage
from tests.common import CLIENT_ID, CLIENT_REDIRECT_URI, register_auth_provider from tests.common import (
CLIENT_ID,
CLIENT_REDIRECT_URI,
MockUser,
register_auth_provider,
)
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import ClientSessionGenerator
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
@ -112,7 +121,11 @@ def mock_default_integrations():
yield yield
async def test_onboarding_progress(hass, hass_storage, hass_client_no_auth): async def test_onboarding_progress(
hass: HomeAssistant,
hass_storage: dict[str, Any],
hass_client_no_auth: ClientSessionGenerator,
) -> None:
"""Test fetching progress.""" """Test fetching progress."""
mock_storage(hass_storage, {"done": ["hello"]}) mock_storage(hass_storage, {"done": ["hello"]})
@ -131,7 +144,11 @@ async def test_onboarding_progress(hass, hass_storage, hass_client_no_auth):
assert data[1] == {"step": "world", "done": False} assert data[1] == {"step": "world", "done": False}
async def test_onboarding_user_already_done(hass, hass_storage, hass_client_no_auth): async def test_onboarding_user_already_done(
hass: HomeAssistant,
hass_storage: dict[str, Any],
hass_client_no_auth: ClientSessionGenerator,
) -> None:
"""Test creating a new user when user step already done.""" """Test creating a new user when user step already done."""
mock_storage(hass_storage, {"done": [views.STEP_USER]}) mock_storage(hass_storage, {"done": [views.STEP_USER]})
@ -155,7 +172,11 @@ async def test_onboarding_user_already_done(hass, hass_storage, hass_client_no_a
assert resp.status == HTTPStatus.FORBIDDEN assert resp.status == HTTPStatus.FORBIDDEN
async def test_onboarding_user(hass, hass_storage, hass_client_no_auth): async def test_onboarding_user(
hass: HomeAssistant,
hass_storage: dict[str, Any],
hass_client_no_auth: ClientSessionGenerator,
) -> None:
"""Test creating a new user.""" """Test creating a new user."""
area_registry = ar.async_get(hass) area_registry = ar.async_get(hass)
@ -221,7 +242,11 @@ async def test_onboarding_user(hass, hass_storage, hass_client_no_auth):
] ]
async def test_onboarding_user_invalid_name(hass, hass_storage, hass_client_no_auth): async def test_onboarding_user_invalid_name(
hass: HomeAssistant,
hass_storage: dict[str, Any],
hass_client_no_auth: ClientSessionGenerator,
) -> None:
"""Test not providing name.""" """Test not providing name."""
mock_storage(hass_storage, {"done": []}) mock_storage(hass_storage, {"done": []})
@ -243,7 +268,11 @@ async def test_onboarding_user_invalid_name(hass, hass_storage, hass_client_no_a
assert resp.status == 400 assert resp.status == 400
async def test_onboarding_user_race(hass, hass_storage, hass_client_no_auth): async def test_onboarding_user_race(
hass: HomeAssistant,
hass_storage: dict[str, Any],
hass_client_no_auth: ClientSessionGenerator,
) -> None:
"""Test race condition on creating new user.""" """Test race condition on creating new user."""
mock_storage(hass_storage, {"done": ["hello"]}) mock_storage(hass_storage, {"done": ["hello"]})
@ -278,7 +307,12 @@ async def test_onboarding_user_race(hass, hass_storage, hass_client_no_auth):
assert sorted([res1.status, res2.status]) == [HTTPStatus.OK, HTTPStatus.FORBIDDEN] assert sorted([res1.status, res2.status]) == [HTTPStatus.OK, HTTPStatus.FORBIDDEN]
async def test_onboarding_integration(hass, hass_storage, hass_client, hass_admin_user): async def test_onboarding_integration(
hass: HomeAssistant,
hass_storage: dict[str, Any],
hass_client: ClientSessionGenerator,
hass_admin_user: MockUser,
) -> None:
"""Test finishing integration step.""" """Test finishing integration step."""
mock_storage(hass_storage, {"done": [const.STEP_USER]}) mock_storage(hass_storage, {"done": [const.STEP_USER]})
@ -320,8 +354,11 @@ async def test_onboarding_integration(hass, hass_storage, hass_client, hass_admi
async def test_onboarding_integration_missing_credential( async def test_onboarding_integration_missing_credential(
hass, hass_storage, hass_client, hass_access_token hass: HomeAssistant,
): hass_storage: dict[str, Any],
hass_client: ClientSessionGenerator,
hass_access_token: str,
) -> None:
"""Test that we fail integration step if user is missing credentials.""" """Test that we fail integration step if user is missing credentials."""
mock_storage(hass_storage, {"done": [const.STEP_USER]}) mock_storage(hass_storage, {"done": [const.STEP_USER]})
@ -342,8 +379,10 @@ async def test_onboarding_integration_missing_credential(
async def test_onboarding_integration_invalid_redirect_uri( async def test_onboarding_integration_invalid_redirect_uri(
hass, hass_storage, hass_client hass: HomeAssistant,
): hass_storage: dict[str, Any],
hass_client: ClientSessionGenerator,
) -> None:
"""Test finishing integration step.""" """Test finishing integration step."""
mock_storage(hass_storage, {"done": [const.STEP_USER]}) mock_storage(hass_storage, {"done": [const.STEP_USER]})
@ -374,8 +413,10 @@ async def test_onboarding_integration_invalid_redirect_uri(
async def test_onboarding_integration_requires_auth( async def test_onboarding_integration_requires_auth(
hass, hass_storage, hass_client_no_auth hass: HomeAssistant,
): hass_storage: dict[str, Any],
hass_client_no_auth: ClientSessionGenerator,
) -> None:
"""Test finishing integration step.""" """Test finishing integration step."""
mock_storage(hass_storage, {"done": [const.STEP_USER]}) mock_storage(hass_storage, {"done": [const.STEP_USER]})
@ -392,8 +433,11 @@ async def test_onboarding_integration_requires_auth(
async def test_onboarding_core_sets_up_met( async def test_onboarding_core_sets_up_met(
hass, hass_storage, hass_client, mock_default_integrations hass: HomeAssistant,
): hass_storage: dict[str, Any],
hass_client: ClientSessionGenerator,
mock_default_integrations,
) -> None:
"""Test finishing the core step.""" """Test finishing the core step."""
mock_storage(hass_storage, {"done": [const.STEP_USER]}) mock_storage(hass_storage, {"done": [const.STEP_USER]})
@ -410,8 +454,11 @@ async def test_onboarding_core_sets_up_met(
async def test_onboarding_core_sets_up_radio_browser( async def test_onboarding_core_sets_up_radio_browser(
hass, hass_storage, hass_client, mock_default_integrations hass: HomeAssistant,
): hass_storage: dict[str, Any],
hass_client: ClientSessionGenerator,
mock_default_integrations,
) -> None:
"""Test finishing the core step set up the radio browser.""" """Test finishing the core step set up the radio browser."""
mock_storage(hass_storage, {"done": [const.STEP_USER]}) mock_storage(hass_storage, {"done": [const.STEP_USER]})
@ -428,8 +475,13 @@ async def test_onboarding_core_sets_up_radio_browser(
async def test_onboarding_core_sets_up_rpi_power( async def test_onboarding_core_sets_up_rpi_power(
hass, hass_storage, hass_client, aioclient_mock, rpi, mock_default_integrations hass: HomeAssistant,
): hass_storage: dict[str, Any],
hass_client: ClientSessionGenerator,
aioclient_mock: AiohttpClientMocker,
rpi,
mock_default_integrations,
) -> None:
"""Test that the core step sets up rpi_power on RPi.""" """Test that the core step sets up rpi_power on RPi."""
mock_storage(hass_storage, {"done": [const.STEP_USER]}) mock_storage(hass_storage, {"done": [const.STEP_USER]})
@ -449,8 +501,13 @@ async def test_onboarding_core_sets_up_rpi_power(
async def test_onboarding_core_no_rpi_power( async def test_onboarding_core_no_rpi_power(
hass, hass_storage, hass_client, aioclient_mock, no_rpi, mock_default_integrations hass: HomeAssistant,
): hass_storage: dict[str, Any],
hass_client: ClientSessionGenerator,
aioclient_mock: AiohttpClientMocker,
no_rpi,
mock_default_integrations,
) -> None:
"""Test that the core step do not set up rpi_power on non RPi.""" """Test that the core step do not set up rpi_power on non RPi."""
mock_storage(hass_storage, {"done": [const.STEP_USER]}) mock_storage(hass_storage, {"done": [const.STEP_USER]})
@ -469,7 +526,12 @@ async def test_onboarding_core_no_rpi_power(
assert not rpi_power_state assert not rpi_power_state
async def test_onboarding_analytics(hass, hass_storage, hass_client, hass_admin_user): async def test_onboarding_analytics(
hass: HomeAssistant,
hass_storage: dict[str, Any],
hass_client: ClientSessionGenerator,
hass_admin_user: MockUser,
) -> None:
"""Test finishing analytics step.""" """Test finishing analytics step."""
mock_storage(hass_storage, {"done": [const.STEP_USER]}) mock_storage(hass_storage, {"done": [const.STEP_USER]})
@ -488,7 +550,11 @@ async def test_onboarding_analytics(hass, hass_storage, hass_client, hass_admin_
assert resp.status == 403 assert resp.status == 403
async def test_onboarding_installation_type(hass, hass_storage, hass_client): async def test_onboarding_installation_type(
hass: HomeAssistant,
hass_storage: dict[str, Any],
hass_client: ClientSessionGenerator,
) -> None:
"""Test returning installation type during onboarding.""" """Test returning installation type during onboarding."""
mock_storage(hass_storage, {"done": []}) mock_storage(hass_storage, {"done": []})
@ -509,7 +575,11 @@ async def test_onboarding_installation_type(hass, hass_storage, hass_client):
assert resp_content["installation_type"] == "Home Assistant Core" assert resp_content["installation_type"] == "Home Assistant Core"
async def test_onboarding_installation_type_after_done(hass, hass_storage, hass_client): async def test_onboarding_installation_type_after_done(
hass: HomeAssistant,
hass_storage: dict[str, Any],
hass_client: ClientSessionGenerator,
) -> None:
"""Test raising for installation type after onboarding.""" """Test raising for installation type after onboarding."""
mock_storage(hass_storage, {"done": [const.STEP_USER]}) mock_storage(hass_storage, {"done": [const.STEP_USER]})

View file

@ -14,6 +14,8 @@ from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_entry_oauth2_flow from homeassistant.helpers import config_entry_oauth2_flow
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import ClientSessionGenerator
CLIENT_ID = OAUTH2_CLIENTID CLIENT_ID = OAUTH2_CLIENTID
CLIENT_SECRET = OAUTH2_CLIENTSECRET CLIENT_SECRET = OAUTH2_CLIENTSECRET
@ -31,8 +33,11 @@ async def test_abort_if_existing_entry(hass: HomeAssistant) -> None:
async def test_full_flow( async def test_full_flow(
hass, hass_client_no_auth, aioclient_mock, current_request_with_host hass: HomeAssistant,
): hass_client_no_auth: ClientSessionGenerator,
aioclient_mock: AiohttpClientMocker,
current_request_with_host: None,
) -> None:
"""Check full flow.""" """Check full flow."""
assert await setup.async_setup_component( assert await setup.async_setup_component(
hass, hass,

View file

@ -12,6 +12,7 @@ from homeassistant.core import HomeAssistant
from . import setup_owproxy_mock_devices from . import setup_owproxy_mock_devices
from tests.components.diagnostics import get_diagnostics_for_config_entry from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
@ -39,7 +40,7 @@ DEVICE_DETAILS = {
async def test_entry_diagnostics( async def test_entry_diagnostics(
hass: HomeAssistant, hass: HomeAssistant,
config_entry: ConfigEntry, config_entry: ConfigEntry,
hass_client, hass_client: ClientSessionGenerator,
owproxy: MagicMock, owproxy: MagicMock,
device_id: str, device_id: str,
) -> None: ) -> None:

View file

@ -33,7 +33,7 @@ async def remove_device(
@pytest.mark.usefixtures("owproxy_with_connerror") @pytest.mark.usefixtures("owproxy_with_connerror")
async def test_connect_failure(hass: HomeAssistant, config_entry: ConfigEntry): async def test_connect_failure(hass: HomeAssistant, config_entry: ConfigEntry) -> None:
"""Test connection failure raises ConfigEntryNotReady.""" """Test connection failure raises ConfigEntryNotReady."""
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -45,7 +45,7 @@ async def test_connect_failure(hass: HomeAssistant, config_entry: ConfigEntry):
async def test_listing_failure( async def test_listing_failure(
hass: HomeAssistant, config_entry: ConfigEntry, owproxy: MagicMock hass: HomeAssistant, config_entry: ConfigEntry, owproxy: MagicMock
): ) -> None:
"""Test listing failure raises ConfigEntryNotReady.""" """Test listing failure raises ConfigEntryNotReady."""
owproxy.return_value.dir.side_effect = protocol.OwnetError() owproxy.return_value.dir.side_effect = protocol.OwnetError()
@ -58,7 +58,7 @@ async def test_listing_failure(
@pytest.mark.usefixtures("owproxy") @pytest.mark.usefixtures("owproxy")
async def test_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry): async def test_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> None:
"""Test being able to unload an entry.""" """Test being able to unload an entry."""
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -10,7 +10,7 @@ from homeassistant.helpers import area_registry, device_registry, intent
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
async def test_default_prompt(hass, mock_init_component): async def test_default_prompt(hass: HomeAssistant, mock_init_component) -> None:
"""Test that the default prompt works.""" """Test that the default prompt works."""
device_reg = device_registry.async_get(hass) device_reg = device_registry.async_get(hass)
area_reg = area_registry.async_get(hass) area_reg = area_registry.async_get(hass)
@ -115,7 +115,7 @@ Smart home: """
) )
async def test_error_handling(hass, mock_init_component): async def test_error_handling(hass: HomeAssistant, mock_init_component) -> None:
"""Test that the default prompt works.""" """Test that the default prompt works."""
with patch("openai.Completion.acreate", side_effect=error.ServiceUnavailableError): with patch("openai.Completion.acreate", side_effect=error.ServiceUnavailableError):
result = await conversation.async_converse(hass, "hello", None, Context()) result = await conversation.async_converse(hass, "hello", None, Context())

View file

@ -11,6 +11,7 @@ from homeassistant.setup import async_setup_component
from tests.common import assert_setup_component, async_capture_events, load_fixture from tests.common import assert_setup_component, async_capture_events, load_fixture
from tests.components.image_processing import common from tests.components.image_processing import common
from tests.test_util.aiohttp import AiohttpClientMocker
@pytest.fixture @pytest.fixture
@ -118,8 +119,11 @@ async def test_setup_platform_without_region(hass: HomeAssistant) -> None:
async def test_openalpr_process_image( async def test_openalpr_process_image(
alpr_events, setup_openalpr_cloud, hass, aioclient_mock alpr_events,
): setup_openalpr_cloud,
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Set up and scan a picture and test plates from event.""" """Set up and scan a picture and test plates from event."""
aioclient_mock.post( aioclient_mock.post(
OPENALPR_API_URL, OPENALPR_API_URL,
@ -152,8 +156,11 @@ async def test_openalpr_process_image(
async def test_openalpr_process_image_api_error( async def test_openalpr_process_image_api_error(
alpr_events, setup_openalpr_cloud, hass, aioclient_mock alpr_events,
): setup_openalpr_cloud,
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Set up and scan a picture and test api error.""" """Set up and scan a picture and test api error."""
aioclient_mock.post( aioclient_mock.post(
OPENALPR_API_URL, OPENALPR_API_URL,
@ -174,8 +181,11 @@ async def test_openalpr_process_image_api_error(
async def test_openalpr_process_image_api_timeout( async def test_openalpr_process_image_api_timeout(
alpr_events, setup_openalpr_cloud, hass, aioclient_mock alpr_events,
): setup_openalpr_cloud,
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Set up and scan a picture and test api error.""" """Set up and scan a picture and test api error."""
aioclient_mock.post(OPENALPR_API_URL, params=PARAMS, exc=asyncio.TimeoutError()) aioclient_mock.post(OPENALPR_API_URL, params=PARAMS, exc=asyncio.TimeoutError())

View file

@ -1,10 +1,13 @@
"""The tests for the Open Hardware Monitor platform.""" """The tests for the Open Hardware Monitor platform."""
import requests_mock
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import load_fixture from tests.common import load_fixture
async def test_setup(hass, requests_mock): async def test_setup(hass: HomeAssistant, requests_mock: requests_mock.Mocker) -> None:
"""Test for successfully setting up the platform.""" """Test for successfully setting up the platform."""
config = { config = {
"sensor": { "sensor": {

View file

@ -13,11 +13,12 @@ from homeassistant.const import (
CONF_LATITUDE, CONF_LATITUDE,
CONF_LONGITUDE, CONF_LONGITUDE,
) )
from homeassistant.core import HomeAssistant
from .conftest import TEST_API_KEY, TEST_ELEVATION, TEST_LATITUDE, TEST_LONGITUDE from .conftest import TEST_API_KEY, TEST_ELEVATION, TEST_LATITUDE, TEST_LONGITUDE
async def test_create_entry(hass, client, config, mock_pyopenuv): async def test_create_entry(hass: HomeAssistant, client, config, mock_pyopenuv) -> None:
"""Test creating an entry.""" """Test creating an entry."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER} DOMAIN, context={"source": SOURCE_USER}
@ -48,7 +49,9 @@ async def test_create_entry(hass, client, config, mock_pyopenuv):
} }
async def test_duplicate_error(hass, config, config_entry, setup_config_entry): async def test_duplicate_error(
hass: HomeAssistant, config, config_entry, setup_config_entry
) -> None:
"""Test that errors are shown when duplicates are added.""" """Test that errors are shown when duplicates are added."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=config DOMAIN, context={"source": SOURCE_USER}, data=config
@ -57,7 +60,9 @@ async def test_duplicate_error(hass, config, config_entry, setup_config_entry):
assert result["reason"] == "already_configured" assert result["reason"] == "already_configured"
async def test_options_flow(hass, config_entry, setup_config_entry): async def test_options_flow(
hass: HomeAssistant, config_entry, setup_config_entry
) -> None:
"""Test config flow options.""" """Test config flow options."""
result = await hass.config_entries.options.async_init(config_entry.entry_id) result = await hass.config_entries.options.async_init(config_entry.entry_id)
assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["type"] == data_entry_flow.FlowResultType.FORM
@ -95,7 +100,9 @@ async def test_options_flow(hass, config_entry, setup_config_entry):
} }
async def test_step_reauth(hass, config, config_entry, setup_config_entry): async def test_step_reauth(
hass: HomeAssistant, config, config_entry, setup_config_entry
) -> None:
"""Test that the reauth step works.""" """Test that the reauth step works."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_REAUTH}, data=config DOMAIN, context={"source": SOURCE_REAUTH}, data=config

View file

@ -1,11 +1,18 @@
"""Test OpenUV diagnostics.""" """Test OpenUV diagnostics."""
from homeassistant.components.diagnostics import REDACTED from homeassistant.components.diagnostics import REDACTED
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.components.diagnostics import get_diagnostics_for_config_entry from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_entry_diagnostics(hass, config_entry, hass_client, setup_config_entry): async def test_entry_diagnostics(
hass: HomeAssistant,
config_entry,
hass_client: ClientSessionGenerator,
setup_config_entry,
) -> None:
"""Test config entry diagnostics.""" """Test config entry diagnostics."""
await async_setup_component(hass, "homeassistant", {}) await async_setup_component(hass, "homeassistant", {})
assert await get_diagnostics_for_config_entry(hass, hass_client, config_entry) == { assert await get_diagnostics_for_config_entry(hass, hass_client, config_entry) == {

View file

@ -1,12 +1,13 @@
"""The tests for the opnsense device tracker platform.""" """The tests for the opnsense device tracker platform."""
from unittest import mock from unittest import mock
import pytest import pytest
from homeassistant.components import opnsense from homeassistant.components import opnsense
from homeassistant.components.device_tracker import legacy
from homeassistant.components.opnsense import CONF_API_SECRET, DOMAIN from homeassistant.components.opnsense import CONF_API_SECRET, DOMAIN
from homeassistant.const import CONF_API_KEY, CONF_URL, CONF_VERIFY_SSL from homeassistant.const import CONF_API_KEY, CONF_URL, CONF_VERIFY_SSL
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -17,7 +18,9 @@ def mocked_opnsense():
yield mocked_opn yield mocked_opn
async def test_get_scanner(hass, mocked_opnsense, mock_device_tracker_conf): async def test_get_scanner(
hass: HomeAssistant, mocked_opnsense, mock_device_tracker_conf: list[legacy.Device]
) -> None:
"""Test creating an opnsense scanner.""" """Test creating an opnsense scanner."""
interface_client = mock.MagicMock() interface_client = mock.MagicMock()
mocked_opnsense.InterfaceClient.return_value = interface_client mocked_opnsense.InterfaceClient.return_value = interface_client

View file

@ -16,7 +16,7 @@ from tests.components.bluetooth import (
) )
async def test_sensors(hass, entity_registry_enabled_by_default): async def test_sensors(hass: HomeAssistant, entity_registry_enabled_by_default) -> None:
"""Test setting up creates the sensors.""" """Test setting up creates the sensors."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,
@ -46,7 +46,9 @@ async def test_sensors(hass, entity_registry_enabled_by_default):
await hass.async_block_till_done() await hass.async_block_till_done()
async def test_sensors_io_series_4(hass, entity_registry_enabled_by_default): async def test_sensors_io_series_4(
hass: HomeAssistant, entity_registry_enabled_by_default
) -> None:
"""Test setting up creates the sensors with an io series 4.""" """Test setting up creates the sensors with an io series 4."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,

View file

@ -15,7 +15,7 @@ from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker from tests.test_util.aiohttp import AiohttpClientMocker
async def test_import_dataset(hass: HomeAssistant): async def test_import_dataset(hass: HomeAssistant) -> None:
"""Test the active dataset is imported at setup.""" """Test the active dataset is imported at setup."""
config_entry = MockConfigEntry( config_entry = MockConfigEntry(
@ -37,7 +37,7 @@ async def test_import_dataset(hass: HomeAssistant):
async def test_config_entry_not_ready( async def test_config_entry_not_ready(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
): ) -> None:
"""Test raising ConfigEntryNotReady .""" """Test raising ConfigEntryNotReady ."""
config_entry = MockConfigEntry( config_entry = MockConfigEntry(
@ -53,7 +53,7 @@ async def test_config_entry_not_ready(
async def test_remove_entry( async def test_remove_entry(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, otbr_config_entry hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, otbr_config_entry
): ) -> None:
"""Test async_get_active_dataset_tlvs after removing the config entry.""" """Test async_get_active_dataset_tlvs after removing the config entry."""
aioclient_mock.get(f"{BASE_URL}/node/dataset/active", text="0E") aioclient_mock.get(f"{BASE_URL}/node/dataset/active", text="0E")
@ -69,7 +69,7 @@ async def test_remove_entry(
async def test_get_active_dataset_tlvs( async def test_get_active_dataset_tlvs(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, otbr_config_entry hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, otbr_config_entry
): ) -> None:
"""Test async_get_active_dataset_tlvs.""" """Test async_get_active_dataset_tlvs."""
mock_response = ( mock_response = (
@ -87,14 +87,14 @@ async def test_get_active_dataset_tlvs(
async def test_get_active_dataset_tlvs_empty( async def test_get_active_dataset_tlvs_empty(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, otbr_config_entry hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, otbr_config_entry
): ) -> None:
"""Test async_get_active_dataset_tlvs.""" """Test async_get_active_dataset_tlvs."""
aioclient_mock.get(f"{BASE_URL}/node/dataset/active", status=HTTPStatus.NO_CONTENT) aioclient_mock.get(f"{BASE_URL}/node/dataset/active", status=HTTPStatus.NO_CONTENT)
assert await otbr.async_get_active_dataset_tlvs(hass) is None assert await otbr.async_get_active_dataset_tlvs(hass) is None
async def test_get_active_dataset_tlvs_addon_not_installed(hass: HomeAssistant): async def test_get_active_dataset_tlvs_addon_not_installed(hass: HomeAssistant) -> None:
"""Test async_get_active_dataset_tlvs when the multi-PAN addon is not installed.""" """Test async_get_active_dataset_tlvs when the multi-PAN addon is not installed."""
with pytest.raises(HomeAssistantError): with pytest.raises(HomeAssistantError):
@ -103,7 +103,7 @@ async def test_get_active_dataset_tlvs_addon_not_installed(hass: HomeAssistant):
async def test_get_active_dataset_tlvs_404( async def test_get_active_dataset_tlvs_404(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, otbr_config_entry hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, otbr_config_entry
): ) -> None:
"""Test async_get_active_dataset_tlvs with error.""" """Test async_get_active_dataset_tlvs with error."""
aioclient_mock.get(f"{BASE_URL}/node/dataset/active", status=HTTPStatus.NOT_FOUND) aioclient_mock.get(f"{BASE_URL}/node/dataset/active", status=HTTPStatus.NOT_FOUND)
@ -113,7 +113,7 @@ async def test_get_active_dataset_tlvs_404(
async def test_get_active_dataset_tlvs_201( async def test_get_active_dataset_tlvs_201(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, otbr_config_entry hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, otbr_config_entry
): ) -> None:
"""Test async_get_active_dataset_tlvs with error.""" """Test async_get_active_dataset_tlvs with error."""
aioclient_mock.get(f"{BASE_URL}/node/dataset/active", status=HTTPStatus.CREATED) aioclient_mock.get(f"{BASE_URL}/node/dataset/active", status=HTTPStatus.CREATED)
@ -123,7 +123,7 @@ async def test_get_active_dataset_tlvs_201(
async def test_get_active_dataset_tlvs_invalid( async def test_get_active_dataset_tlvs_invalid(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, otbr_config_entry hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, otbr_config_entry
): ) -> None:
"""Test async_get_active_dataset_tlvs with error.""" """Test async_get_active_dataset_tlvs with error."""
aioclient_mock.get(f"{BASE_URL}/node/dataset/active", text="unexpected") aioclient_mock.get(f"{BASE_URL}/node/dataset/active", text="unexpected")

View file

@ -23,7 +23,7 @@ async def test_get_info(
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
otbr_config_entry, otbr_config_entry,
websocket_client, websocket_client,
): ) -> None:
"""Test async_get_info.""" """Test async_get_info."""
mock_response = ( mock_response = (
@ -54,7 +54,7 @@ async def test_get_info_no_entry(
hass: HomeAssistant, hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
websocket_client, websocket_client,
): ) -> None:
"""Test async_get_info.""" """Test async_get_info."""
await async_setup_component(hass, "otbr", {}) await async_setup_component(hass, "otbr", {})
await websocket_client.send_json( await websocket_client.send_json(
@ -75,7 +75,7 @@ async def test_get_info_fetch_fails(
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
otbr_config_entry, otbr_config_entry,
websocket_client, websocket_client,
): ) -> None:
"""Test async_get_info.""" """Test async_get_info."""
await async_setup_component(hass, "otbr", {}) await async_setup_component(hass, "otbr", {})

View file

@ -60,7 +60,7 @@ async def init_config_flow(hass):
return flow return flow
async def test_user(hass, webhook_id, secret): async def test_user(hass: HomeAssistant, webhook_id, secret) -> None:
"""Test user step.""" """Test user step."""
flow = await init_config_flow(hass) flow = await init_config_flow(hass)
@ -103,7 +103,9 @@ async def test_abort_if_already_setup(hass: HomeAssistant) -> None:
assert result["reason"] == "single_instance_allowed" assert result["reason"] == "single_instance_allowed"
async def test_user_not_supports_encryption(hass, not_supports_encryption): async def test_user_not_supports_encryption(
hass: HomeAssistant, not_supports_encryption
) -> None:
"""Test user step.""" """Test user step."""
flow = await init_config_flow(hass) flow = await init_config_flow(hass)

View file

@ -401,14 +401,14 @@ def assert_mobile_tracker_accuracy(hass, accuracy, beacon=IBEACON_DEVICE):
assert state.attributes.get("gps_accuracy") == accuracy assert state.attributes.get("gps_accuracy") == accuracy
async def test_location_invalid_devid(hass, context): async def test_location_invalid_devid(hass: HomeAssistant, context) -> None:
"""Test the update of a location.""" """Test the update of a location."""
await send_message(hass, "owntracks/paulus/nexus-5x", LOCATION_MESSAGE) await send_message(hass, "owntracks/paulus/nexus-5x", LOCATION_MESSAGE)
state = hass.states.get("device_tracker.paulus_nexus_5x") state = hass.states.get("device_tracker.paulus_nexus_5x")
assert state.state == "outer" assert state.state == "outer"
async def test_location_update(hass, context): async def test_location_update(hass: HomeAssistant, context) -> None:
"""Test the update of a location.""" """Test the update of a location."""
await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE) await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE)
@ -418,7 +418,7 @@ async def test_location_update(hass, context):
assert_location_state(hass, "outer") assert_location_state(hass, "outer")
async def test_location_update_no_t_key(hass, context): async def test_location_update_no_t_key(hass: HomeAssistant, context) -> None:
"""Test the update of a location when message does not contain 't'.""" """Test the update of a location when message does not contain 't'."""
message = LOCATION_MESSAGE.copy() message = LOCATION_MESSAGE.copy()
message.pop("t") message.pop("t")
@ -430,7 +430,7 @@ async def test_location_update_no_t_key(hass, context):
assert_location_state(hass, "outer") assert_location_state(hass, "outer")
async def test_location_inaccurate_gps(hass, context): async def test_location_inaccurate_gps(hass: HomeAssistant, context) -> None:
"""Test the location for inaccurate GPS information.""" """Test the location for inaccurate GPS information."""
await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE) await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE)
await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE_INACCURATE) await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE_INACCURATE)
@ -440,7 +440,7 @@ async def test_location_inaccurate_gps(hass, context):
assert_location_longitude(hass, LOCATION_MESSAGE["lon"]) assert_location_longitude(hass, LOCATION_MESSAGE["lon"])
async def test_location_zero_accuracy_gps(hass, context): async def test_location_zero_accuracy_gps(hass: HomeAssistant, context) -> None:
"""Ignore the location for zero accuracy GPS information.""" """Ignore the location for zero accuracy GPS information."""
await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE) await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE)
await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE_ZERO_ACCURACY) await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE_ZERO_ACCURACY)
@ -452,7 +452,7 @@ async def test_location_zero_accuracy_gps(hass, context):
# ------------------------------------------------------------------------ # ------------------------------------------------------------------------
# GPS based event entry / exit testing # GPS based event entry / exit testing
async def test_event_gps_entry_exit(hass, context): async def test_event_gps_entry_exit(hass: HomeAssistant, context) -> None:
"""Test the entry event.""" """Test the entry event."""
# Entering the owntracks circular region named "inner" # Entering the owntracks circular region named "inner"
await send_message(hass, EVENT_TOPIC, REGION_GPS_ENTER_MESSAGE) await send_message(hass, EVENT_TOPIC, REGION_GPS_ENTER_MESSAGE)
@ -490,7 +490,7 @@ async def test_event_gps_entry_exit(hass, context):
assert_location_accuracy(hass, LOCATION_MESSAGE["acc"]) assert_location_accuracy(hass, LOCATION_MESSAGE["acc"])
async def test_event_gps_with_spaces(hass, context): async def test_event_gps_with_spaces(hass: HomeAssistant, context) -> None:
"""Test the entry event.""" """Test the entry event."""
message = build_message({"desc": "inner 2"}, REGION_GPS_ENTER_MESSAGE) message = build_message({"desc": "inner 2"}, REGION_GPS_ENTER_MESSAGE)
await send_message(hass, EVENT_TOPIC, message) await send_message(hass, EVENT_TOPIC, message)
@ -503,7 +503,7 @@ async def test_event_gps_with_spaces(hass, context):
assert not context().regions_entered[USER] assert not context().regions_entered[USER]
async def test_event_gps_entry_inaccurate(hass, context): async def test_event_gps_entry_inaccurate(hass: HomeAssistant, context) -> None:
"""Test the event for inaccurate entry.""" """Test the event for inaccurate entry."""
# Set location to the outer zone. # Set location to the outer zone.
await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE) await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE)
@ -516,7 +516,7 @@ async def test_event_gps_entry_inaccurate(hass, context):
assert_location_state(hass, "inner") assert_location_state(hass, "inner")
async def test_event_gps_entry_exit_inaccurate(hass, context): async def test_event_gps_entry_exit_inaccurate(hass: HomeAssistant, context) -> None:
"""Test the event for inaccurate exit.""" """Test the event for inaccurate exit."""
await send_message(hass, EVENT_TOPIC, REGION_GPS_ENTER_MESSAGE) await send_message(hass, EVENT_TOPIC, REGION_GPS_ENTER_MESSAGE)
@ -536,7 +536,7 @@ async def test_event_gps_entry_exit_inaccurate(hass, context):
assert not context().regions_entered[USER] assert not context().regions_entered[USER]
async def test_event_gps_entry_exit_zero_accuracy(hass, context): async def test_event_gps_entry_exit_zero_accuracy(hass: HomeAssistant, context) -> None:
"""Test entry/exit events with accuracy zero.""" """Test entry/exit events with accuracy zero."""
await send_message(hass, EVENT_TOPIC, REGION_GPS_ENTER_MESSAGE_ZERO) await send_message(hass, EVENT_TOPIC, REGION_GPS_ENTER_MESSAGE_ZERO)
@ -556,7 +556,9 @@ async def test_event_gps_entry_exit_zero_accuracy(hass, context):
assert not context().regions_entered[USER] assert not context().regions_entered[USER]
async def test_event_gps_exit_outside_zone_sets_away(hass, context): async def test_event_gps_exit_outside_zone_sets_away(
hass: HomeAssistant, context
) -> None:
"""Test the event for exit zone.""" """Test the event for exit zone."""
await send_message(hass, EVENT_TOPIC, REGION_GPS_ENTER_MESSAGE) await send_message(hass, EVENT_TOPIC, REGION_GPS_ENTER_MESSAGE)
assert_location_state(hass, "inner") assert_location_state(hass, "inner")
@ -569,7 +571,7 @@ async def test_event_gps_exit_outside_zone_sets_away(hass, context):
assert_location_state(hass, STATE_NOT_HOME) assert_location_state(hass, STATE_NOT_HOME)
async def test_event_gps_entry_exit_right_order(hass, context): async def test_event_gps_entry_exit_right_order(hass: HomeAssistant, context) -> None:
"""Test the event for ordering.""" """Test the event for ordering."""
# Enter inner zone # Enter inner zone
# Set location to the outer zone. # Set location to the outer zone.
@ -594,7 +596,7 @@ async def test_event_gps_entry_exit_right_order(hass, context):
assert_location_state(hass, "outer") assert_location_state(hass, "outer")
async def test_event_gps_entry_exit_wrong_order(hass, context): async def test_event_gps_entry_exit_wrong_order(hass: HomeAssistant, context) -> None:
"""Test the event for wrong order.""" """Test the event for wrong order."""
# Enter inner zone # Enter inner zone
await send_message(hass, EVENT_TOPIC, REGION_GPS_ENTER_MESSAGE) await send_message(hass, EVENT_TOPIC, REGION_GPS_ENTER_MESSAGE)
@ -617,7 +619,7 @@ async def test_event_gps_entry_exit_wrong_order(hass, context):
assert_location_state(hass, "outer") assert_location_state(hass, "outer")
async def test_event_gps_entry_unknown_zone(hass, context): async def test_event_gps_entry_unknown_zone(hass: HomeAssistant, context) -> None:
"""Test the event for unknown zone.""" """Test the event for unknown zone."""
# Just treat as location update # Just treat as location update
message = build_message({"desc": "unknown"}, REGION_GPS_ENTER_MESSAGE) message = build_message({"desc": "unknown"}, REGION_GPS_ENTER_MESSAGE)
@ -626,7 +628,7 @@ async def test_event_gps_entry_unknown_zone(hass, context):
assert_location_state(hass, "inner") assert_location_state(hass, "inner")
async def test_event_gps_exit_unknown_zone(hass, context): async def test_event_gps_exit_unknown_zone(hass: HomeAssistant, context) -> None:
"""Test the event for unknown zone.""" """Test the event for unknown zone."""
# Just treat as location update # Just treat as location update
message = build_message({"desc": "unknown"}, REGION_GPS_LEAVE_MESSAGE) message = build_message({"desc": "unknown"}, REGION_GPS_LEAVE_MESSAGE)
@ -635,7 +637,7 @@ async def test_event_gps_exit_unknown_zone(hass, context):
assert_location_state(hass, "outer") assert_location_state(hass, "outer")
async def test_event_entry_zone_loading_dash(hass, context): async def test_event_entry_zone_loading_dash(hass: HomeAssistant, context) -> None:
"""Test the event for zone landing.""" """Test the event for zone landing."""
# Make sure the leading - is ignored # Make sure the leading - is ignored
# Owntracks uses this to switch on hold # Owntracks uses this to switch on hold
@ -644,7 +646,7 @@ async def test_event_entry_zone_loading_dash(hass, context):
assert_location_state(hass, "inner") assert_location_state(hass, "inner")
async def test_events_only_on(hass, context): async def test_events_only_on(hass: HomeAssistant, context) -> None:
"""Test events_only config suppresses location updates.""" """Test events_only config suppresses location updates."""
# Sending a location message that is not home # Sending a location message that is not home
await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE_NOT_HOME) await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE_NOT_HOME)
@ -665,7 +667,7 @@ async def test_events_only_on(hass, context):
assert_location_state(hass, STATE_NOT_HOME) assert_location_state(hass, STATE_NOT_HOME)
async def test_events_only_off(hass, context): async def test_events_only_off(hass: HomeAssistant, context) -> None:
"""Test when events_only is False.""" """Test when events_only is False."""
# Sending a location message that is not home # Sending a location message that is not home
await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE_NOT_HOME) await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE_NOT_HOME)
@ -686,7 +688,7 @@ async def test_events_only_off(hass, context):
assert_location_state(hass, "outer") assert_location_state(hass, "outer")
async def test_event_source_type_entry_exit(hass, context): async def test_event_source_type_entry_exit(hass: HomeAssistant, context) -> None:
"""Test the entry and exit events of source type.""" """Test the entry and exit events of source type."""
# Entering the owntracks circular region named "inner" # Entering the owntracks circular region named "inner"
await send_message(hass, EVENT_TOPIC, REGION_GPS_ENTER_MESSAGE) await send_message(hass, EVENT_TOPIC, REGION_GPS_ENTER_MESSAGE)
@ -716,7 +718,7 @@ async def test_event_source_type_entry_exit(hass, context):
# Region Beacon based event entry / exit testing # Region Beacon based event entry / exit testing
async def test_event_region_entry_exit(hass, context): async def test_event_region_entry_exit(hass: HomeAssistant, context) -> None:
"""Test the entry event.""" """Test the entry event."""
# Seeing a beacon named "inner" # Seeing a beacon named "inner"
await send_message(hass, EVENT_TOPIC, REGION_BEACON_ENTER_MESSAGE) await send_message(hass, EVENT_TOPIC, REGION_BEACON_ENTER_MESSAGE)
@ -755,7 +757,7 @@ async def test_event_region_entry_exit(hass, context):
assert_location_accuracy(hass, LOCATION_MESSAGE["acc"]) assert_location_accuracy(hass, LOCATION_MESSAGE["acc"])
async def test_event_region_with_spaces(hass, context): async def test_event_region_with_spaces(hass: HomeAssistant, context) -> None:
"""Test the entry event.""" """Test the entry event."""
message = build_message({"desc": "inner 2"}, REGION_BEACON_ENTER_MESSAGE) message = build_message({"desc": "inner 2"}, REGION_BEACON_ENTER_MESSAGE)
await send_message(hass, EVENT_TOPIC, message) await send_message(hass, EVENT_TOPIC, message)
@ -768,7 +770,9 @@ async def test_event_region_with_spaces(hass, context):
assert not context().regions_entered[USER] assert not context().regions_entered[USER]
async def test_event_region_entry_exit_right_order(hass, context): async def test_event_region_entry_exit_right_order(
hass: HomeAssistant, context
) -> None:
"""Test the event for ordering.""" """Test the event for ordering."""
# Enter inner zone # Enter inner zone
# Set location to the outer zone. # Set location to the outer zone.
@ -799,7 +803,9 @@ async def test_event_region_entry_exit_right_order(hass, context):
assert_location_state(hass, "inner") assert_location_state(hass, "inner")
async def test_event_region_entry_exit_wrong_order(hass, context): async def test_event_region_entry_exit_wrong_order(
hass: HomeAssistant, context
) -> None:
"""Test the event for wrong order.""" """Test the event for wrong order."""
# Enter inner zone # Enter inner zone
await send_message(hass, EVENT_TOPIC, REGION_BEACON_ENTER_MESSAGE) await send_message(hass, EVENT_TOPIC, REGION_BEACON_ENTER_MESSAGE)
@ -826,7 +832,9 @@ async def test_event_region_entry_exit_wrong_order(hass, context):
assert_location_state(hass, "inner_2") assert_location_state(hass, "inner_2")
async def test_event_beacon_unknown_zone_no_location(hass, context): async def test_event_beacon_unknown_zone_no_location(
hass: HomeAssistant, context
) -> None:
"""Test the event for unknown zone.""" """Test the event for unknown zone."""
# A beacon which does not match a HA zone is the # A beacon which does not match a HA zone is the
# definition of a mobile beacon. In this case, "unknown" # definition of a mobile beacon. In this case, "unknown"
@ -851,7 +859,7 @@ async def test_event_beacon_unknown_zone_no_location(hass, context):
assert_mobile_tracker_state(hass, "unknown", "unknown") assert_mobile_tracker_state(hass, "unknown", "unknown")
async def test_event_beacon_unknown_zone(hass, context): async def test_event_beacon_unknown_zone(hass: HomeAssistant, context) -> None:
"""Test the event for unknown zone.""" """Test the event for unknown zone."""
# A beacon which does not match a HA zone is the # A beacon which does not match a HA zone is the
# definition of a mobile beacon. In this case, "unknown" # definition of a mobile beacon. In this case, "unknown"
@ -871,7 +879,9 @@ async def test_event_beacon_unknown_zone(hass, context):
assert_mobile_tracker_state(hass, "outer", "unknown") assert_mobile_tracker_state(hass, "outer", "unknown")
async def test_event_beacon_entry_zone_loading_dash(hass, context): async def test_event_beacon_entry_zone_loading_dash(
hass: HomeAssistant, context
) -> None:
"""Test the event for beacon zone landing.""" """Test the event for beacon zone landing."""
# Make sure the leading - is ignored # Make sure the leading - is ignored
# Owntracks uses this to switch on hold # Owntracks uses this to switch on hold
@ -883,7 +893,7 @@ async def test_event_beacon_entry_zone_loading_dash(hass, context):
# ------------------------------------------------------------------------ # ------------------------------------------------------------------------
# Mobile Beacon based event entry / exit testing # Mobile Beacon based event entry / exit testing
async def test_mobile_enter_move_beacon(hass, context): async def test_mobile_enter_move_beacon(hass: HomeAssistant, context) -> None:
"""Test the movement of a beacon.""" """Test the movement of a beacon."""
# I am in the outer zone. # I am in the outer zone.
await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE) await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE)
@ -907,7 +917,7 @@ async def test_mobile_enter_move_beacon(hass, context):
assert_mobile_tracker_latitude(hass, not_home_lat) assert_mobile_tracker_latitude(hass, not_home_lat)
async def test_mobile_enter_exit_region_beacon(hass, context): async def test_mobile_enter_exit_region_beacon(hass: HomeAssistant, context) -> None:
"""Test the enter and the exit of a mobile beacon.""" """Test the enter and the exit of a mobile beacon."""
# I am in the outer zone. # I am in the outer zone.
await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE) await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE)
@ -930,7 +940,7 @@ async def test_mobile_enter_exit_region_beacon(hass, context):
assert_mobile_tracker_state(hass, "outer") assert_mobile_tracker_state(hass, "outer")
async def test_mobile_exit_move_beacon(hass, context): async def test_mobile_exit_move_beacon(hass: HomeAssistant, context) -> None:
"""Test the exit move of a beacon.""" """Test the exit move of a beacon."""
# I am in the outer zone. # I am in the outer zone.
await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE) await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE)
@ -952,7 +962,7 @@ async def test_mobile_exit_move_beacon(hass, context):
assert_mobile_tracker_state(hass, "outer") assert_mobile_tracker_state(hass, "outer")
async def test_mobile_multiple_async_enter_exit(hass, context): async def test_mobile_multiple_async_enter_exit(hass: HomeAssistant, context) -> None:
"""Test the multiple entering.""" """Test the multiple entering."""
# Test race condition # Test race condition
for _ in range(0, 20): for _ in range(0, 20):
@ -972,7 +982,7 @@ async def test_mobile_multiple_async_enter_exit(hass, context):
assert len(context().mobile_beacons_active["greg_phone"]) == 0 assert len(context().mobile_beacons_active["greg_phone"]) == 0
async def test_mobile_multiple_enter_exit(hass, context): async def test_mobile_multiple_enter_exit(hass: HomeAssistant, context) -> None:
"""Test the multiple entering.""" """Test the multiple entering."""
await send_message(hass, EVENT_TOPIC, MOBILE_BEACON_ENTER_EVENT_MESSAGE) await send_message(hass, EVENT_TOPIC, MOBILE_BEACON_ENTER_EVENT_MESSAGE)
await send_message(hass, EVENT_TOPIC, MOBILE_BEACON_ENTER_EVENT_MESSAGE) await send_message(hass, EVENT_TOPIC, MOBILE_BEACON_ENTER_EVENT_MESSAGE)
@ -981,7 +991,7 @@ async def test_mobile_multiple_enter_exit(hass, context):
assert len(context().mobile_beacons_active["greg_phone"]) == 0 assert len(context().mobile_beacons_active["greg_phone"]) == 0
async def test_complex_movement(hass, context): async def test_complex_movement(hass: HomeAssistant, context) -> None:
"""Test a complex sequence representative of real-world use.""" """Test a complex sequence representative of real-world use."""
# I am in the outer zone. # I am in the outer zone.
await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE) await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE)
@ -1103,7 +1113,9 @@ async def test_complex_movement(hass, context):
assert_mobile_tracker_state(hass, "outer") assert_mobile_tracker_state(hass, "outer")
async def test_complex_movement_sticky_keys_beacon(hass, context): async def test_complex_movement_sticky_keys_beacon(
hass: HomeAssistant, context
) -> None:
"""Test a complex sequence which was previously broken.""" """Test a complex sequence which was previously broken."""
# I am not_home # I am not_home
await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE) await send_message(hass, LOCATION_TOPIC, LOCATION_MESSAGE)
@ -1215,7 +1227,7 @@ async def test_complex_movement_sticky_keys_beacon(hass, context):
assert_mobile_tracker_latitude(hass, INNER_ZONE["latitude"]) assert_mobile_tracker_latitude(hass, INNER_ZONE["latitude"])
async def test_waypoint_import_simple(hass, context): async def test_waypoint_import_simple(hass: HomeAssistant, context) -> None:
"""Test a simple import of list of waypoints.""" """Test a simple import of list of waypoints."""
waypoints_message = WAYPOINTS_EXPORTED_MESSAGE.copy() waypoints_message = WAYPOINTS_EXPORTED_MESSAGE.copy()
await send_message(hass, WAYPOINTS_TOPIC, waypoints_message) await send_message(hass, WAYPOINTS_TOPIC, waypoints_message)
@ -1226,7 +1238,7 @@ async def test_waypoint_import_simple(hass, context):
assert wayp is not None assert wayp is not None
async def test_waypoint_import_block(hass, context): async def test_waypoint_import_block(hass: HomeAssistant, context) -> None:
"""Test import of list of waypoints for blocked user.""" """Test import of list of waypoints for blocked user."""
waypoints_message = WAYPOINTS_EXPORTED_MESSAGE.copy() waypoints_message = WAYPOINTS_EXPORTED_MESSAGE.copy()
await send_message(hass, WAYPOINTS_TOPIC_BLOCKED, waypoints_message) await send_message(hass, WAYPOINTS_TOPIC_BLOCKED, waypoints_message)
@ -1237,7 +1249,7 @@ async def test_waypoint_import_block(hass, context):
assert wayp is None assert wayp is None
async def test_waypoint_import_no_whitelist(hass, setup_comp): async def test_waypoint_import_no_whitelist(hass: HomeAssistant, setup_comp) -> None:
"""Test import of list of waypoints with no whitelist set.""" """Test import of list of waypoints with no whitelist set."""
await setup_owntracks( await setup_owntracks(
hass, hass,
@ -1257,7 +1269,7 @@ async def test_waypoint_import_no_whitelist(hass, setup_comp):
assert wayp is not None assert wayp is not None
async def test_waypoint_import_bad_json(hass, context): async def test_waypoint_import_bad_json(hass: HomeAssistant, context) -> None:
"""Test importing a bad JSON payload.""" """Test importing a bad JSON payload."""
waypoints_message = WAYPOINTS_EXPORTED_MESSAGE.copy() waypoints_message = WAYPOINTS_EXPORTED_MESSAGE.copy()
await send_message(hass, WAYPOINTS_TOPIC, waypoints_message, True) await send_message(hass, WAYPOINTS_TOPIC, waypoints_message, True)
@ -1268,7 +1280,7 @@ async def test_waypoint_import_bad_json(hass, context):
assert wayp is None assert wayp is None
async def test_waypoint_import_existing(hass, context): async def test_waypoint_import_existing(hass: HomeAssistant, context) -> None:
"""Test importing a zone that exists.""" """Test importing a zone that exists."""
waypoints_message = WAYPOINTS_EXPORTED_MESSAGE.copy() waypoints_message = WAYPOINTS_EXPORTED_MESSAGE.copy()
await send_message(hass, WAYPOINTS_TOPIC, waypoints_message) await send_message(hass, WAYPOINTS_TOPIC, waypoints_message)
@ -1281,7 +1293,7 @@ async def test_waypoint_import_existing(hass, context):
assert wayp == new_wayp assert wayp == new_wayp
async def test_single_waypoint_import(hass, context): async def test_single_waypoint_import(hass: HomeAssistant, context) -> None:
"""Test single waypoint message.""" """Test single waypoint message."""
waypoint_message = WAYPOINT_MESSAGE.copy() waypoint_message = WAYPOINT_MESSAGE.copy()
await send_message(hass, WAYPOINT_TOPIC, waypoint_message) await send_message(hass, WAYPOINT_TOPIC, waypoint_message)
@ -1289,7 +1301,7 @@ async def test_single_waypoint_import(hass, context):
assert wayp is not None assert wayp is not None
async def test_not_implemented_message(hass, context): async def test_not_implemented_message(hass: HomeAssistant, context) -> None:
"""Handle not implemented message type.""" """Handle not implemented message type."""
patch_handler = patch( patch_handler = patch(
"homeassistant.components.owntracks.messages.async_handle_not_impl_msg", "homeassistant.components.owntracks.messages.async_handle_not_impl_msg",
@ -1300,7 +1312,7 @@ async def test_not_implemented_message(hass, context):
patch_handler.stop() patch_handler.stop()
async def test_unsupported_message(hass, context): async def test_unsupported_message(hass: HomeAssistant, context) -> None:
"""Handle not implemented message type.""" """Handle not implemented message type."""
patch_handler = patch( patch_handler = patch(
"homeassistant.components.owntracks.messages.async_handle_unsupported_msg", "homeassistant.components.owntracks.messages.async_handle_unsupported_msg",
@ -1418,7 +1430,7 @@ def mock_get_cipher_error():
@patch("homeassistant.components.owntracks.messages.get_cipher", mock_cipher) @patch("homeassistant.components.owntracks.messages.get_cipher", mock_cipher)
async def test_encrypted_payload(hass, setup_comp): async def test_encrypted_payload(hass: HomeAssistant, setup_comp) -> None:
"""Test encrypted payload.""" """Test encrypted payload."""
await setup_owntracks(hass, {CONF_SECRET: TEST_SECRET_KEY}) await setup_owntracks(hass, {CONF_SECRET: TEST_SECRET_KEY})
await send_message(hass, LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE) await send_message(hass, LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE)
@ -1426,7 +1438,7 @@ async def test_encrypted_payload(hass, setup_comp):
@patch("homeassistant.components.owntracks.messages.get_cipher", mock_cipher) @patch("homeassistant.components.owntracks.messages.get_cipher", mock_cipher)
async def test_encrypted_payload_topic_key(hass, setup_comp): async def test_encrypted_payload_topic_key(hass: HomeAssistant, setup_comp) -> None:
"""Test encrypted payload with a topic key.""" """Test encrypted payload with a topic key."""
await setup_owntracks(hass, {CONF_SECRET: {LOCATION_TOPIC: TEST_SECRET_KEY}}) await setup_owntracks(hass, {CONF_SECRET: {LOCATION_TOPIC: TEST_SECRET_KEY}})
await send_message(hass, LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE) await send_message(hass, LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE)
@ -1434,15 +1446,17 @@ async def test_encrypted_payload_topic_key(hass, setup_comp):
async def test_encrypted_payload_not_supports_encryption( async def test_encrypted_payload_not_supports_encryption(
hass, setup_comp, not_supports_encryption hass: HomeAssistant, setup_comp, not_supports_encryption
): ) -> None:
"""Test encrypted payload with no supported encryption.""" """Test encrypted payload with no supported encryption."""
await setup_owntracks(hass, {CONF_SECRET: TEST_SECRET_KEY}) await setup_owntracks(hass, {CONF_SECRET: TEST_SECRET_KEY})
await send_message(hass, LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE) await send_message(hass, LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE)
assert hass.states.get(DEVICE_TRACKER_STATE) is None assert hass.states.get(DEVICE_TRACKER_STATE) is None
async def test_encrypted_payload_get_cipher_error(hass, setup_comp, get_cipher_error): async def test_encrypted_payload_get_cipher_error(
hass: HomeAssistant, setup_comp, get_cipher_error
) -> None:
"""Test encrypted payload with no supported encryption.""" """Test encrypted payload with no supported encryption."""
await setup_owntracks(hass, {CONF_SECRET: TEST_SECRET_KEY}) await setup_owntracks(hass, {CONF_SECRET: TEST_SECRET_KEY})
await send_message(hass, LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE) await send_message(hass, LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE)
@ -1450,7 +1464,7 @@ async def test_encrypted_payload_get_cipher_error(hass, setup_comp, get_cipher_e
@patch("homeassistant.components.owntracks.messages.get_cipher", mock_cipher) @patch("homeassistant.components.owntracks.messages.get_cipher", mock_cipher)
async def test_encrypted_payload_no_key(hass, setup_comp): async def test_encrypted_payload_no_key(hass: HomeAssistant, setup_comp) -> None:
"""Test encrypted payload with no key, .""" """Test encrypted payload with no key, ."""
assert hass.states.get(DEVICE_TRACKER_STATE) is None assert hass.states.get(DEVICE_TRACKER_STATE) is None
await setup_owntracks(hass, {CONF_SECRET: {}}) await setup_owntracks(hass, {CONF_SECRET: {}})
@ -1459,7 +1473,7 @@ async def test_encrypted_payload_no_key(hass, setup_comp):
@patch("homeassistant.components.owntracks.messages.get_cipher", mock_cipher) @patch("homeassistant.components.owntracks.messages.get_cipher", mock_cipher)
async def test_encrypted_payload_wrong_key(hass, setup_comp): async def test_encrypted_payload_wrong_key(hass: HomeAssistant, setup_comp) -> None:
"""Test encrypted payload with wrong key.""" """Test encrypted payload with wrong key."""
await setup_owntracks(hass, {CONF_SECRET: "wrong key"}) await setup_owntracks(hass, {CONF_SECRET: "wrong key"})
await send_message(hass, LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE) await send_message(hass, LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE)
@ -1467,7 +1481,9 @@ async def test_encrypted_payload_wrong_key(hass, setup_comp):
@patch("homeassistant.components.owntracks.messages.get_cipher", mock_cipher) @patch("homeassistant.components.owntracks.messages.get_cipher", mock_cipher)
async def test_encrypted_payload_wrong_topic_key(hass, setup_comp): async def test_encrypted_payload_wrong_topic_key(
hass: HomeAssistant, setup_comp
) -> None:
"""Test encrypted payload with wrong topic key.""" """Test encrypted payload with wrong topic key."""
await setup_owntracks(hass, {CONF_SECRET: {LOCATION_TOPIC: "wrong key"}}) await setup_owntracks(hass, {CONF_SECRET: {LOCATION_TOPIC: "wrong key"}})
await send_message(hass, LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE) await send_message(hass, LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE)
@ -1475,7 +1491,7 @@ async def test_encrypted_payload_wrong_topic_key(hass, setup_comp):
@patch("homeassistant.components.owntracks.messages.get_cipher", mock_cipher) @patch("homeassistant.components.owntracks.messages.get_cipher", mock_cipher)
async def test_encrypted_payload_no_topic_key(hass, setup_comp): async def test_encrypted_payload_no_topic_key(hass: HomeAssistant, setup_comp) -> None:
"""Test encrypted payload with no topic key.""" """Test encrypted payload with no topic key."""
await setup_owntracks( await setup_owntracks(
hass, {CONF_SECRET: {"owntracks/{}/{}".format(USER, "otherdevice"): "foobar"}} hass, {CONF_SECRET: {"owntracks/{}/{}".format(USER, "otherdevice"): "foobar"}}
@ -1484,7 +1500,7 @@ async def test_encrypted_payload_no_topic_key(hass, setup_comp):
assert hass.states.get(DEVICE_TRACKER_STATE) is None assert hass.states.get(DEVICE_TRACKER_STATE) is None
async def test_encrypted_payload_libsodium(hass, setup_comp): async def test_encrypted_payload_libsodium(hass: HomeAssistant, setup_comp) -> None:
"""Test sending encrypted message payload.""" """Test sending encrypted message payload."""
try: try:
import nacl # noqa: F401 pylint: disable=unused-import import nacl # noqa: F401 pylint: disable=unused-import
@ -1498,7 +1514,7 @@ async def test_encrypted_payload_libsodium(hass, setup_comp):
assert_location_latitude(hass, LOCATION_MESSAGE["lat"]) assert_location_latitude(hass, LOCATION_MESSAGE["lat"])
async def test_customized_mqtt_topic(hass, setup_comp): async def test_customized_mqtt_topic(hass: HomeAssistant, setup_comp) -> None:
"""Test subscribing to a custom mqtt topic.""" """Test subscribing to a custom mqtt topic."""
await setup_owntracks(hass, {CONF_MQTT_TOPIC: "mytracks/#"}) await setup_owntracks(hass, {CONF_MQTT_TOPIC: "mytracks/#"})
@ -1508,7 +1524,7 @@ async def test_customized_mqtt_topic(hass, setup_comp):
assert_location_latitude(hass, LOCATION_MESSAGE["lat"]) assert_location_latitude(hass, LOCATION_MESSAGE["lat"])
async def test_region_mapping(hass, setup_comp): async def test_region_mapping(hass: HomeAssistant, setup_comp) -> None:
"""Test region to zone mapping.""" """Test region to zone mapping."""
await setup_owntracks(hass, {CONF_REGION_MAPPING: {"foo": "inner"}}) await setup_owntracks(hass, {CONF_REGION_MAPPING: {"foo": "inner"}})

View file

@ -20,11 +20,11 @@ def mock_nacl_not_imported():
yield yield
def test_supports_encryption(nacl_imported): def test_supports_encryption(nacl_imported) -> None:
"""Test if env supports encryption.""" """Test if env supports encryption."""
assert helper.supports_encryption() assert helper.supports_encryption()
def test_supports_encryption_failed(nacl_not_imported): def test_supports_encryption_failed(nacl_not_imported) -> None:
"""Test if env does not support encryption.""" """Test if env does not support encryption."""
assert not helper.supports_encryption() assert not helper.supports_encryption()

View file

@ -52,7 +52,7 @@ def mock_client(hass, hass_client_no_auth):
return hass.loop.run_until_complete(hass_client_no_auth()) return hass.loop.run_until_complete(hass_client_no_auth())
async def test_handle_valid_message(mock_client): async def test_handle_valid_message(mock_client) -> None:
"""Test that we forward messages correctly to OwnTracks.""" """Test that we forward messages correctly to OwnTracks."""
resp = await mock_client.post( resp = await mock_client.post(
"/api/webhook/owntracks_test", "/api/webhook/owntracks_test",
@ -66,7 +66,7 @@ async def test_handle_valid_message(mock_client):
assert json == [] assert json == []
async def test_handle_valid_minimal_message(mock_client): async def test_handle_valid_minimal_message(mock_client) -> None:
"""Test that we forward messages correctly to OwnTracks.""" """Test that we forward messages correctly to OwnTracks."""
resp = await mock_client.post( resp = await mock_client.post(
"/api/webhook/owntracks_test", "/api/webhook/owntracks_test",
@ -80,7 +80,7 @@ async def test_handle_valid_minimal_message(mock_client):
assert json == [] assert json == []
async def test_handle_value_error(mock_client): async def test_handle_value_error(mock_client) -> None:
"""Test we don't disclose that this is a valid webhook.""" """Test we don't disclose that this is a valid webhook."""
resp = await mock_client.post( resp = await mock_client.post(
"/api/webhook/owntracks_test", "/api/webhook/owntracks_test",
@ -94,7 +94,9 @@ async def test_handle_value_error(mock_client):
assert json == "" assert json == ""
async def test_returns_error_missing_username(mock_client, caplog): async def test_returns_error_missing_username(
mock_client, caplog: pytest.LogCaptureFixture
) -> None:
"""Test that an error is returned when username is missing.""" """Test that an error is returned when username is missing."""
resp = await mock_client.post( resp = await mock_client.post(
"/api/webhook/owntracks_test", "/api/webhook/owntracks_test",
@ -109,7 +111,9 @@ async def test_returns_error_missing_username(mock_client, caplog):
assert "No topic or user found" in caplog.text assert "No topic or user found" in caplog.text
async def test_returns_error_incorrect_json(mock_client, caplog): async def test_returns_error_incorrect_json(
mock_client, caplog: pytest.LogCaptureFixture
) -> None:
"""Test that an error is returned when username is missing.""" """Test that an error is returned when username is missing."""
resp = await mock_client.post( resp = await mock_client.post(
"/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"}
@ -122,7 +126,7 @@ async def test_returns_error_incorrect_json(mock_client, caplog):
assert "invalid JSON" in caplog.text assert "invalid JSON" in caplog.text
async def test_returns_error_missing_device(mock_client): async def test_returns_error_missing_device(mock_client) -> None:
"""Test that an error is returned when device name is missing.""" """Test that an error is returned when device name is missing."""
resp = await mock_client.post( resp = await mock_client.post(
"/api/webhook/owntracks_test", "/api/webhook/owntracks_test",

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."""
assert await get_diagnostics_for_config_entry( assert await get_diagnostics_for_config_entry(
hass, hass_client, init_integration hass, hass_client, init_integration

View file

@ -22,7 +22,7 @@ from .conftest import (
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
async def test_setup_entry_encrypted(hass, mock_remote): async def test_setup_entry_encrypted(hass: HomeAssistant, mock_remote) -> None:
"""Test setup with encrypted config entry.""" """Test setup with encrypted config entry."""
mock_entry = MockConfigEntry( mock_entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,
@ -45,7 +45,9 @@ async def test_setup_entry_encrypted(hass, mock_remote):
assert state_remote.name == DEFAULT_NAME assert state_remote.name == DEFAULT_NAME
async def test_setup_entry_encrypted_missing_device_info(hass, mock_remote): async def test_setup_entry_encrypted_missing_device_info(
hass: HomeAssistant, mock_remote
) -> None:
"""Test setup with encrypted config entry and missing device info.""" """Test setup with encrypted config entry and missing device info."""
mock_entry = MockConfigEntry( mock_entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,
@ -105,7 +107,7 @@ async def test_setup_entry_encrypted_missing_device_info_none(
assert state_remote.name == DEFAULT_NAME assert state_remote.name == DEFAULT_NAME
async def test_setup_entry_unencrypted(hass, mock_remote): async def test_setup_entry_unencrypted(hass: HomeAssistant, mock_remote) -> None:
"""Test setup with unencrypted config entry.""" """Test setup with unencrypted config entry."""
mock_entry = MockConfigEntry( mock_entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,
@ -128,7 +130,9 @@ async def test_setup_entry_unencrypted(hass, mock_remote):
assert state_remote.name == DEFAULT_NAME assert state_remote.name == DEFAULT_NAME
async def test_setup_entry_unencrypted_missing_device_info(hass, mock_remote): async def test_setup_entry_unencrypted_missing_device_info(
hass: HomeAssistant, mock_remote
) -> None:
"""Test setup with unencrypted config entry and missing device info.""" """Test setup with unencrypted config entry and missing device info."""
mock_entry = MockConfigEntry( mock_entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,
@ -209,7 +213,7 @@ async def test_setup_config_flow_initiated(hass: HomeAssistant) -> None:
assert len(hass.config_entries.flow.async_progress()) == 1 assert len(hass.config_entries.flow.async_progress()) == 1
async def test_setup_unload_entry(hass, mock_remote): async def test_setup_unload_entry(hass: HomeAssistant, mock_remote) -> None:
"""Test if config entry is unloaded.""" """Test if config entry is unloaded."""
mock_entry = MockConfigEntry( mock_entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,

View file

@ -1,5 +1,4 @@
"""Test the Panasonic Viera remote entity.""" """Test the Panasonic Viera remote entity."""
from unittest.mock import Mock, call from unittest.mock import Mock, call
from panasonic_viera import Keys, SOAPError from panasonic_viera import Keys, SOAPError
@ -11,6 +10,7 @@ from homeassistant.components.remote import (
SERVICE_SEND_COMMAND, SERVICE_SEND_COMMAND,
) )
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON
from homeassistant.core import HomeAssistant
from .conftest import MOCK_CONFIG_DATA, MOCK_DEVICE_INFO, MOCK_ENCRYPTION_DATA from .conftest import MOCK_CONFIG_DATA, MOCK_DEVICE_INFO, MOCK_ENCRYPTION_DATA
@ -31,7 +31,7 @@ async def setup_panasonic_viera(hass):
await hass.async_block_till_done() await hass.async_block_till_done()
async def test_onoff(hass, mock_remote): async def test_onoff(hass: HomeAssistant, mock_remote) -> None:
"""Test the on/off service calls.""" """Test the on/off service calls."""
await setup_panasonic_viera(hass) await setup_panasonic_viera(hass)
@ -49,7 +49,7 @@ async def test_onoff(hass, mock_remote):
assert mock_remote.send_key.call_args_list == [call(power), call(power)] assert mock_remote.send_key.call_args_list == [call(power), call(power)]
async def test_send_command(hass, mock_remote): async def test_send_command(hass: HomeAssistant, mock_remote) -> None:
"""Test the send_command service call.""" """Test the send_command service call."""
await setup_panasonic_viera(hass) await setup_panasonic_viera(hass)

View file

@ -13,7 +13,7 @@ from homeassistant.setup import async_setup_component
{"router": {"url": "not-a-url"}}, {"router": {"url": "not-a-url"}},
), ),
) )
async def test_wrong_config(hass, config_to_try): async def test_wrong_config(hass: HomeAssistant, config_to_try) -> None:
"""Test setup with wrong configuration.""" """Test setup with wrong configuration."""
assert not await async_setup_component( assert not await async_setup_component(
hass, "panel_iframe", {"panel_iframe": config_to_try} hass, "panel_iframe", {"panel_iframe": config_to_try}

View file

@ -57,7 +57,7 @@ async def test_unload_entry(hass: HomeAssistant) -> None:
"bucks_customers_served", "bucks_customers_served",
], ],
) )
async def test_update_timeout(hass: HomeAssistant, sensor): async def test_update_timeout(hass: HomeAssistant, sensor) -> None:
"""Test if it raises an error when there is a timeout.""" """Test if it raises an error when there is a timeout."""
config_entry = MockConfigEntry(domain=DOMAIN, data=COUNTY_ENTRY_DATA) config_entry = MockConfigEntry(domain=DOMAIN, data=COUNTY_ENTRY_DATA)
@ -83,7 +83,7 @@ async def test_update_timeout(hass: HomeAssistant, sensor):
"total_customers_served", "total_customers_served",
], ],
) )
async def test_total_update_timeout(hass: HomeAssistant, sensor): async def test_total_update_timeout(hass: HomeAssistant, sensor) -> None:
"""Test if it raises an error when there is a timeout.""" """Test if it raises an error when there is a timeout."""
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_ENTRY_DATA) config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_ENTRY_DATA)
@ -108,7 +108,7 @@ async def test_total_update_timeout(hass: HomeAssistant, sensor):
"bucks_customers_served", "bucks_customers_served",
], ],
) )
async def test_http_error(hass: HomeAssistant, sensor: str): async def test_http_error(hass: HomeAssistant, sensor: str) -> None:
"""Test if it raises an error when an abnormal status code is returned.""" """Test if it raises an error when an abnormal status code is returned."""
config_entry = MockConfigEntry(domain=DOMAIN, data=COUNTY_ENTRY_DATA) config_entry = MockConfigEntry(domain=DOMAIN, data=COUNTY_ENTRY_DATA)
@ -134,7 +134,7 @@ async def test_http_error(hass: HomeAssistant, sensor: str):
"bucks_customers_served", "bucks_customers_served",
], ],
) )
async def test_bad_json(hass: HomeAssistant, sensor: str): async def test_bad_json(hass: HomeAssistant, sensor: str) -> None:
"""Test if it raises an error when abnormal JSON is returned.""" """Test if it raises an error when abnormal JSON is returned."""
config_entry = MockConfigEntry(domain=DOMAIN, data=COUNTY_ENTRY_DATA) config_entry = MockConfigEntry(domain=DOMAIN, data=COUNTY_ENTRY_DATA)

View file

@ -1,5 +1,6 @@
"""The tests for the person component.""" """The tests for the person component."""
import logging import logging
from typing import Any
from unittest.mock import patch from unittest.mock import patch
import pytest import pytest
@ -21,7 +22,8 @@ from homeassistant.core import Context, CoreState, HomeAssistant, State
from homeassistant.helpers import collection, entity_registry as er from homeassistant.helpers import collection, entity_registry as er
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import mock_component, mock_restore_cache from tests.common import MockUser, mock_component, mock_restore_cache
from tests.typing import WebSocketGenerator
DEVICE_TRACKER = "device_tracker.test_tracker" DEVICE_TRACKER = "device_tracker.test_tracker"
DEVICE_TRACKER_2 = "device_tracker.test_tracker_2" DEVICE_TRACKER_2 = "device_tracker.test_tracker_2"
@ -87,7 +89,7 @@ async def test_setup_no_name(hass: HomeAssistant) -> None:
assert not await async_setup_component(hass, DOMAIN, config) assert not await async_setup_component(hass, DOMAIN, config)
async def test_setup_user_id(hass, hass_admin_user): async def test_setup_user_id(hass: HomeAssistant, hass_admin_user: MockUser) -> None:
"""Test config with user id.""" """Test config with user id."""
user_id = hass_admin_user.id user_id = hass_admin_user.id
config = {DOMAIN: {"id": "1234", "name": "test person", "user_id": user_id}} config = {DOMAIN: {"id": "1234", "name": "test person", "user_id": user_id}}
@ -102,7 +104,9 @@ async def test_setup_user_id(hass, hass_admin_user):
assert state.attributes.get(ATTR_USER_ID) == user_id assert state.attributes.get(ATTR_USER_ID) == user_id
async def test_valid_invalid_user_ids(hass, hass_admin_user): async def test_valid_invalid_user_ids(
hass: HomeAssistant, hass_admin_user: MockUser
) -> None:
"""Test a person with valid user id and a person with invalid user id .""" """Test a person with valid user id and a person with invalid user id ."""
user_id = hass_admin_user.id user_id = hass_admin_user.id
config = { config = {
@ -124,7 +128,7 @@ async def test_valid_invalid_user_ids(hass, hass_admin_user):
assert state is None assert state is None
async def test_setup_tracker(hass, hass_admin_user): async def test_setup_tracker(hass: HomeAssistant, hass_admin_user: MockUser) -> None:
"""Test set up person with one device tracker.""" """Test set up person with one device tracker."""
hass.state = CoreState.not_running hass.state = CoreState.not_running
user_id = hass_admin_user.id user_id = hass_admin_user.id
@ -180,7 +184,9 @@ async def test_setup_tracker(hass, hass_admin_user):
assert state.attributes.get(ATTR_USER_ID) == user_id assert state.attributes.get(ATTR_USER_ID) == user_id
async def test_setup_two_trackers(hass, hass_admin_user): async def test_setup_two_trackers(
hass: HomeAssistant, hass_admin_user: MockUser
) -> None:
"""Test set up person with two device trackers.""" """Test set up person with two device trackers."""
hass.state = CoreState.not_running hass.state = CoreState.not_running
user_id = hass_admin_user.id user_id = hass_admin_user.id
@ -258,7 +264,9 @@ async def test_setup_two_trackers(hass, hass_admin_user):
assert state.attributes.get(ATTR_SOURCE) == DEVICE_TRACKER assert state.attributes.get(ATTR_SOURCE) == DEVICE_TRACKER
async def test_ignore_unavailable_states(hass, hass_admin_user): async def test_ignore_unavailable_states(
hass: HomeAssistant, hass_admin_user: MockUser
) -> None:
"""Test set up person with two device trackers, one unavailable.""" """Test set up person with two device trackers, one unavailable."""
hass.state = CoreState.not_running hass.state = CoreState.not_running
user_id = hass_admin_user.id user_id = hass_admin_user.id
@ -301,7 +309,9 @@ async def test_ignore_unavailable_states(hass, hass_admin_user):
assert state.state == "not_home" assert state.state == "not_home"
async def test_restore_home_state(hass, hass_admin_user): async def test_restore_home_state(
hass: HomeAssistant, hass_admin_user: MockUser
) -> None:
"""Test that the state is restored for a person on startup.""" """Test that the state is restored for a person on startup."""
user_id = hass_admin_user.id user_id = hass_admin_user.id
attrs = { attrs = {
@ -337,7 +347,7 @@ async def test_restore_home_state(hass, hass_admin_user):
assert state.attributes.get(ATTR_ENTITY_PICTURE) == "/bla" assert state.attributes.get(ATTR_ENTITY_PICTURE) == "/bla"
async def test_duplicate_ids(hass, hass_admin_user): async def test_duplicate_ids(hass: HomeAssistant, hass_admin_user: MockUser) -> None:
"""Test we don't allow duplicate IDs.""" """Test we don't allow duplicate IDs."""
config = { config = {
DOMAIN: [ DOMAIN: [
@ -368,7 +378,9 @@ async def test_create_person_during_run(hass: HomeAssistant) -> None:
assert state.state == "home" assert state.state == "home"
async def test_load_person_storage(hass, hass_admin_user, storage_setup): async def test_load_person_storage(
hass: HomeAssistant, hass_admin_user: MockUser, storage_setup
) -> None:
"""Test set up person from storage.""" """Test set up person from storage."""
state = hass.states.get("person.tracked_person") state = hass.states.get("person.tracked_person")
assert state.state == STATE_UNKNOWN assert state.state == STATE_UNKNOWN
@ -392,7 +404,9 @@ async def test_load_person_storage(hass, hass_admin_user, storage_setup):
assert state.attributes.get(ATTR_USER_ID) == hass_admin_user.id assert state.attributes.get(ATTR_USER_ID) == hass_admin_user.id
async def test_load_person_storage_two_nonlinked(hass, hass_storage): async def test_load_person_storage_two_nonlinked(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test loading two users with both not having a user linked.""" """Test loading two users with both not having a user linked."""
hass_storage[DOMAIN] = { hass_storage[DOMAIN] = {
"key": DOMAIN, "key": DOMAIN,
@ -421,7 +435,9 @@ async def test_load_person_storage_two_nonlinked(hass, hass_storage):
assert hass.states.get("person.tracked_person_2") is not None assert hass.states.get("person.tracked_person_2") is not None
async def test_ws_list(hass, hass_ws_client, storage_setup): async def test_ws_list(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, storage_setup
) -> None:
"""Test listing via WS.""" """Test listing via WS."""
manager = hass.data[DOMAIN][1] manager = hass.data[DOMAIN][1]
@ -435,7 +451,12 @@ async def test_ws_list(hass, hass_ws_client, storage_setup):
assert len(resp["result"]["config"]) == 0 assert len(resp["result"]["config"]) == 0
async def test_ws_create(hass, hass_ws_client, storage_setup, hass_read_only_user): async def test_ws_create(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
storage_setup,
hass_read_only_user: MockUser,
) -> None:
"""Test creating via WS.""" """Test creating via WS."""
manager = hass.data[DOMAIN][1] manager = hass.data[DOMAIN][1]
@ -461,8 +482,12 @@ async def test_ws_create(hass, hass_ws_client, storage_setup, hass_read_only_use
async def test_ws_create_requires_admin( async def test_ws_create_requires_admin(
hass, hass_ws_client, storage_setup, hass_admin_user, hass_read_only_user hass: HomeAssistant,
): hass_ws_client: WebSocketGenerator,
storage_setup,
hass_admin_user: MockUser,
hass_read_only_user: MockUser,
) -> None:
"""Test creating via WS requires admin.""" """Test creating via WS requires admin."""
hass_admin_user.groups = [] hass_admin_user.groups = []
manager = hass.data[DOMAIN][1] manager = hass.data[DOMAIN][1]
@ -486,7 +511,9 @@ async def test_ws_create_requires_admin(
assert not resp["success"] assert not resp["success"]
async def test_ws_update(hass, hass_ws_client, storage_setup): async def test_ws_update(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, storage_setup
) -> None:
"""Test updating via WS.""" """Test updating via WS."""
manager = hass.data[DOMAIN][1] manager = hass.data[DOMAIN][1]
@ -534,8 +561,11 @@ async def test_ws_update(hass, hass_ws_client, storage_setup):
async def test_ws_update_require_admin( async def test_ws_update_require_admin(
hass, hass_ws_client, storage_setup, hass_admin_user hass: HomeAssistant,
): hass_ws_client: WebSocketGenerator,
storage_setup,
hass_admin_user: MockUser,
) -> None:
"""Test updating via WS requires admin.""" """Test updating via WS requires admin."""
hass_admin_user.groups = [] hass_admin_user.groups = []
manager = hass.data[DOMAIN][1] manager = hass.data[DOMAIN][1]
@ -560,7 +590,9 @@ async def test_ws_update_require_admin(
assert original == not_updated assert original == not_updated
async def test_ws_delete(hass, hass_ws_client, storage_setup): async def test_ws_delete(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, storage_setup
) -> None:
"""Test deleting via WS.""" """Test deleting via WS."""
manager = hass.data[DOMAIN][1] manager = hass.data[DOMAIN][1]
@ -582,8 +614,11 @@ async def test_ws_delete(hass, hass_ws_client, storage_setup):
async def test_ws_delete_require_admin( async def test_ws_delete_require_admin(
hass, hass_ws_client, storage_setup, hass_admin_user hass: HomeAssistant,
): hass_ws_client: WebSocketGenerator,
storage_setup,
hass_admin_user: MockUser,
) -> None:
"""Test deleting via WS requires admin.""" """Test deleting via WS requires admin."""
hass_admin_user.groups = [] hass_admin_user.groups = []
manager = hass.data[DOMAIN][1] manager = hass.data[DOMAIN][1]
@ -607,7 +642,7 @@ async def test_ws_delete_require_admin(
assert len(persons) == 1 assert len(persons) == 1
async def test_create_invalid_user_id(hass, storage_collection): async def test_create_invalid_user_id(hass: HomeAssistant, storage_collection) -> None:
"""Test we do not allow invalid user ID during creation.""" """Test we do not allow invalid user ID during creation."""
with pytest.raises(ValueError): with pytest.raises(ValueError):
await storage_collection.async_create_item( await storage_collection.async_create_item(
@ -615,7 +650,9 @@ async def test_create_invalid_user_id(hass, storage_collection):
) )
async def test_create_duplicate_user_id(hass, hass_admin_user, storage_collection): async def test_create_duplicate_user_id(
hass: HomeAssistant, hass_admin_user: MockUser, storage_collection
) -> None:
"""Test we do not allow duplicate user ID during creation.""" """Test we do not allow duplicate user ID during creation."""
await storage_collection.async_create_item( await storage_collection.async_create_item(
{"name": "Hello", "user_id": hass_admin_user.id} {"name": "Hello", "user_id": hass_admin_user.id}
@ -627,7 +664,9 @@ async def test_create_duplicate_user_id(hass, hass_admin_user, storage_collectio
) )
async def test_update_double_user_id(hass, hass_admin_user, storage_collection): async def test_update_double_user_id(
hass: HomeAssistant, hass_admin_user: MockUser, storage_collection
) -> None:
"""Test we do not allow double user ID during update.""" """Test we do not allow double user ID during update."""
await storage_collection.async_create_item( await storage_collection.async_create_item(
{"name": "Hello", "user_id": hass_admin_user.id} {"name": "Hello", "user_id": hass_admin_user.id}
@ -640,7 +679,7 @@ async def test_update_double_user_id(hass, hass_admin_user, storage_collection):
) )
async def test_update_invalid_user_id(hass, storage_collection): async def test_update_invalid_user_id(hass: HomeAssistant, storage_collection) -> None:
"""Test updating to invalid user ID.""" """Test updating to invalid user ID."""
person = await storage_collection.async_create_item({"name": "Hello"}) person = await storage_collection.async_create_item({"name": "Hello"})
@ -651,8 +690,8 @@ async def test_update_invalid_user_id(hass, storage_collection):
async def test_update_person_when_user_removed( async def test_update_person_when_user_removed(
hass, storage_setup, hass_read_only_user hass: HomeAssistant, storage_setup, hass_read_only_user: MockUser
): ) -> None:
"""Update person when user is removed.""" """Update person when user is removed."""
storage_collection = hass.data[DOMAIN][1] storage_collection = hass.data[DOMAIN][1]
@ -666,7 +705,7 @@ async def test_update_person_when_user_removed(
assert storage_collection.data[person["id"]]["user_id"] is None assert storage_collection.data[person["id"]]["user_id"] is None
async def test_removing_device_tracker(hass, storage_setup): async def test_removing_device_tracker(hass: HomeAssistant, storage_setup) -> None:
"""Test we automatically remove removed device trackers.""" """Test we automatically remove removed device trackers."""
storage_collection = hass.data[DOMAIN][1] storage_collection = hass.data[DOMAIN][1]
reg = er.async_get(hass) reg = er.async_get(hass)
@ -684,7 +723,9 @@ async def test_removing_device_tracker(hass, storage_setup):
assert storage_collection.data[person["id"]]["device_trackers"] == [] assert storage_collection.data[person["id"]]["device_trackers"] == []
async def test_add_user_device_tracker(hass, storage_setup, hass_read_only_user): async def test_add_user_device_tracker(
hass: HomeAssistant, storage_setup, hass_read_only_user: MockUser
) -> None:
"""Test adding a device tracker to a person tied to a user.""" """Test adding a device tracker to a person tied to a user."""
storage_collection = hass.data[DOMAIN][1] storage_collection = hass.data[DOMAIN][1]
pers = await storage_collection.async_create_item( pers = await storage_collection.async_create_item(
@ -705,7 +746,7 @@ async def test_add_user_device_tracker(hass, storage_setup, hass_read_only_user)
] ]
async def test_reload(hass, hass_admin_user): async def test_reload(hass: HomeAssistant, hass_admin_user: MockUser) -> None:
"""Test reloading the YAML config.""" """Test reloading the YAML config."""
assert await async_setup_component( assert await async_setup_component(
hass, hass,
@ -761,7 +802,7 @@ async def test_reload(hass, hass_admin_user):
assert state_3.name == "Person 3" assert state_3.name == "Person 3"
async def test_person_storage_fixing_device_trackers(storage_collection): async def test_person_storage_fixing_device_trackers(storage_collection) -> None:
"""Test None device trackers become lists.""" """Test None device trackers become lists."""
with patch.object( with patch.object(
storage_collection.store, storage_collection.store,

View file

@ -45,7 +45,7 @@ async def mock_tv_pairable(mock_tv):
return mock_tv return mock_tv
async def test_form(hass, mock_setup_entry): async def test_form(hass: HomeAssistant, mock_setup_entry) -> 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}
@ -65,7 +65,7 @@ async def test_form(hass, mock_setup_entry):
assert len(mock_setup_entry.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
async def test_form_cannot_connect(hass, mock_tv): async def test_form_cannot_connect(hass: HomeAssistant, mock_tv) -> None:
"""Test we handle cannot connect error.""" """Test we handle cannot connect 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}
@ -80,7 +80,7 @@ async def test_form_cannot_connect(hass, mock_tv):
assert result["errors"] == {"base": "cannot_connect"} assert result["errors"] == {"base": "cannot_connect"}
async def test_form_unexpected_error(hass, mock_tv): async def test_form_unexpected_error(hass: HomeAssistant, mock_tv) -> None:
"""Test we handle unexpected exceptions.""" """Test we handle unexpected exceptions."""
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}
@ -95,7 +95,7 @@ async def test_form_unexpected_error(hass, mock_tv):
assert result["errors"] == {"base": "unknown"} assert result["errors"] == {"base": "unknown"}
async def test_pairing(hass, mock_tv_pairable, mock_setup_entry): async def test_pairing(hass: HomeAssistant, mock_tv_pairable, mock_setup_entry) -> None:
"""Test we get the form.""" """Test we get the form."""
mock_tv = mock_tv_pairable mock_tv = mock_tv_pairable
@ -138,7 +138,9 @@ async def test_pairing(hass, mock_tv_pairable, mock_setup_entry):
assert len(mock_setup_entry.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
async def test_pair_request_failed(hass, mock_tv_pairable, mock_setup_entry): async def test_pair_request_failed(
hass: HomeAssistant, mock_tv_pairable, mock_setup_entry
) -> None:
"""Test we get the form.""" """Test we get the form."""
mock_tv = mock_tv_pairable mock_tv = mock_tv_pairable
mock_tv.pairRequest.side_effect = PairingFailure({}) mock_tv.pairRequest.side_effect = PairingFailure({})
@ -163,7 +165,9 @@ async def test_pair_request_failed(hass, mock_tv_pairable, mock_setup_entry):
} }
async def test_pair_grant_failed(hass, mock_tv_pairable, mock_setup_entry): async def test_pair_grant_failed(
hass: HomeAssistant, mock_tv_pairable, mock_setup_entry
) -> None:
"""Test we get the form.""" """Test we get the form."""
mock_tv = mock_tv_pairable mock_tv = mock_tv_pairable

View file

@ -4,6 +4,7 @@ import pytest
import homeassistant.components.automation as automation import homeassistant.components.automation as automation
from homeassistant.components.device_automation import DeviceAutomationType from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.philips_js.const import DOMAIN from homeassistant.components.philips_js.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import ( from tests.common import (
@ -20,7 +21,7 @@ def calls(hass):
return async_mock_service(hass, "test", "automation") return async_mock_service(hass, "test", "automation")
async def test_get_triggers(hass, mock_device): async def test_get_triggers(hass: HomeAssistant, mock_device) -> None:
"""Test we get the expected triggers.""" """Test we get the expected triggers."""
expected_triggers = [ expected_triggers = [
{ {
@ -39,8 +40,8 @@ async def test_get_triggers(hass, mock_device):
async def test_if_fires_on_turn_on_request( async def test_if_fires_on_turn_on_request(
hass, calls, mock_tv, mock_entity, mock_device hass: HomeAssistant, calls, mock_tv, mock_entity, mock_device
): ) -> None:
"""Test for turn_on and turn_off triggers firing.""" """Test for turn_on and turn_off triggers firing."""
mock_tv.on = False mock_tv.on = False

View file

@ -23,7 +23,7 @@ from . import (
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
async def test_flow_user_with_api_key(hass: HomeAssistant): async def test_flow_user_with_api_key(hass: HomeAssistant) -> None:
"""Test user initialized flow with api key needed.""" """Test user initialized flow with api key needed."""
mocked_hole = _create_mocked_hole(has_data=False) mocked_hole = _create_mocked_hole(has_data=False)
with _patch_config_flow_hole(mocked_hole), _patch_setup_hole() as mock_setup: with _patch_config_flow_hole(mocked_hole), _patch_setup_hole() as mock_setup:
@ -71,7 +71,7 @@ async def test_flow_user_with_api_key(hass: HomeAssistant):
assert result["reason"] == "already_configured" assert result["reason"] == "already_configured"
async def test_flow_user_without_api_key(hass: HomeAssistant): async def test_flow_user_without_api_key(hass: HomeAssistant) -> None:
"""Test user initialized flow without api key needed.""" """Test user initialized flow without api key needed."""
mocked_hole = _create_mocked_hole() mocked_hole = _create_mocked_hole()
with _patch_config_flow_hole(mocked_hole), _patch_setup_hole() as mock_setup: with _patch_config_flow_hole(mocked_hole), _patch_setup_hole() as mock_setup:
@ -93,7 +93,7 @@ async def test_flow_user_without_api_key(hass: HomeAssistant):
mock_setup.assert_called_once() mock_setup.assert_called_once()
async def test_flow_user_invalid(hass: HomeAssistant): async def test_flow_user_invalid(hass: HomeAssistant) -> None:
"""Test user initialized flow with invalid server.""" """Test user initialized flow with invalid server."""
mocked_hole = _create_mocked_hole(True) mocked_hole = _create_mocked_hole(True)
with _patch_config_flow_hole(mocked_hole): with _patch_config_flow_hole(mocked_hole):
@ -105,7 +105,7 @@ async def test_flow_user_invalid(hass: HomeAssistant):
assert result["errors"] == {"base": "cannot_connect"} assert result["errors"] == {"base": "cannot_connect"}
async def test_flow_reauth(hass: HomeAssistant): async def test_flow_reauth(hass: HomeAssistant) -> None:
"""Test reauth flow.""" """Test reauth flow."""
mocked_hole = _create_mocked_hole(has_data=False) mocked_hole = _create_mocked_hole(has_data=False)
entry = MockConfigEntry(domain=pi_hole.DOMAIN, data=CONFIG_DATA_DEFAULTS) entry = MockConfigEntry(domain=pi_hole.DOMAIN, data=CONFIG_DATA_DEFAULTS)

View file

@ -3,6 +3,7 @@ import logging
from unittest.mock import AsyncMock from unittest.mock import AsyncMock
from hole.exceptions import HoleError from hole.exceptions import HoleError
import pytest
from homeassistant.components import pi_hole, switch from homeassistant.components import pi_hole, switch
from homeassistant.components.pi_hole.const import ( from homeassistant.components.pi_hole.const import (
@ -24,7 +25,7 @@ from . import (
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
async def test_setup_with_defaults(hass: HomeAssistant): async def test_setup_with_defaults(hass: HomeAssistant) -> None:
"""Tests component setup with default config.""" """Tests component setup with default config."""
mocked_hole = _create_mocked_hole() mocked_hole = _create_mocked_hole()
entry = MockConfigEntry( entry = MockConfigEntry(
@ -75,7 +76,7 @@ async def test_setup_with_defaults(hass: HomeAssistant):
assert state.state == "off" assert state.state == "off"
async def test_setup_name_config(hass: HomeAssistant): async def test_setup_name_config(hass: HomeAssistant) -> None:
"""Tests component setup with a custom name.""" """Tests component setup with a custom name."""
mocked_hole = _create_mocked_hole() mocked_hole = _create_mocked_hole()
entry = MockConfigEntry( entry = MockConfigEntry(
@ -93,7 +94,7 @@ async def test_setup_name_config(hass: HomeAssistant):
) )
async def test_switch(hass: HomeAssistant, caplog): async def test_switch(hass: HomeAssistant, caplog: pytest.LogCaptureFixture) -> None:
"""Test Pi-hole switch.""" """Test Pi-hole switch."""
mocked_hole = _create_mocked_hole() mocked_hole = _create_mocked_hole()
entry = MockConfigEntry(domain=pi_hole.DOMAIN, data=CONFIG_DATA) entry = MockConfigEntry(domain=pi_hole.DOMAIN, data=CONFIG_DATA)
@ -140,7 +141,7 @@ async def test_switch(hass: HomeAssistant, caplog):
assert errors[-1].message == "Unable to disable Pi-hole: Error2" assert errors[-1].message == "Unable to disable Pi-hole: Error2"
async def test_disable_service_call(hass: HomeAssistant): async def test_disable_service_call(hass: HomeAssistant) -> None:
"""Test disable service call with no Pi-hole named.""" """Test disable service call with no Pi-hole named."""
mocked_hole = _create_mocked_hole() mocked_hole = _create_mocked_hole()
@ -169,7 +170,7 @@ async def test_disable_service_call(hass: HomeAssistant):
mocked_hole.disable.assert_called_with(1) mocked_hole.disable.assert_called_with(1)
async def test_unload(hass: HomeAssistant): async def test_unload(hass: HomeAssistant) -> None:
"""Test unload entities.""" """Test unload entities."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=pi_hole.DOMAIN, domain=pi_hole.DOMAIN,
@ -188,7 +189,7 @@ async def test_unload(hass: HomeAssistant):
assert entry.entry_id not in hass.data[pi_hole.DOMAIN] assert entry.entry_id not in hass.data[pi_hole.DOMAIN]
async def test_remove_obsolete(hass: HomeAssistant): async def test_remove_obsolete(hass: HomeAssistant) -> None:
"""Test removing obsolete config entry parameters.""" """Test removing obsolete config entry parameters."""
mocked_hole = _create_mocked_hole() mocked_hole = _create_mocked_hole()
entry = MockConfigEntry( entry = MockConfigEntry(

View file

@ -9,7 +9,7 @@ from . import CONFIG_DATA_DEFAULTS, _create_mocked_hole, _patch_init_hole
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
async def test_update(hass: HomeAssistant): async def test_update(hass: HomeAssistant) -> None:
"""Tests update entity.""" """Tests update entity."""
mocked_hole = _create_mocked_hole() mocked_hole = _create_mocked_hole()
entry = MockConfigEntry(domain=pi_hole.DOMAIN, data=CONFIG_DATA_DEFAULTS) entry = MockConfigEntry(domain=pi_hole.DOMAIN, data=CONFIG_DATA_DEFAULTS)
@ -50,7 +50,7 @@ async def test_update(hass: HomeAssistant):
) )
async def test_update_no_versions(hass: HomeAssistant): async def test_update_no_versions(hass: HomeAssistant) -> None:
"""Tests update entity when no version data available.""" """Tests update entity when no version data available."""
mocked_hole = _create_mocked_hole(has_versions=False) mocked_hole = _create_mocked_hole(has_versions=False)
entry = MockConfigEntry(domain=pi_hole.DOMAIN, data=CONFIG_DATA_DEFAULTS) entry = MockConfigEntry(domain=pi_hole.DOMAIN, data=CONFIG_DATA_DEFAULTS)