Add type hints to integration tests (part 15) (#88006)

This commit is contained in:
epenet 2023-02-15 10:00:49 +01:00 committed by GitHub
parent 6c23d6abfe
commit 50cbabb2d8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
51 changed files with 896 additions and 427 deletions

View file

@ -39,7 +39,7 @@ async def test_setup_adds_proper_devices(hass: HomeAssistant) -> None:
@pytest.mark.parametrize( @pytest.mark.parametrize(
"brightness,expected", [(32, "on"), (256, "xdim 255"), (64, "xdim 63")] "brightness,expected", [(32, "on"), (256, "xdim 255"), (64, "xdim 63")]
) )
async def test_turn_on_with_no_brightness(light_mock, expected): async def test_turn_on_with_no_brightness(light_mock, expected) -> None:
"""Test turn_on.""" """Test turn_on."""
light_mock.turn_on() light_mock.turn_on()
light_mock.light.send_cmd.assert_called_once_with(expected) light_mock.light.send_cmd.assert_called_once_with(expected)
@ -53,14 +53,14 @@ async def test_turn_on_with_no_brightness(light_mock, expected):
(64, [mock.call("xdim 11")]), (64, [mock.call("xdim 11")]),
], ],
) )
async def test_turn_on_with_brightness(light_mock, expected): async def test_turn_on_with_brightness(light_mock, expected) -> None:
"""Test turn_on.""" """Test turn_on."""
light_mock.turn_on(brightness=45) light_mock.turn_on(brightness=45)
light_mock.light.send_cmd.assert_has_calls(expected) light_mock.light.send_cmd.assert_has_calls(expected)
@pytest.mark.parametrize("brightness", [32]) @pytest.mark.parametrize("brightness", [32])
async def test_turn_off(light_mock): async def test_turn_off(light_mock) -> None:
"""Test turn_off.""" """Test turn_off."""
light_mock.turn_off() light_mock.turn_off()
light_mock.light.send_cmd.assert_called_once_with("off") light_mock.light.send_cmd.assert_called_once_with("off")

View file

@ -38,18 +38,18 @@ async def test_setup_adds_proper_devices(hass: HomeAssistant) -> None:
assert await async_setup_component(hass, switch.DOMAIN, good_config) assert await async_setup_component(hass, switch.DOMAIN, good_config)
async def test_name(switch_mock): async def test_name(switch_mock) -> None:
"""Test the name.""" """Test the name."""
assert switch_mock.name == "fake_switch" assert switch_mock.name == "fake_switch"
async def test_turn_on(switch_mock): async def test_turn_on(switch_mock) -> None:
"""Test turn_on.""" """Test turn_on."""
switch_mock.turn_on() switch_mock.turn_on()
switch_mock.switch.send_cmd.assert_called_once_with("on") switch_mock.switch.send_cmd.assert_called_once_with("on")
async def test_turn_off(switch_mock): async def test_turn_off(switch_mock) -> None:
"""Test turn_off.""" """Test turn_off."""
switch_mock.turn_off() switch_mock.turn_off()
switch_mock.switch.send_cmd.assert_called_once_with("off") switch_mock.switch.send_cmd.assert_called_once_with("off")

View file

@ -70,7 +70,7 @@ SLAVE_UNIQUE_ID = "ground_floor_sensor"
}, },
], ],
) )
async def test_config_binary_sensor(hass, mock_modbus): async def test_config_binary_sensor(hass: HomeAssistant, mock_modbus) -> None:
"""Run config test for binary sensor.""" """Run config test for binary sensor."""
assert SENSOR_DOMAIN in hass.config.components assert SENSOR_DOMAIN in hass.config.components
@ -166,7 +166,7 @@ async def test_config_binary_sensor(hass, mock_modbus):
), ),
], ],
) )
async def test_all_binary_sensor(hass, expected, mock_do_cycle): async def test_all_binary_sensor(hass: HomeAssistant, expected, mock_do_cycle) -> None:
"""Run test for given config.""" """Run test for given config."""
assert hass.states.get(ENTITY_ID).state == expected assert hass.states.get(ENTITY_ID).state == expected
@ -198,7 +198,9 @@ async def test_all_binary_sensor(hass, expected, mock_do_cycle):
), ),
], ],
) )
async def test_lazy_error_binary_sensor(hass, start_expect, end_expect, mock_do_cycle): async def test_lazy_error_binary_sensor(
hass: HomeAssistant, start_expect, end_expect, mock_do_cycle
) -> None:
"""Run test for given config.""" """Run test for given config."""
now = mock_do_cycle now = mock_do_cycle
assert hass.states.get(ENTITY_ID).state == start_expect assert hass.states.get(ENTITY_ID).state == start_expect
@ -222,7 +224,9 @@ async def test_lazy_error_binary_sensor(hass, start_expect, end_expect, mock_do_
}, },
], ],
) )
async def test_service_binary_sensor_update(hass, mock_modbus, mock_ha): async def test_service_binary_sensor_update(
hass: HomeAssistant, mock_modbus, mock_ha
) -> None:
"""Run test for service homeassistant.update_entity.""" """Run test for service homeassistant.update_entity."""
await hass.services.async_call( await hass.services.async_call(
@ -267,7 +271,9 @@ ENTITY_ID2 = f"{ENTITY_ID}_1"
}, },
], ],
) )
async def test_restore_state_binary_sensor(hass, mock_test_state, mock_modbus): async def test_restore_state_binary_sensor(
hass: HomeAssistant, mock_test_state, mock_modbus
) -> None:
"""Run test for binary sensor restore state.""" """Run test for binary sensor restore state."""
assert hass.states.get(ENTITY_ID).state == mock_test_state[0].state assert hass.states.get(ENTITY_ID).state == mock_test_state[0].state
assert hass.states.get(ENTITY_ID2).state == mock_test_state[1].state assert hass.states.get(ENTITY_ID2).state == mock_test_state[1].state
@ -290,7 +296,7 @@ TEST_NAME = "test_sensor"
}, },
], ],
) )
async def test_config_slave_binary_sensor(hass, mock_modbus): async def test_config_slave_binary_sensor(hass: HomeAssistant, mock_modbus) -> None:
"""Run config test for binary sensor.""" """Run config test for binary sensor."""
assert SENSOR_DOMAIN in hass.config.components assert SENSOR_DOMAIN in hass.config.components
@ -375,7 +381,9 @@ async def test_config_slave_binary_sensor(hass, mock_modbus):
), ),
], ],
) )
async def test_slave_binary_sensor(hass, expected, slaves, mock_do_cycle): async def test_slave_binary_sensor(
hass: HomeAssistant, expected, slaves, mock_do_cycle
) -> None:
"""Run test for given config.""" """Run test for given config."""
assert hass.states.get(ENTITY_ID).state == expected assert hass.states.get(ENTITY_ID).state == expected
entity_registry = er.async_get(hass) entity_registry = er.async_get(hass)

View file

@ -103,7 +103,7 @@ ENTITY_ID = f"{CLIMATE_DOMAIN}.{TEST_ENTITY_NAME}".replace(" ", "_")
}, },
], ],
) )
async def test_config_climate(hass, mock_modbus): async def test_config_climate(hass: HomeAssistant, mock_modbus) -> None:
"""Run configuration test for climate.""" """Run configuration test for climate."""
assert CLIMATE_DOMAIN in hass.config.components assert CLIMATE_DOMAIN in hass.config.components
@ -134,7 +134,7 @@ async def test_config_climate(hass, mock_modbus):
}, },
], ],
) )
async def test_config_hvac_mode_register(hass, mock_modbus): async def test_config_hvac_mode_register(hass: HomeAssistant, mock_modbus) -> None:
"""Run configuration test for mode register.""" """Run configuration test for mode register."""
state = hass.states.get(ENTITY_ID) state = hass.states.get(ENTITY_ID)
assert HVACMode.OFF in state.attributes[ATTR_HVAC_MODES] assert HVACMode.OFF in state.attributes[ATTR_HVAC_MODES]
@ -161,7 +161,7 @@ async def test_config_hvac_mode_register(hass, mock_modbus):
}, },
], ],
) )
async def test_config_hvac_onoff_register(hass, mock_modbus): async def test_config_hvac_onoff_register(hass: HomeAssistant, mock_modbus) -> None:
"""Run configuration test for On/Off register.""" """Run configuration test for On/Off register."""
state = hass.states.get(ENTITY_ID) state = hass.states.get(ENTITY_ID)
assert HVACMode.OFF in state.attributes[ATTR_HVAC_MODES] assert HVACMode.OFF in state.attributes[ATTR_HVAC_MODES]
@ -193,7 +193,9 @@ async def test_config_hvac_onoff_register(hass, mock_modbus):
), ),
], ],
) )
async def test_temperature_climate(hass, expected, mock_do_cycle): async def test_temperature_climate(
hass: HomeAssistant, expected, mock_do_cycle
) -> None:
"""Run test for given config.""" """Run test for given config."""
assert hass.states.get(ENTITY_ID).state == expected assert hass.states.get(ENTITY_ID).state == expected
@ -277,8 +279,8 @@ async def test_temperature_climate(hass, expected, mock_do_cycle):
], ],
) )
async def test_service_climate_update( async def test_service_climate_update(
hass, mock_modbus, mock_ha, result, register_words hass: HomeAssistant, mock_modbus, mock_ha, result, register_words
): ) -> None:
"""Run test for service homeassistant.update_entity.""" """Run test for service homeassistant.update_entity."""
mock_modbus.read_holding_registers.return_value = ReadResult(register_words) mock_modbus.read_holding_registers.return_value = ReadResult(register_words)
await hass.services.async_call( await hass.services.async_call(
@ -354,8 +356,8 @@ async def test_service_climate_update(
], ],
) )
async def test_service_climate_set_temperature( async def test_service_climate_set_temperature(
hass, temperature, result, mock_modbus, mock_ha hass: HomeAssistant, temperature, result, mock_modbus, mock_ha
): ) -> None:
"""Test set_temperature.""" """Test set_temperature."""
mock_modbus.read_holding_registers.return_value = ReadResult(result) mock_modbus.read_holding_registers.return_value = ReadResult(result)
await hass.services.async_call( await hass.services.async_call(
@ -417,7 +419,9 @@ async def test_service_climate_set_temperature(
), ),
], ],
) )
async def test_service_set_mode(hass, hvac_mode, result, mock_modbus, mock_ha): async def test_service_set_mode(
hass: HomeAssistant, hvac_mode, result, mock_modbus, mock_ha
) -> None:
"""Test set mode.""" """Test set mode."""
mock_modbus.read_holding_registers.return_value = ReadResult(result) mock_modbus.read_holding_registers.return_value = ReadResult(result)
await hass.services.async_call( await hass.services.async_call(
@ -455,7 +459,9 @@ test_value.attributes = {ATTR_TEMPERATURE: 37}
}, },
], ],
) )
async def test_restore_state_climate(hass, mock_test_state, mock_modbus): async def test_restore_state_climate(
hass: HomeAssistant, mock_test_state, mock_modbus
) -> None:
"""Run test for sensor restore state.""" """Run test for sensor restore state."""
state = hass.states.get(ENTITY_ID) state = hass.states.get(ENTITY_ID)
assert state.state == HVACMode.AUTO assert state.state == HVACMode.AUTO
@ -489,7 +495,9 @@ async def test_restore_state_climate(hass, mock_test_state, mock_modbus):
), ),
], ],
) )
async def test_lazy_error_climate(hass, mock_do_cycle, start_expect, end_expect): async def test_lazy_error_climate(
hass: HomeAssistant, mock_do_cycle, start_expect, end_expect
) -> None:
"""Run test for sensor.""" """Run test for sensor."""
hass.states.async_set(ENTITY_ID, 17) hass.states.async_set(ENTITY_ID, 17)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -533,7 +541,7 @@ async def test_lazy_error_climate(hass, mock_do_cycle, start_expect, end_expect)
), ),
], ],
) )
async def test_wrong_unpack_climate(hass, mock_do_cycle): async def test_wrong_unpack_climate(hass: HomeAssistant, mock_do_cycle) -> None:
"""Run test for sensor.""" """Run test for sensor."""
assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE

View file

@ -63,7 +63,7 @@ ENTITY_ID2 = f"{ENTITY_ID}_2"
}, },
], ],
) )
async def test_config_cover(hass, mock_modbus): async def test_config_cover(hass: HomeAssistant, mock_modbus) -> None:
"""Run configuration test for cover.""" """Run configuration test for cover."""
assert COVER_DOMAIN in hass.config.components assert COVER_DOMAIN in hass.config.components
@ -108,7 +108,7 @@ async def test_config_cover(hass, mock_modbus):
), ),
], ],
) )
async def test_coil_cover(hass, expected, mock_do_cycle): async def test_coil_cover(hass: HomeAssistant, expected, mock_do_cycle) -> None:
"""Run test for given config.""" """Run test for given config."""
assert hass.states.get(ENTITY_ID).state == expected assert hass.states.get(ENTITY_ID).state == expected
@ -141,7 +141,9 @@ async def test_coil_cover(hass, expected, mock_do_cycle):
), ),
], ],
) )
async def test_lazy_error_cover(hass, start_expect, end_expect, mock_do_cycle): async def test_lazy_error_cover(
hass: HomeAssistant, start_expect, end_expect, mock_do_cycle
) -> None:
"""Run test for given config.""" """Run test for given config."""
now = mock_do_cycle now = mock_do_cycle
assert hass.states.get(ENTITY_ID).state == start_expect assert hass.states.get(ENTITY_ID).state == start_expect
@ -190,7 +192,7 @@ async def test_lazy_error_cover(hass, start_expect, end_expect, mock_do_cycle):
), ),
], ],
) )
async def test_register_cover(hass, expected, mock_do_cycle): async def test_register_cover(hass: HomeAssistant, expected, mock_do_cycle) -> None:
"""Run test for given config.""" """Run test for given config."""
assert hass.states.get(ENTITY_ID).state == expected assert hass.states.get(ENTITY_ID).state == expected
@ -209,7 +211,7 @@ async def test_register_cover(hass, expected, mock_do_cycle):
}, },
], ],
) )
async def test_service_cover_update(hass, mock_modbus, mock_ha): async def test_service_cover_update(hass: HomeAssistant, mock_modbus, mock_ha) -> None:
"""Run test for service homeassistant.update_entity.""" """Run test for service homeassistant.update_entity."""
await hass.services.async_call( await hass.services.async_call(
"homeassistant", "update_entity", {"entity_id": ENTITY_ID}, blocking=True "homeassistant", "update_entity", {"entity_id": ENTITY_ID}, blocking=True
@ -253,7 +255,9 @@ async def test_service_cover_update(hass, mock_modbus, mock_ha):
}, },
], ],
) )
async def test_restore_state_cover(hass, mock_test_state, mock_modbus): async def test_restore_state_cover(
hass: HomeAssistant, mock_test_state, mock_modbus
) -> None:
"""Run test for cover restore state.""" """Run test for cover restore state."""
test_state = mock_test_state[0].state test_state = mock_test_state[0].state
assert hass.states.get(ENTITY_ID).state == test_state assert hass.states.get(ENTITY_ID).state == test_state
@ -280,7 +284,7 @@ async def test_restore_state_cover(hass, mock_test_state, mock_modbus):
}, },
], ],
) )
async def test_service_cover_move(hass, mock_modbus, mock_ha): async def test_service_cover_move(hass: HomeAssistant, mock_modbus, mock_ha) -> None:
"""Run test for service homeassistant.update_entity.""" """Run test for service homeassistant.update_entity."""
mock_modbus.read_holding_registers.return_value = ReadResult([0x01]) mock_modbus.read_holding_registers.return_value = ReadResult([0x01])

View file

@ -123,7 +123,7 @@ ENTITY_ID2 = f"{ENTITY_ID}_2"
}, },
], ],
) )
async def test_config_fan(hass, mock_modbus): async def test_config_fan(hass: HomeAssistant, mock_modbus) -> None:
"""Run configuration test for fan.""" """Run configuration test for fan."""
assert FAN_DOMAIN in hass.config.components assert FAN_DOMAIN in hass.config.components
@ -188,7 +188,7 @@ async def test_config_fan(hass, mock_modbus):
), ),
], ],
) )
async def test_all_fan(hass, mock_do_cycle, expected): async def test_all_fan(hass: HomeAssistant, mock_do_cycle, expected) -> None:
"""Run test for given config.""" """Run test for given config."""
assert hass.states.get(ENTITY_ID).state == expected assert hass.states.get(ENTITY_ID).state == expected
@ -212,7 +212,9 @@ async def test_all_fan(hass, mock_do_cycle, expected):
}, },
], ],
) )
async def test_restore_state_fan(hass, mock_test_state, mock_modbus): async def test_restore_state_fan(
hass: HomeAssistant, mock_test_state, mock_modbus
) -> None:
"""Run test for fan restore state.""" """Run test for fan restore state."""
assert hass.states.get(ENTITY_ID).state == STATE_ON assert hass.states.get(ENTITY_ID).state == STATE_ON
@ -239,7 +241,9 @@ async def test_restore_state_fan(hass, mock_test_state, mock_modbus):
}, },
], ],
) )
async def test_fan_service_turn(hass, caplog, mock_modbus): async def test_fan_service_turn(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, mock_modbus
) -> None:
"""Run test for service turn_on/turn_off.""" """Run test for service turn_on/turn_off."""
assert MODBUS_DOMAIN in hass.config.components assert MODBUS_DOMAIN in hass.config.components
@ -299,7 +303,7 @@ async def test_fan_service_turn(hass, caplog, mock_modbus):
}, },
], ],
) )
async def test_service_fan_update(hass, mock_modbus, mock_ha): async def test_service_fan_update(hass: HomeAssistant, mock_modbus, mock_ha) -> None:
"""Run test for service homeassistant.update_entity.""" """Run test for service homeassistant.update_entity."""
await hass.services.async_call( await hass.services.async_call(
"homeassistant", "update_entity", {"entity_id": ENTITY_ID}, blocking=True "homeassistant", "update_entity", {"entity_id": ENTITY_ID}, blocking=True

View file

@ -167,7 +167,7 @@ async def test_number_validator() -> None:
}, },
], ],
) )
async def test_ok_struct_validator(do_config): async def test_ok_struct_validator(do_config) -> None:
"""Test struct validator.""" """Test struct validator."""
try: try:
struct_validator(do_config) struct_validator(do_config)
@ -223,7 +223,7 @@ async def test_ok_struct_validator(do_config):
}, },
], ],
) )
async def test_exception_struct_validator(do_config): async def test_exception_struct_validator(do_config) -> None:
"""Test struct validator.""" """Test struct validator."""
try: try:
struct_validator(do_config) struct_validator(do_config)
@ -265,7 +265,7 @@ async def test_exception_struct_validator(do_config):
], ],
], ],
) )
async def test_duplicate_modbus_validator(do_config): async def test_duplicate_modbus_validator(do_config) -> None:
"""Test duplicate modbus validator.""" """Test duplicate modbus validator."""
duplicate_modbus_validator(do_config) duplicate_modbus_validator(do_config)
assert len(do_config) == 1 assert len(do_config) == 1
@ -316,7 +316,7 @@ async def test_duplicate_modbus_validator(do_config):
], ],
], ],
) )
async def test_duplicate_entity_validator(do_config): async def test_duplicate_entity_validator(do_config) -> None:
"""Test duplicate entity validator.""" """Test duplicate entity validator."""
duplicate_entity_validator(do_config) duplicate_entity_validator(do_config)
assert len(do_config[0][CONF_SENSORS]) == 1 assert len(do_config[0][CONF_SENSORS]) == 1
@ -432,7 +432,9 @@ async def test_duplicate_entity_validator(do_config):
}, },
], ],
) )
async def test_config_modbus(hass, caplog, mock_modbus_with_pymodbus): async def test_config_modbus(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, mock_modbus_with_pymodbus
) -> None:
"""Run configuration test for modbus.""" """Run configuration test for modbus."""
@ -503,8 +505,13 @@ SERVICE = "service"
], ],
) )
async def test_pb_service_write( async def test_pb_service_write(
hass, do_write, do_return, do_unit, caplog, mock_modbus_with_pymodbus hass: HomeAssistant,
): do_write,
do_return,
do_unit,
caplog: pytest.LogCaptureFixture,
mock_modbus_with_pymodbus,
) -> None:
"""Run test for service write_register.""" """Run test for service write_register."""
func_name = { func_name = {
@ -610,8 +617,13 @@ async def mock_modbus_read_pymodbus_fixture(
], ],
) )
async def test_pb_read( async def test_pb_read(
hass, do_domain, do_expect_state, do_expect_value, caplog, mock_modbus_read_pymodbus hass: HomeAssistant,
): do_domain,
do_expect_state,
do_expect_value,
caplog: pytest.LogCaptureFixture,
mock_modbus_read_pymodbus,
) -> None:
"""Run test for different read.""" """Run test for different read."""
# Check state # Check state
@ -654,7 +666,9 @@ async def test_pymodbus_constructor_fail(
assert mock_pb.called assert mock_pb.called
async def test_pymodbus_close_fail(hass, caplog, mock_pymodbus): async def test_pymodbus_close_fail(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, mock_pymodbus
) -> None:
"""Run test for failing pymodbus close.""" """Run test for failing pymodbus close."""
config = { config = {
DOMAIN: [ DOMAIN: [
@ -673,7 +687,9 @@ async def test_pymodbus_close_fail(hass, caplog, mock_pymodbus):
# Close() is called as part of teardown # Close() is called as part of teardown
async def test_pymodbus_connect_fail(hass, caplog, mock_pymodbus): async def test_pymodbus_connect_fail(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, mock_pymodbus
) -> None:
"""Run test for failing pymodbus constructor.""" """Run test for failing pymodbus constructor."""
config = { config = {
DOMAIN: [ DOMAIN: [
@ -692,7 +708,9 @@ async def test_pymodbus_connect_fail(hass, caplog, mock_pymodbus):
assert ExceptionMessage in caplog.text assert ExceptionMessage in caplog.text
async def test_delay(hass, mock_pymodbus, freezer: FrozenDateTimeFactory): async def test_delay(
hass: HomeAssistant, mock_pymodbus, freezer: FrozenDateTimeFactory
) -> None:
"""Run test for startup delay.""" """Run test for startup delay."""
# the purpose of this test is to test startup delay # the purpose of this test is to test startup delay
@ -764,7 +782,12 @@ async def test_delay(hass, mock_pymodbus, freezer: FrozenDateTimeFactory):
}, },
], ],
) )
async def test_shutdown(hass, caplog, mock_pymodbus, mock_modbus_with_pymodbus): async def test_shutdown(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
mock_pymodbus,
mock_modbus_with_pymodbus,
) -> None:
"""Run test for shutdown.""" """Run test for shutdown."""
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -787,7 +810,9 @@ async def test_shutdown(hass, caplog, mock_pymodbus, mock_modbus_with_pymodbus):
}, },
], ],
) )
async def test_stop_restart(hass, caplog, mock_modbus): async def test_stop_restart(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, mock_modbus
) -> None:
"""Run test for service stop.""" """Run test for service stop."""
caplog.set_level(logging.INFO) caplog.set_level(logging.INFO)
@ -827,7 +852,7 @@ async def test_stop_restart(hass, caplog, mock_modbus):
@pytest.mark.parametrize("do_config", [{}]) @pytest.mark.parametrize("do_config", [{}])
async def test_write_no_client(hass, mock_modbus): async def test_write_no_client(hass: HomeAssistant, mock_modbus) -> None:
"""Run test for service stop and write without client.""" """Run test for service stop and write without client."""
mock_modbus.reset() mock_modbus.reset()
@ -849,8 +874,11 @@ async def test_write_no_client(hass, mock_modbus):
@pytest.mark.parametrize("do_config", [{}]) @pytest.mark.parametrize("do_config", [{}])
async def test_integration_reload( async def test_integration_reload(
hass, caplog, mock_modbus, freezer: FrozenDateTimeFactory hass: HomeAssistant,
): caplog: pytest.LogCaptureFixture,
mock_modbus,
freezer: FrozenDateTimeFactory,
) -> None:
"""Run test for integration reload.""" """Run test for integration reload."""
caplog.set_level(logging.INFO) caplog.set_level(logging.INFO)
@ -868,7 +896,9 @@ async def test_integration_reload(
@pytest.mark.parametrize("do_config", [{}]) @pytest.mark.parametrize("do_config", [{}])
async def test_integration_reload_failed(hass, caplog, mock_modbus) -> None: async def test_integration_reload_failed(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, mock_modbus
) -> None:
"""Run test for integration connect failure on reload.""" """Run test for integration connect failure on reload."""
caplog.set_level(logging.INFO) caplog.set_level(logging.INFO)
caplog.clear() caplog.clear()

View file

@ -123,7 +123,7 @@ ENTITY_ID2 = f"{ENTITY_ID}_2"
}, },
], ],
) )
async def test_config_light(hass, mock_modbus): async def test_config_light(hass: HomeAssistant, mock_modbus) -> None:
"""Run configuration test for light.""" """Run configuration test for light."""
assert LIGHT_DOMAIN in hass.config.components assert LIGHT_DOMAIN in hass.config.components
@ -188,7 +188,7 @@ async def test_config_light(hass, mock_modbus):
), ),
], ],
) )
async def test_all_light(hass, mock_do_cycle, expected): async def test_all_light(hass: HomeAssistant, mock_do_cycle, expected) -> None:
"""Run test for given config.""" """Run test for given config."""
assert hass.states.get(ENTITY_ID).state == expected assert hass.states.get(ENTITY_ID).state == expected
@ -212,7 +212,9 @@ async def test_all_light(hass, mock_do_cycle, expected):
}, },
], ],
) )
async def test_restore_state_light(hass, mock_test_state, mock_modbus): async def test_restore_state_light(
hass: HomeAssistant, mock_test_state, mock_modbus
) -> None:
"""Run test for sensor restore state.""" """Run test for sensor restore state."""
assert hass.states.get(ENTITY_ID).state == mock_test_state[0].state assert hass.states.get(ENTITY_ID).state == mock_test_state[0].state
@ -239,7 +241,9 @@ async def test_restore_state_light(hass, mock_test_state, mock_modbus):
}, },
], ],
) )
async def test_light_service_turn(hass, caplog, mock_modbus): async def test_light_service_turn(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, mock_modbus
) -> None:
"""Run test for service turn_on/turn_off.""" """Run test for service turn_on/turn_off."""
assert MODBUS_DOMAIN in hass.config.components assert MODBUS_DOMAIN in hass.config.components
@ -299,7 +303,7 @@ async def test_light_service_turn(hass, caplog, mock_modbus):
}, },
], ],
) )
async def test_service_light_update(hass, mock_modbus, mock_ha): async def test_service_light_update(hass: HomeAssistant, mock_modbus, mock_ha) -> None:
"""Run test for service homeassistant.update_entity.""" """Run test for service homeassistant.update_entity."""
await hass.services.async_call( await hass.services.async_call(
"homeassistant", "update_entity", {"entity_id": ENTITY_ID}, blocking=True "homeassistant", "update_entity", {"entity_id": ENTITY_ID}, blocking=True

View file

@ -146,7 +146,7 @@ SLAVE_UNIQUE_ID = "ground_floor_sensor"
}, },
], ],
) )
async def test_config_sensor(hass, mock_modbus): async def test_config_sensor(hass: HomeAssistant, mock_modbus) -> None:
"""Run configuration test for sensor.""" """Run configuration test for sensor."""
assert SENSOR_DOMAIN in hass.config.components assert SENSOR_DOMAIN in hass.config.components
@ -247,7 +247,9 @@ async def test_config_sensor(hass, mock_modbus):
), ),
], ],
) )
async def test_config_wrong_struct_sensor(hass, error_message, mock_modbus, caplog): async def test_config_wrong_struct_sensor(
hass: HomeAssistant, error_message, mock_modbus, caplog: pytest.LogCaptureFixture
) -> None:
"""Run test for sensor with wrong struct.""" """Run test for sensor with wrong struct."""
messages = str([x.message for x in caplog.get_records("setup")]) messages = str([x.message for x in caplog.get_records("setup")])
assert error_message in messages assert error_message in messages
@ -586,7 +588,7 @@ async def test_config_wrong_struct_sensor(hass, error_message, mock_modbus, capl
), ),
], ],
) )
async def test_all_sensor(hass, mock_do_cycle, expected): async def test_all_sensor(hass: HomeAssistant, mock_do_cycle, expected) -> None:
"""Run test for sensor.""" """Run test for sensor."""
assert hass.states.get(ENTITY_ID).state == expected assert hass.states.get(ENTITY_ID).state == expected
@ -673,7 +675,7 @@ async def test_all_sensor(hass, mock_do_cycle, expected):
), ),
], ],
) )
async def test_slave_sensor(hass, mock_do_cycle, expected): async def test_slave_sensor(hass: HomeAssistant, mock_do_cycle, expected) -> None:
"""Run test for sensor.""" """Run test for sensor."""
assert hass.states.get(ENTITY_ID).state == expected[0] assert hass.states.get(ENTITY_ID).state == expected[0]
entity_registry = er.async_get(hass) entity_registry = er.async_get(hass)
@ -717,7 +719,7 @@ async def test_slave_sensor(hass, mock_do_cycle, expected):
), ),
], ],
) )
async def test_wrong_unpack(hass, mock_do_cycle): async def test_wrong_unpack(hass: HomeAssistant, mock_do_cycle) -> None:
"""Run test for sensor.""" """Run test for sensor."""
assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE
@ -748,7 +750,9 @@ async def test_wrong_unpack(hass, mock_do_cycle):
), ),
], ],
) )
async def test_lazy_error_sensor(hass, mock_do_cycle, start_expect, end_expect): async def test_lazy_error_sensor(
hass: HomeAssistant, mock_do_cycle, start_expect, end_expect
) -> None:
"""Run test for sensor.""" """Run test for sensor."""
hass.states.async_set(ENTITY_ID, 17) hass.states.async_set(ENTITY_ID, 17)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -809,7 +813,7 @@ async def test_lazy_error_sensor(hass, mock_do_cycle, start_expect, end_expect):
), ),
], ],
) )
async def test_struct_sensor(hass, mock_do_cycle, expected): async def test_struct_sensor(hass: HomeAssistant, mock_do_cycle, expected) -> None:
"""Run test for sensor struct.""" """Run test for sensor struct."""
assert hass.states.get(ENTITY_ID).state == expected assert hass.states.get(ENTITY_ID).state == expected
@ -887,7 +891,7 @@ async def test_struct_sensor(hass, mock_do_cycle, expected):
), ),
], ],
) )
async def test_wrap_sensor(hass, mock_do_cycle, expected): async def test_wrap_sensor(hass: HomeAssistant, mock_do_cycle, expected) -> None:
"""Run test for sensor struct.""" """Run test for sensor struct."""
assert hass.states.get(ENTITY_ID).state == expected assert hass.states.get(ENTITY_ID).state == expected
@ -921,7 +925,9 @@ async def test_wrap_sensor(hass, mock_do_cycle, expected):
}, },
], ],
) )
async def test_restore_state_sensor(hass, mock_test_state, mock_modbus): async def test_restore_state_sensor(
hass: HomeAssistant, mock_test_state, mock_modbus
) -> None:
"""Run test for sensor restore state.""" """Run test for sensor restore state."""
assert hass.states.get(ENTITY_ID).state == mock_test_state[0].state assert hass.states.get(ENTITY_ID).state == mock_test_state[0].state
@ -940,7 +946,7 @@ async def test_restore_state_sensor(hass, mock_test_state, mock_modbus):
}, },
], ],
) )
async def test_service_sensor_update(hass, mock_modbus, mock_ha): async def test_service_sensor_update(hass: HomeAssistant, mock_modbus, mock_ha) -> None:
"""Run test for service homeassistant.update_entity.""" """Run test for service homeassistant.update_entity."""
mock_modbus.read_input_registers.return_value = ReadResult([27]) mock_modbus.read_input_registers.return_value = ReadResult([27])
await hass.services.async_call( await hass.services.async_call(

View file

@ -137,7 +137,7 @@ ENTITY_ID2 = f"{ENTITY_ID}_2"
}, },
], ],
) )
async def test_config_switch(hass, mock_modbus): async def test_config_switch(hass: HomeAssistant, mock_modbus) -> None:
"""Run configurationtest for switch.""" """Run configurationtest for switch."""
assert SWITCH_DOMAIN in hass.config.components assert SWITCH_DOMAIN in hass.config.components
@ -202,7 +202,7 @@ async def test_config_switch(hass, mock_modbus):
), ),
], ],
) )
async def test_all_switch(hass, mock_do_cycle, expected): async def test_all_switch(hass: HomeAssistant, mock_do_cycle, expected) -> None:
"""Run test for given config.""" """Run test for given config."""
assert hass.states.get(ENTITY_ID).state == expected assert hass.states.get(ENTITY_ID).state == expected
@ -236,7 +236,9 @@ async def test_all_switch(hass, mock_do_cycle, expected):
), ),
], ],
) )
async def test_lazy_error_switch(hass, start_expect, end_expect, mock_do_cycle): async def test_lazy_error_switch(
hass: HomeAssistant, start_expect, end_expect, mock_do_cycle
) -> None:
"""Run test for given config.""" """Run test for given config."""
now = mock_do_cycle now = mock_do_cycle
assert hass.states.get(ENTITY_ID).state == start_expect assert hass.states.get(ENTITY_ID).state == start_expect
@ -265,7 +267,9 @@ async def test_lazy_error_switch(hass, start_expect, end_expect, mock_do_cycle):
}, },
], ],
) )
async def test_restore_state_switch(hass, mock_test_state, mock_modbus): async def test_restore_state_switch(
hass: HomeAssistant, mock_test_state, mock_modbus
) -> None:
"""Run test for sensor restore state.""" """Run test for sensor restore state."""
assert hass.states.get(ENTITY_ID).state == mock_test_state[0].state assert hass.states.get(ENTITY_ID).state == mock_test_state[0].state
@ -292,7 +296,9 @@ async def test_restore_state_switch(hass, mock_test_state, mock_modbus):
}, },
], ],
) )
async def test_switch_service_turn(hass, caplog, mock_modbus): async def test_switch_service_turn(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, mock_modbus
) -> None:
"""Run test for service turn_on/turn_off.""" """Run test for service turn_on/turn_off."""
assert MODBUS_DOMAIN in hass.config.components assert MODBUS_DOMAIN in hass.config.components
@ -351,7 +357,7 @@ async def test_switch_service_turn(hass, caplog, mock_modbus):
}, },
], ],
) )
async def test_service_switch_update(hass, mock_modbus, mock_ha): async def test_service_switch_update(hass: HomeAssistant, mock_modbus, mock_ha) -> None:
"""Run test for service homeassistant.update_entity.""" """Run test for service homeassistant.update_entity."""
await hass.services.async_call( await hass.services.async_call(
"homeassistant", "update_entity", {"entity_id": ENTITY_ID}, blocking=True "homeassistant", "update_entity", {"entity_id": ENTITY_ID}, blocking=True
@ -382,7 +388,7 @@ async def test_service_switch_update(hass, mock_modbus, mock_ha):
}, },
], ],
) )
async def test_delay_switch(hass, mock_modbus): async def test_delay_switch(hass: HomeAssistant, mock_modbus) -> None:
"""Run test for switch verify delay.""" """Run test for switch verify delay."""
mock_modbus.read_holding_registers.return_value = ReadResult([0x01]) mock_modbus.read_holding_registers.return_value = ReadResult([0x01])
now = dt_util.utcnow() now = dt_util.utcnow()

View file

@ -29,7 +29,7 @@ def _patch_setup():
@patch("serial.tools.list_ports.comports", MagicMock(return_value=[com_port()])) @patch("serial.tools.list_ports.comports", MagicMock(return_value=[com_port()]))
async def test_flow_usb(hass: HomeAssistant): async def test_flow_usb(hass: HomeAssistant) -> None:
"""Test usb discovery flow.""" """Test usb discovery flow."""
with patch_config_flow_modem(), _patch_setup(): with patch_config_flow_modem(), _patch_setup():
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
@ -49,7 +49,7 @@ async def test_flow_usb(hass: HomeAssistant):
@patch("serial.tools.list_ports.comports", MagicMock(return_value=[com_port()])) @patch("serial.tools.list_ports.comports", MagicMock(return_value=[com_port()]))
async def test_flow_usb_cannot_connect(hass: HomeAssistant): async def test_flow_usb_cannot_connect(hass: HomeAssistant) -> None:
"""Test usb flow connection error.""" """Test usb flow connection error."""
with patch_config_flow_modem() as modemmock: with patch_config_flow_modem() as modemmock:
modemmock.side_effect = phone_modem.exceptions.SerialError modemmock.side_effect = phone_modem.exceptions.SerialError
@ -61,7 +61,7 @@ async def test_flow_usb_cannot_connect(hass: HomeAssistant):
@patch("serial.tools.list_ports.comports", MagicMock(return_value=[com_port()])) @patch("serial.tools.list_ports.comports", MagicMock(return_value=[com_port()]))
async def test_flow_user(hass: HomeAssistant): async def test_flow_user(hass: HomeAssistant) -> None:
"""Test user initialized flow.""" """Test user initialized flow."""
port = com_port() port = com_port()
port_select = usb.human_readable_device_name( port_select = usb.human_readable_device_name(
@ -91,7 +91,7 @@ async def test_flow_user(hass: HomeAssistant):
@patch("serial.tools.list_ports.comports", MagicMock(return_value=[com_port()])) @patch("serial.tools.list_ports.comports", MagicMock(return_value=[com_port()]))
async def test_flow_user_error(hass: HomeAssistant): async def test_flow_user_error(hass: HomeAssistant) -> None:
"""Test user initialized flow with unreachable device.""" """Test user initialized flow with unreachable device."""
port = com_port() port = com_port()
port_select = usb.human_readable_device_name( port_select = usb.human_readable_device_name(
@ -121,7 +121,7 @@ async def test_flow_user_error(hass: HomeAssistant):
@patch("serial.tools.list_ports.comports", MagicMock()) @patch("serial.tools.list_ports.comports", MagicMock())
async def test_flow_user_no_port_list(hass: HomeAssistant): async def test_flow_user_no_port_list(hass: HomeAssistant) -> None:
"""Test user with no list of ports.""" """Test user with no list of ports."""
with patch_config_flow_modem(): with patch_config_flow_modem():
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
@ -133,7 +133,7 @@ async def test_flow_user_no_port_list(hass: HomeAssistant):
assert result["reason"] == "no_devices_found" assert result["reason"] == "no_devices_found"
async def test_abort_user_with_existing_flow(hass: HomeAssistant): async def test_abort_user_with_existing_flow(hass: HomeAssistant) -> None:
"""Test user flow is aborted when another discovery has happened.""" """Test user flow is aborted when another discovery has happened."""
with patch_config_flow_modem(): with patch_config_flow_modem():
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(

View file

@ -13,7 +13,7 @@ from . import com_port, patch_init_modem
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
async def test_setup_entry(hass: HomeAssistant): async def test_setup_entry(hass: HomeAssistant) -> None:
"""Test Modem Caller ID entry setup.""" """Test Modem Caller ID entry setup."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,
@ -28,7 +28,7 @@ async def test_setup_entry(hass: HomeAssistant):
assert entry.state == ConfigEntryState.LOADED assert entry.state == ConfigEntryState.LOADED
async def test_async_setup_entry_not_ready(hass: HomeAssistant): async def test_async_setup_entry_not_ready(hass: HomeAssistant) -> None:
"""Test that it throws ConfigEntryNotReady when exception occurs during setup.""" """Test that it throws ConfigEntryNotReady when exception occurs during setup."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,
@ -44,7 +44,7 @@ async def test_async_setup_entry_not_ready(hass: HomeAssistant):
assert not hass.data.get(DOMAIN) assert not hass.data.get(DOMAIN)
async def test_unload_entry(hass: HomeAssistant): async def test_unload_entry(hass: HomeAssistant) -> None:
"""Test unload.""" """Test unload."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,

View file

@ -2,6 +2,7 @@
from unittest.mock import patch from unittest.mock import patch
from aiomodernforms import ModernFormsConnectionError from aiomodernforms import ModernFormsConnectionError
import pytest
from homeassistant.components.fan import ( from homeassistant.components.fan import (
ATTR_DIRECTION, ATTR_DIRECTION,
@ -53,7 +54,9 @@ async def test_fan_state(
async def test_change_state( async def test_change_state(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, caplog hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None: ) -> None:
"""Test the change of state of the Modern Forms fan.""" """Test the change of state of the Modern Forms fan."""
await init_integration(hass, aioclient_mock) await init_integration(hass, aioclient_mock)
@ -85,7 +88,9 @@ async def test_change_state(
async def test_sleep_timer_services( async def test_sleep_timer_services(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, caplog hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None: ) -> None:
"""Test the change of state of the Modern Forms segments.""" """Test the change of state of the Modern Forms segments."""
await init_integration(hass, aioclient_mock) await init_integration(hass, aioclient_mock)
@ -112,7 +117,9 @@ async def test_sleep_timer_services(
async def test_change_direction( async def test_change_direction(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, caplog hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None: ) -> None:
"""Test the change of state of the Modern Forms segments.""" """Test the change of state of the Modern Forms segments."""
await init_integration(hass, aioclient_mock) await init_integration(hass, aioclient_mock)
@ -134,7 +141,9 @@ async def test_change_direction(
async def test_set_percentage( async def test_set_percentage(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, caplog hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None: ) -> None:
"""Test the change of percentage for the Modern Forms fan.""" """Test the change of percentage for the Modern Forms fan."""
await init_integration(hass, aioclient_mock) await init_integration(hass, aioclient_mock)
@ -170,7 +179,9 @@ async def test_set_percentage(
async def test_fan_error( async def test_fan_error(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, caplog hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None: ) -> None:
"""Test error handling of the Modern Forms fans.""" """Test error handling of the Modern Forms fans."""

View file

@ -2,6 +2,7 @@
from unittest.mock import patch from unittest.mock import patch
from aiomodernforms import ModernFormsConnectionError from aiomodernforms import ModernFormsConnectionError
import pytest
from homeassistant.components.light import ATTR_BRIGHTNESS, DOMAIN as LIGHT_DOMAIN from homeassistant.components.light import ATTR_BRIGHTNESS, DOMAIN as LIGHT_DOMAIN
from homeassistant.components.modern_forms.const import ( from homeassistant.components.modern_forms.const import (
@ -46,7 +47,9 @@ async def test_light_state(
async def test_change_state( async def test_change_state(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, caplog hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None: ) -> None:
"""Test the change of state of the Modern Forms segments.""" """Test the change of state of the Modern Forms segments."""
await init_integration(hass, aioclient_mock) await init_integration(hass, aioclient_mock)
@ -75,7 +78,9 @@ async def test_change_state(
async def test_sleep_timer_services( async def test_sleep_timer_services(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, caplog hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None: ) -> None:
"""Test the change of state of the Modern Forms segments.""" """Test the change of state of the Modern Forms segments."""
await init_integration(hass, aioclient_mock) await init_integration(hass, aioclient_mock)
@ -102,7 +107,9 @@ async def test_sleep_timer_services(
async def test_light_error( async def test_light_error(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, caplog hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None: ) -> None:
"""Test error handling of the Modern Forms lights.""" """Test error handling of the Modern Forms lights."""

View file

@ -2,6 +2,7 @@
from unittest.mock import patch from unittest.mock import patch
from aiomodernforms import ModernFormsConnectionError from aiomodernforms import ModernFormsConnectionError
import pytest
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import ( from homeassistant.const import (
@ -101,7 +102,9 @@ async def test_switch_change_state(
async def test_switch_error( async def test_switch_error(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, caplog hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None: ) -> None:
"""Test error handling of the Modern Forms switches.""" """Test error handling of the Modern Forms switches."""
await init_integration(hass, aioclient_mock) await init_integration(hass, aioclient_mock)

View file

@ -4,7 +4,7 @@ from unittest.mock import patch
import pytest import pytest
from homeassistant.components import device_tracker, mqtt from homeassistant.components import device_tracker, mqtt
from homeassistant.components.device_tracker.legacy import Device from homeassistant.components.device_tracker import legacy
from homeassistant.components.mqtt.const import DOMAIN as MQTT_DOMAIN from homeassistant.components.mqtt.const import DOMAIN as MQTT_DOMAIN
from homeassistant.const import STATE_HOME, STATE_NOT_HOME, STATE_UNKNOWN, Platform from homeassistant.const import STATE_HOME, STATE_NOT_HOME, STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
@ -590,7 +590,7 @@ async def test_setting_blocked_attribute_via_mqtt_json_message(
async def test_setup_with_modern_schema( async def test_setup_with_modern_schema(
hass: HomeAssistant, mock_device_tracker_conf: list[Device] hass: HomeAssistant, mock_device_tracker_conf: list[legacy.Device]
) -> None: ) -> None:
"""Test setup using the modern schema.""" """Test setup using the modern schema."""
dev_id = "jan" dev_id = "jan"

View file

@ -4,7 +4,7 @@ from unittest.mock import ANY, patch
import homeassistant.components.mqtt_eventstream as eventstream import homeassistant.components.mqtt_eventstream as eventstream
from homeassistant.const import EVENT_STATE_CHANGED, MATCH_ALL from homeassistant.const import EVENT_STATE_CHANGED, MATCH_ALL
from homeassistant.core import State, callback from homeassistant.core import HomeAssistant, State, callback
from homeassistant.helpers.json import JSONEncoder from homeassistant.helpers.json import JSONEncoder
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
@ -14,6 +14,7 @@ from tests.common import (
async_fire_time_changed, async_fire_time_changed,
mock_state_change_event, mock_state_change_event,
) )
from tests.typing import MqttMockHAClient
async def add_eventstream(hass, sub_topic=None, pub_topic=None, ignore_event=None): async def add_eventstream(hass, sub_topic=None, pub_topic=None, ignore_event=None):
@ -30,12 +31,12 @@ async def add_eventstream(hass, sub_topic=None, pub_topic=None, ignore_event=Non
) )
async def test_setup_succeeds(hass, mqtt_mock): async def test_setup_succeeds(hass: HomeAssistant, mqtt_mock: MqttMockHAClient) -> None:
"""Test the success of the setup.""" """Test the success of the setup."""
assert await add_eventstream(hass) assert await add_eventstream(hass)
async def test_setup_with_pub(hass, mqtt_mock): async def test_setup_with_pub(hass: HomeAssistant, mqtt_mock: MqttMockHAClient) -> None:
"""Test the setup with subscription.""" """Test the setup with subscription."""
# Should start off with no listeners for all events # Should start off with no listeners for all events
assert hass.bus.async_listeners().get("*") is None assert hass.bus.async_listeners().get("*") is None
@ -47,7 +48,7 @@ async def test_setup_with_pub(hass, mqtt_mock):
assert hass.bus.async_listeners().get("*") == 1 assert hass.bus.async_listeners().get("*") == 1
async def test_subscribe(hass, mqtt_mock): async def test_subscribe(hass: HomeAssistant, mqtt_mock: MqttMockHAClient) -> None:
"""Test the subscription.""" """Test the subscription."""
sub_topic = "foo" sub_topic = "foo"
assert await add_eventstream(hass, sub_topic=sub_topic) assert await add_eventstream(hass, sub_topic=sub_topic)
@ -57,7 +58,9 @@ async def test_subscribe(hass, mqtt_mock):
mqtt_mock.async_subscribe.assert_called_with(sub_topic, ANY, 0, ANY) mqtt_mock.async_subscribe.assert_called_with(sub_topic, ANY, 0, ANY)
async def test_state_changed_event_sends_message(hass, mqtt_mock): async def test_state_changed_event_sends_message(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test the sending of a new message if event changed.""" """Test the sending of a new message if event changed."""
now = dt_util.as_utc(dt_util.now()) now = dt_util.as_utc(dt_util.now())
e_id = "fake.entity" e_id = "fake.entity"
@ -104,7 +107,9 @@ async def test_state_changed_event_sends_message(hass, mqtt_mock):
assert result == event assert result == event
async def test_time_event_does_not_send_message(hass, mqtt_mock): async def test_time_event_does_not_send_message(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test the sending of a new message if time event.""" """Test the sending of a new message if time event."""
assert await add_eventstream(hass, pub_topic="bar") assert await add_eventstream(hass, pub_topic="bar")
await hass.async_block_till_done() await hass.async_block_till_done()
@ -118,7 +123,9 @@ async def test_time_event_does_not_send_message(hass, mqtt_mock):
assert not mqtt_mock.async_publish.called assert not mqtt_mock.async_publish.called
async def test_receiving_remote_event_fires_hass_event(hass, mqtt_mock): async def test_receiving_remote_event_fires_hass_event(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test the receiving of the remotely fired event.""" """Test the receiving of the remotely fired event."""
sub_topic = "foo" sub_topic = "foo"
assert await add_eventstream(hass, sub_topic=sub_topic) assert await add_eventstream(hass, sub_topic=sub_topic)
@ -144,7 +151,9 @@ async def test_receiving_remote_event_fires_hass_event(hass, mqtt_mock):
await hass.async_block_till_done() await hass.async_block_till_done()
async def test_receiving_blocked_event_fires_hass_event(hass, mqtt_mock): async def test_receiving_blocked_event_fires_hass_event(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test the receiving of blocked event does not fire.""" """Test the receiving of blocked event does not fire."""
sub_topic = "foo" sub_topic = "foo"
assert await add_eventstream(hass, sub_topic=sub_topic) assert await add_eventstream(hass, sub_topic=sub_topic)
@ -169,7 +178,9 @@ async def test_receiving_blocked_event_fires_hass_event(hass, mqtt_mock):
await hass.async_block_till_done() await hass.async_block_till_done()
async def test_ignored_event_doesnt_send_over_stream(hass, mqtt_mock): async def test_ignored_event_doesnt_send_over_stream(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test the ignoring of sending events if defined.""" """Test the ignoring of sending events if defined."""
assert await add_eventstream(hass, pub_topic="bar", ignore_event=["state_changed"]) assert await add_eventstream(hass, pub_topic="bar", ignore_event=["state_changed"])
await hass.async_block_till_done() await hass.async_block_till_done()
@ -192,7 +203,9 @@ async def test_ignored_event_doesnt_send_over_stream(hass, mqtt_mock):
assert not mqtt_mock.async_publish.called assert not mqtt_mock.async_publish.called
async def test_wrong_ignored_event_sends_over_stream(hass, mqtt_mock): async def test_wrong_ignored_event_sends_over_stream(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test the ignoring of sending events if defined.""" """Test the ignoring of sending events if defined."""
assert await add_eventstream(hass, pub_topic="bar", ignore_event=["statee_changed"]) assert await add_eventstream(hass, pub_topic="bar", ignore_event=["statee_changed"])
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -11,6 +11,7 @@ from homeassistant.components.device_tracker.legacy import (
YAML_DEVICES, YAML_DEVICES,
) )
from homeassistant.const import CONF_PLATFORM from homeassistant.const import CONF_PLATFORM
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import async_fire_mqtt_message from tests.common import async_fire_mqtt_message
@ -34,7 +35,7 @@ async def setup_comp(hass, mqtt_mock_entry_with_yaml_config):
os.remove(yaml_devices) os.remove(yaml_devices)
async def test_ensure_device_tracker_platform_validation(hass): async def test_ensure_device_tracker_platform_validation(hass: HomeAssistant) -> None:
"""Test if platform validation was done.""" """Test if platform validation was done."""
async def mock_setup_scanner(hass, config, see, discovery_info=None): async def mock_setup_scanner(hass, config, see, discovery_info=None):
@ -56,7 +57,7 @@ async def test_ensure_device_tracker_platform_validation(hass):
assert mock_sp.call_count == 1 assert mock_sp.call_count == 1
async def test_json_message(hass): async def test_json_message(hass: HomeAssistant) -> None:
"""Test json location message.""" """Test json location message."""
dev_id = "zanzito" dev_id = "zanzito"
topic = "location/zanzito" topic = "location/zanzito"
@ -74,7 +75,9 @@ async def test_json_message(hass):
assert state.attributes.get("longitude") == 1.0 assert state.attributes.get("longitude") == 1.0
async def test_non_json_message(hass, caplog): async def test_non_json_message(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test receiving a non JSON message.""" """Test receiving a non JSON message."""
dev_id = "zanzito" dev_id = "zanzito"
topic = "location/zanzito" topic = "location/zanzito"
@ -93,7 +96,9 @@ async def test_non_json_message(hass, caplog):
assert "Error parsing JSON payload: home" in caplog.text assert "Error parsing JSON payload: home" in caplog.text
async def test_incomplete_message(hass, caplog): async def test_incomplete_message(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test receiving an incomplete message.""" """Test receiving an incomplete message."""
dev_id = "zanzito" dev_id = "zanzito"
topic = "location/zanzito" topic = "location/zanzito"
@ -115,7 +120,7 @@ async def test_incomplete_message(hass, caplog):
) )
async def test_single_level_wildcard_topic(hass): async def test_single_level_wildcard_topic(hass: HomeAssistant) -> None:
"""Test single level wildcard topic.""" """Test single level wildcard topic."""
dev_id = "zanzito" dev_id = "zanzito"
subscription = "location/+/zanzito" subscription = "location/+/zanzito"
@ -134,7 +139,7 @@ async def test_single_level_wildcard_topic(hass):
assert state.attributes.get("longitude") == 1.0 assert state.attributes.get("longitude") == 1.0
async def test_multi_level_wildcard_topic(hass): async def test_multi_level_wildcard_topic(hass: HomeAssistant) -> None:
"""Test multi level wildcard topic.""" """Test multi level wildcard topic."""
dev_id = "zanzito" dev_id = "zanzito"
subscription = "location/#" subscription = "location/#"
@ -153,7 +158,7 @@ async def test_multi_level_wildcard_topic(hass):
assert state.attributes.get("longitude") == 1.0 assert state.attributes.get("longitude") == 1.0
async def test_single_level_wildcard_topic_not_matching(hass): async def test_single_level_wildcard_topic_not_matching(hass: HomeAssistant) -> None:
"""Test not matching single level wildcard topic.""" """Test not matching single level wildcard topic."""
dev_id = "zanzito" dev_id = "zanzito"
entity_id = f"{DT_DOMAIN}.{dev_id}" entity_id = f"{DT_DOMAIN}.{dev_id}"
@ -171,7 +176,7 @@ async def test_single_level_wildcard_topic_not_matching(hass):
assert hass.states.get(entity_id) is None assert hass.states.get(entity_id) is None
async def test_multi_level_wildcard_topic_not_matching(hass): async def test_multi_level_wildcard_topic_not_matching(hass: HomeAssistant) -> None:
"""Test not matching multi level wildcard topic.""" """Test not matching multi level wildcard topic."""
dev_id = "zanzito" dev_id = "zanzito"
entity_id = f"{DT_DOMAIN}.{dev_id}" entity_id = f"{DT_DOMAIN}.{dev_id}"

View file

@ -18,6 +18,7 @@ from homeassistant.setup import async_setup_component
from homeassistant.util import dt from homeassistant.util import dt
from tests.common import async_fire_mqtt_message from tests.common import async_fire_mqtt_message
from tests.typing import MqttMockHAClientGenerator
DEVICE_ID = "123TESTMAC" DEVICE_ID = "123TESTMAC"
NAME = "test_device" NAME = "test_device"
@ -55,7 +56,9 @@ async def assert_distance(hass, distance):
assert state.attributes.get("distance") == distance assert state.attributes.get("distance") == distance
async def test_room_update(hass, mqtt_mock_entry_with_yaml_config): async def test_room_update(
hass: HomeAssistant, mqtt_mock_entry_with_yaml_config: MqttMockHAClientGenerator
) -> None:
"""Test the updating between rooms.""" """Test the updating between rooms."""
assert await async_setup_component( assert await async_setup_component(
hass, hass,
@ -93,7 +96,7 @@ async def test_room_update(hass, mqtt_mock_entry_with_yaml_config):
async def test_unique_id_is_set( async def test_unique_id_is_set(
hass: HomeAssistant, mqtt_mock_entry_with_yaml_config hass: HomeAssistant, mqtt_mock_entry_with_yaml_config: MqttMockHAClientGenerator
) -> None: ) -> None:
"""Test the updating between rooms.""" """Test the updating between rooms."""
unique_name = "my_unique_name_0123456789" unique_name = "my_unique_name_0123456789"

View file

@ -2,10 +2,11 @@
from unittest.mock import ANY, call from unittest.mock import ANY, call
import homeassistant.components.mqtt_statestream as statestream import homeassistant.components.mqtt_statestream as statestream
from homeassistant.core import State from homeassistant.core import HomeAssistant, State
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import mock_state_change_event from tests.common import mock_state_change_event
from tests.typing import MqttMockHAClient
async def add_statestream( async def add_statestream(
@ -33,22 +34,30 @@ async def add_statestream(
) )
async def test_fails_with_no_base(hass, mqtt_mock): async def test_fails_with_no_base(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Setup should fail if no base_topic is set.""" """Setup should fail if no base_topic is set."""
assert await add_statestream(hass) is False assert await add_statestream(hass) is False
async def test_setup_succeeds_without_attributes(hass, mqtt_mock): async def test_setup_succeeds_without_attributes(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test the success of the setup with a valid base_topic.""" """Test the success of the setup with a valid base_topic."""
assert await add_statestream(hass, base_topic="pub") assert await add_statestream(hass, base_topic="pub")
async def test_setup_succeeds_with_attributes(hass, mqtt_mock): async def test_setup_succeeds_with_attributes(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test setup with a valid base_topic and publish_attributes.""" """Test setup with a valid base_topic and publish_attributes."""
assert await add_statestream(hass, base_topic="pub", publish_attributes=True) assert await add_statestream(hass, base_topic="pub", publish_attributes=True)
async def test_state_changed_event_sends_message(hass, mqtt_mock): async def test_state_changed_event_sends_message(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test the sending of a new message if event changed.""" """Test the sending of a new message if event changed."""
e_id = "fake.entity" e_id = "fake.entity"
base_topic = "pub" base_topic = "pub"
@ -71,7 +80,9 @@ async def test_state_changed_event_sends_message(hass, mqtt_mock):
assert mqtt_mock.async_publish.called assert mqtt_mock.async_publish.called
async def test_state_changed_event_sends_message_and_timestamp(hass, mqtt_mock): async def test_state_changed_event_sends_message_and_timestamp(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test the sending of a message and timestamps if event changed.""" """Test the sending of a message and timestamps if event changed."""
e_id = "another.entity" e_id = "another.entity"
base_topic = "pub" base_topic = "pub"
@ -102,7 +113,9 @@ async def test_state_changed_event_sends_message_and_timestamp(hass, mqtt_mock):
assert mqtt_mock.async_publish.called assert mqtt_mock.async_publish.called
async def test_state_changed_attr_sends_message(hass, mqtt_mock): async def test_state_changed_attr_sends_message(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test the sending of a new message if attribute changed.""" """Test the sending of a new message if attribute changed."""
e_id = "fake.entity" e_id = "fake.entity"
base_topic = "pub" base_topic = "pub"
@ -134,7 +147,9 @@ async def test_state_changed_attr_sends_message(hass, mqtt_mock):
assert mqtt_mock.async_publish.called assert mqtt_mock.async_publish.called
async def test_state_changed_event_include_domain(hass, mqtt_mock): async def test_state_changed_event_include_domain(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test that filtering on included domain works as expected.""" """Test that filtering on included domain works as expected."""
base_topic = "pub" base_topic = "pub"
@ -170,7 +185,9 @@ async def test_state_changed_event_include_domain(hass, mqtt_mock):
assert not mqtt_mock.async_publish.called assert not mqtt_mock.async_publish.called
async def test_state_changed_event_include_entity(hass, mqtt_mock): async def test_state_changed_event_include_entity(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test that filtering on included entity works as expected.""" """Test that filtering on included entity works as expected."""
base_topic = "pub" base_topic = "pub"
@ -206,7 +223,9 @@ async def test_state_changed_event_include_entity(hass, mqtt_mock):
assert not mqtt_mock.async_publish.called assert not mqtt_mock.async_publish.called
async def test_state_changed_event_exclude_domain(hass, mqtt_mock): async def test_state_changed_event_exclude_domain(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test that filtering on excluded domain works as expected.""" """Test that filtering on excluded domain works as expected."""
base_topic = "pub" base_topic = "pub"
@ -242,7 +261,9 @@ async def test_state_changed_event_exclude_domain(hass, mqtt_mock):
assert not mqtt_mock.async_publish.called assert not mqtt_mock.async_publish.called
async def test_state_changed_event_exclude_entity(hass, mqtt_mock): async def test_state_changed_event_exclude_entity(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test that filtering on excluded entity works as expected.""" """Test that filtering on excluded entity works as expected."""
base_topic = "pub" base_topic = "pub"
@ -278,7 +299,9 @@ async def test_state_changed_event_exclude_entity(hass, mqtt_mock):
assert not mqtt_mock.async_publish.called assert not mqtt_mock.async_publish.called
async def test_state_changed_event_exclude_domain_include_entity(hass, mqtt_mock): async def test_state_changed_event_exclude_domain_include_entity(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test filtering with excluded domain and included entity.""" """Test filtering with excluded domain and included entity."""
base_topic = "pub" base_topic = "pub"
@ -314,7 +337,9 @@ async def test_state_changed_event_exclude_domain_include_entity(hass, mqtt_mock
assert not mqtt_mock.async_publish.called assert not mqtt_mock.async_publish.called
async def test_state_changed_event_include_domain_exclude_entity(hass, mqtt_mock): async def test_state_changed_event_include_domain_exclude_entity(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test filtering with included domain and excluded entity.""" """Test filtering with included domain and excluded entity."""
base_topic = "pub" base_topic = "pub"
@ -350,7 +375,9 @@ async def test_state_changed_event_include_domain_exclude_entity(hass, mqtt_mock
assert not mqtt_mock.async_publish.called assert not mqtt_mock.async_publish.called
async def test_state_changed_event_include_globs(hass, mqtt_mock): async def test_state_changed_event_include_globs(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test that filtering on included glob works as expected.""" """Test that filtering on included glob works as expected."""
base_topic = "pub" base_topic = "pub"
@ -388,7 +415,9 @@ async def test_state_changed_event_include_globs(hass, mqtt_mock):
assert not mqtt_mock.async_publish.called assert not mqtt_mock.async_publish.called
async def test_state_changed_event_exclude_globs(hass, mqtt_mock): async def test_state_changed_event_exclude_globs(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test that filtering on excluded globs works as expected.""" """Test that filtering on excluded globs works as expected."""
base_topic = "pub" base_topic = "pub"
@ -424,7 +453,9 @@ async def test_state_changed_event_exclude_globs(hass, mqtt_mock):
assert not mqtt_mock.async_publish.called assert not mqtt_mock.async_publish.called
async def test_state_changed_event_exclude_domain_globs_include_entity(hass, mqtt_mock): async def test_state_changed_event_exclude_domain_globs_include_entity(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test filtering with excluded domain and glob and included entity.""" """Test filtering with excluded domain and glob and included entity."""
base_topic = "pub" base_topic = "pub"
@ -480,7 +511,9 @@ async def test_state_changed_event_exclude_domain_globs_include_entity(hass, mqt
assert not mqtt_mock.async_publish.called assert not mqtt_mock.async_publish.called
async def test_state_changed_event_include_domain_globs_exclude_entity(hass, mqtt_mock): async def test_state_changed_event_include_domain_globs_exclude_entity(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test filtering with included domain and glob and excluded entity.""" """Test filtering with included domain and glob and excluded entity."""
base_topic = "pub" base_topic = "pub"

View file

@ -174,7 +174,7 @@ async def test_reauth_unsuccessful(hass: HomeAssistant) -> None:
(ValueError, "unknown"), (ValueError, "unknown"),
], ],
) )
async def test_form_with_auth_errors(hass, error): async def test_form_with_auth_errors(hass: HomeAssistant, error) -> None:
"""Test we handle errors when auth is required.""" """Test we handle errors when auth is required."""
exc, base_error = error exc, base_error = error
with patch( with patch(
@ -213,7 +213,7 @@ async def test_form_with_auth_errors(hass, error):
(ValueError, "unknown"), (ValueError, "unknown"),
], ],
) )
async def test_form_errors(hass, error): async def test_form_errors(hass: HomeAssistant, error) -> None:
"""Test we handle errors.""" """Test we handle errors."""
exc, base_error = error exc, base_error = error
with patch( with patch(
@ -391,7 +391,7 @@ async def test_zeroconf_host_already_configured(hass: HomeAssistant) -> None:
(CannotGetMac("Cannot get MAC address from device"), "device_unsupported"), (CannotGetMac("Cannot get MAC address from device"), "device_unsupported"),
], ],
) )
async def test_zeroconf_errors(hass, error): async def test_zeroconf_errors(hass: HomeAssistant, error) -> None:
"""Test we handle errors.""" """Test we handle errors."""
exc, reason = error exc, reason = error
with patch( with patch(

View file

@ -9,6 +9,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 = "1234" CLIENT_ID = "1234"
CLIENT_SECRET = "5678" CLIENT_SECRET = "5678"
@ -19,8 +21,11 @@ OAUTH2_TOKEN = VENDOR.token_endpoint
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,
@ -73,7 +78,7 @@ async def test_full_flow(
assert len(mock_setup.mock_calls) == 1 assert len(mock_setup.mock_calls) == 1
async def test_abort_if_already_setup(hass: HomeAssistant): async def test_abort_if_already_setup(hass: HomeAssistant) -> None:
"""Test we abort if Neato is already setup.""" """Test we abort if Neato is already setup."""
entry = MockConfigEntry( entry = MockConfigEntry(
domain=NEATO_DOMAIN, domain=NEATO_DOMAIN,
@ -90,8 +95,11 @@ async def test_abort_if_already_setup(hass: HomeAssistant):
async def test_reauth( async def test_reauth(
hass: HomeAssistant, 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:
"""Test initialization of the reauth flow.""" """Test initialization of the reauth flow."""
assert await setup.async_setup_component( assert await setup.async_setup_component(
hass, hass,

View file

@ -30,6 +30,7 @@ from homeassistant.const import (
STATE_ALARM_TRIGGERED, STATE_ALARM_TRIGGERED,
STATE_UNKNOWN, STATE_UNKNOWN,
) )
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
VALID_CONFIG = { VALID_CONFIG = {
@ -44,7 +45,7 @@ VALID_CONFIG = {
} }
async def test_setup_platform(hass, mock_nessclient): async def test_setup_platform(hass: HomeAssistant, mock_nessclient) -> None:
"""Test platform setup.""" """Test platform setup."""
await async_setup_component(hass, DOMAIN, VALID_CONFIG) await async_setup_component(hass, DOMAIN, VALID_CONFIG)
assert hass.services.has_service(DOMAIN, "panic") assert hass.services.has_service(DOMAIN, "panic")
@ -59,7 +60,7 @@ async def test_setup_platform(hass, mock_nessclient):
assert mock_nessclient.update.call_count == 1 assert mock_nessclient.update.call_count == 1
async def test_panic_service(hass, mock_nessclient): async def test_panic_service(hass: HomeAssistant, mock_nessclient) -> None:
"""Test calling panic service.""" """Test calling panic service."""
await async_setup_component(hass, DOMAIN, VALID_CONFIG) await async_setup_component(hass, DOMAIN, VALID_CONFIG)
await hass.services.async_call( await hass.services.async_call(
@ -68,7 +69,7 @@ async def test_panic_service(hass, mock_nessclient):
mock_nessclient.panic.assert_awaited_once_with("1234") mock_nessclient.panic.assert_awaited_once_with("1234")
async def test_aux_service(hass, mock_nessclient): async def test_aux_service(hass: HomeAssistant, mock_nessclient) -> None:
"""Test calling aux service.""" """Test calling aux service."""
await async_setup_component(hass, DOMAIN, VALID_CONFIG) await async_setup_component(hass, DOMAIN, VALID_CONFIG)
await hass.services.async_call( await hass.services.async_call(
@ -77,7 +78,7 @@ async def test_aux_service(hass, mock_nessclient):
mock_nessclient.aux.assert_awaited_once_with(1, True) mock_nessclient.aux.assert_awaited_once_with(1, True)
async def test_dispatch_state_change(hass, mock_nessclient): async def test_dispatch_state_change(hass: HomeAssistant, mock_nessclient) -> None:
"""Test calling aux service.""" """Test calling aux service."""
await async_setup_component(hass, DOMAIN, VALID_CONFIG) await async_setup_component(hass, DOMAIN, VALID_CONFIG)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -89,7 +90,7 @@ async def test_dispatch_state_change(hass, mock_nessclient):
assert hass.states.is_state("alarm_control_panel.alarm_panel", STATE_ALARM_ARMING) assert hass.states.is_state("alarm_control_panel.alarm_panel", STATE_ALARM_ARMING)
async def test_alarm_disarm(hass, mock_nessclient): async def test_alarm_disarm(hass: HomeAssistant, mock_nessclient) -> None:
"""Test disarm.""" """Test disarm."""
await async_setup_component(hass, DOMAIN, VALID_CONFIG) await async_setup_component(hass, DOMAIN, VALID_CONFIG)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -106,7 +107,7 @@ async def test_alarm_disarm(hass, mock_nessclient):
mock_nessclient.disarm.assert_called_once_with("1234") mock_nessclient.disarm.assert_called_once_with("1234")
async def test_alarm_arm_away(hass, mock_nessclient): async def test_alarm_arm_away(hass: HomeAssistant, mock_nessclient) -> None:
"""Test disarm.""" """Test disarm."""
await async_setup_component(hass, DOMAIN, VALID_CONFIG) await async_setup_component(hass, DOMAIN, VALID_CONFIG)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -123,7 +124,7 @@ async def test_alarm_arm_away(hass, mock_nessclient):
mock_nessclient.arm_away.assert_called_once_with("1234") mock_nessclient.arm_away.assert_called_once_with("1234")
async def test_alarm_arm_home(hass, mock_nessclient): async def test_alarm_arm_home(hass: HomeAssistant, mock_nessclient) -> None:
"""Test disarm.""" """Test disarm."""
await async_setup_component(hass, DOMAIN, VALID_CONFIG) await async_setup_component(hass, DOMAIN, VALID_CONFIG)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -140,7 +141,7 @@ async def test_alarm_arm_home(hass, mock_nessclient):
mock_nessclient.arm_home.assert_called_once_with("1234") mock_nessclient.arm_home.assert_called_once_with("1234")
async def test_alarm_trigger(hass, mock_nessclient): async def test_alarm_trigger(hass: HomeAssistant, mock_nessclient) -> None:
"""Test disarm.""" """Test disarm."""
await async_setup_component(hass, DOMAIN, VALID_CONFIG) await async_setup_component(hass, DOMAIN, VALID_CONFIG)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -157,7 +158,7 @@ async def test_alarm_trigger(hass, mock_nessclient):
mock_nessclient.panic.assert_called_once_with("1234") mock_nessclient.panic.assert_called_once_with("1234")
async def test_dispatch_zone_change(hass, mock_nessclient): async def test_dispatch_zone_change(hass: HomeAssistant, mock_nessclient) -> None:
"""Test zone change events dispatch a signal to subscribers.""" """Test zone change events dispatch a signal to subscribers."""
await async_setup_component(hass, DOMAIN, VALID_CONFIG) await async_setup_component(hass, DOMAIN, VALID_CONFIG)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -170,7 +171,7 @@ async def test_dispatch_zone_change(hass, mock_nessclient):
assert hass.states.is_state("binary_sensor.zone_2", "off") assert hass.states.is_state("binary_sensor.zone_2", "off")
async def test_arming_state_change(hass, mock_nessclient): async def test_arming_state_change(hass: HomeAssistant, mock_nessclient) -> None:
"""Test arming state change handing.""" """Test arming state change handing."""
states = [ states = [
(MockArmingState.UNKNOWN, STATE_UNKNOWN), (MockArmingState.UNKNOWN, STATE_UNKNOWN),

View file

@ -3,7 +3,6 @@
These tests fake out the subscriber/devicemanager, and are not using a real These tests fake out the subscriber/devicemanager, and are not using a real
pubsub subscriber. pubsub subscriber.
""" """
import datetime import datetime
from http import HTTPStatus from http import HTTPStatus
from unittest.mock import AsyncMock, Mock, patch from unittest.mock import AsyncMock, Mock, patch
@ -26,6 +25,7 @@ from .common import DEVICE_ID, CreateDevice, FakeSubscriber, PlatformSetup
from .conftest import FakeAuth from .conftest import FakeAuth
from tests.common import async_fire_time_changed from tests.common import async_fire_time_changed
from tests.typing import WebSocketGenerator
PLATFORM = "camera" PLATFORM = "camera"
CAMERA_DEVICE_TYPE = "sdm.devices.types.CAMERA" CAMERA_DEVICE_TYPE = "sdm.devices.types.CAMERA"
@ -178,7 +178,7 @@ async def fire_alarm(hass, point_in_time):
await hass.async_block_till_done() await hass.async_block_till_done()
async def test_no_devices(hass: HomeAssistant, setup_platform: PlatformSetup): async def test_no_devices(hass: HomeAssistant, setup_platform: PlatformSetup) -> None:
"""Test configuration that returns no devices.""" """Test configuration that returns no devices."""
await setup_platform() await setup_platform()
assert len(hass.states.async_all()) == 0 assert len(hass.states.async_all()) == 0
@ -186,7 +186,7 @@ async def test_no_devices(hass: HomeAssistant, setup_platform: PlatformSetup):
async def test_ineligible_device( async def test_ineligible_device(
hass: HomeAssistant, setup_platform: PlatformSetup, create_device: CreateDevice hass: HomeAssistant, setup_platform: PlatformSetup, create_device: CreateDevice
): ) -> None:
"""Test configuration with devices that do not support cameras.""" """Test configuration with devices that do not support cameras."""
create_device.create( create_device.create(
{ {
@ -202,7 +202,7 @@ async def test_ineligible_device(
async def test_camera_device( async def test_camera_device(
hass: HomeAssistant, setup_platform: PlatformSetup, camera_device: None hass: HomeAssistant, setup_platform: PlatformSetup, camera_device: None
): ) -> None:
"""Test a basic camera with a live stream.""" """Test a basic camera with a live stream."""
await setup_platform() await setup_platform()
@ -230,7 +230,7 @@ async def test_camera_stream(
camera_device: None, camera_device: None,
auth: FakeAuth, auth: FakeAuth,
mock_create_stream: Mock, mock_create_stream: Mock,
): ) -> None:
"""Test a basic camera and fetch its live stream.""" """Test a basic camera and fetch its live stream."""
auth.responses = [make_stream_url_response()] auth.responses = [make_stream_url_response()]
await setup_platform() await setup_platform()
@ -248,13 +248,13 @@ async def test_camera_stream(
async def test_camera_ws_stream( async def test_camera_ws_stream(
hass, hass: HomeAssistant,
setup_platform, setup_platform,
camera_device, camera_device,
hass_ws_client, hass_ws_client: WebSocketGenerator,
auth, auth,
mock_create_stream, mock_create_stream,
): ) -> None:
"""Test a basic camera that supports web rtc.""" """Test a basic camera that supports web rtc."""
auth.responses = [make_stream_url_response()] auth.responses = [make_stream_url_response()]
await setup_platform() await setup_platform()
@ -284,8 +284,12 @@ async def test_camera_ws_stream(
async def test_camera_ws_stream_failure( async def test_camera_ws_stream_failure(
hass, setup_platform, camera_device, hass_ws_client, auth hass: HomeAssistant,
): setup_platform,
camera_device,
hass_ws_client: WebSocketGenerator,
auth,
) -> None:
"""Test a basic camera that supports web rtc.""" """Test a basic camera that supports web rtc."""
auth.responses = [aiohttp.web.Response(status=HTTPStatus.BAD_REQUEST)] auth.responses = [aiohttp.web.Response(status=HTTPStatus.BAD_REQUEST)]
await setup_platform() await setup_platform()
@ -312,7 +316,9 @@ async def test_camera_ws_stream_failure(
assert msg["error"]["message"].startswith("Nest API error") assert msg["error"]["message"].startswith("Nest API error")
async def test_camera_stream_missing_trait(hass, setup_platform, create_device): async def test_camera_stream_missing_trait(
hass: HomeAssistant, setup_platform, create_device
) -> None:
"""Test fetching a video stream when not supported by the API.""" """Test fetching a video stream when not supported by the API."""
create_device.create( create_device.create(
{ {
@ -346,7 +352,7 @@ async def test_refresh_expired_stream_token(
setup_platform: PlatformSetup, setup_platform: PlatformSetup,
auth: FakeAuth, auth: FakeAuth,
camera_device: None, camera_device: None,
): ) -> None:
"""Test a camera stream expiration and refresh.""" """Test a camera stream expiration and refresh."""
now = utcnow() now = utcnow()
stream_1_expiration = now + datetime.timedelta(seconds=90) stream_1_expiration = now + datetime.timedelta(seconds=90)
@ -423,7 +429,7 @@ async def test_stream_response_already_expired(
auth: FakeAuth, auth: FakeAuth,
setup_platform: PlatformSetup, setup_platform: PlatformSetup,
camera_device: None, camera_device: None,
): ) -> None:
"""Test a API response returning an expired stream url.""" """Test a API response returning an expired stream url."""
now = utcnow() now = utcnow()
stream_1_expiration = now + datetime.timedelta(seconds=-90) stream_1_expiration = now + datetime.timedelta(seconds=-90)
@ -456,7 +462,7 @@ async def test_camera_removed(
camera_device: None, camera_device: None,
subscriber: FakeSubscriber, subscriber: FakeSubscriber,
setup_platform: PlatformSetup, setup_platform: PlatformSetup,
): ) -> None:
"""Test case where entities are removed and stream tokens revoked.""" """Test case where entities are removed and stream tokens revoked."""
await setup_platform() await setup_platform()
# Simplify test setup # Simplify test setup
@ -486,7 +492,7 @@ async def test_camera_remove_failure(
auth: FakeAuth, auth: FakeAuth,
camera_device: None, camera_device: None,
setup_platform: PlatformSetup, setup_platform: PlatformSetup,
): ) -> None:
"""Test case where revoking the stream token fails on unload.""" """Test case where revoking the stream token fails on unload."""
await setup_platform() await setup_platform()
@ -516,7 +522,7 @@ async def test_refresh_expired_stream_failure(
auth: FakeAuth, auth: FakeAuth,
setup_platform: PlatformSetup, setup_platform: PlatformSetup,
camera_device: None, camera_device: None,
): ) -> None:
"""Tests a failure when refreshing the stream.""" """Tests a failure when refreshing the stream."""
now = utcnow() now = utcnow()
stream_1_expiration = now + datetime.timedelta(seconds=90) stream_1_expiration = now + datetime.timedelta(seconds=90)
@ -569,8 +575,12 @@ async def test_refresh_expired_stream_failure(
async def test_camera_web_rtc( async def test_camera_web_rtc(
hass, auth, hass_ws_client, webrtc_camera_device, setup_platform hass: HomeAssistant,
): auth,
hass_ws_client: WebSocketGenerator,
webrtc_camera_device,
setup_platform,
) -> None:
"""Test a basic camera that supports web rtc.""" """Test a basic camera that supports web rtc."""
expiration = utcnow() + datetime.timedelta(seconds=100) expiration = utcnow() + datetime.timedelta(seconds=100)
auth.responses = [ auth.responses = [
@ -614,8 +624,12 @@ async def test_camera_web_rtc(
async def test_camera_web_rtc_unsupported( async def test_camera_web_rtc_unsupported(
hass, auth, hass_ws_client, camera_device, setup_platform hass: HomeAssistant,
): auth,
hass_ws_client: WebSocketGenerator,
camera_device,
setup_platform,
) -> None:
"""Test a basic camera that supports web rtc.""" """Test a basic camera that supports web rtc."""
await setup_platform() await setup_platform()
@ -644,8 +658,12 @@ async def test_camera_web_rtc_unsupported(
async def test_camera_web_rtc_offer_failure( async def test_camera_web_rtc_offer_failure(
hass, auth, hass_ws_client, webrtc_camera_device, setup_platform hass: HomeAssistant,
): auth,
hass_ws_client: WebSocketGenerator,
webrtc_camera_device,
setup_platform,
) -> None:
"""Test a basic camera that supports web rtc.""" """Test a basic camera that supports web rtc."""
auth.responses = [ auth.responses = [
aiohttp.web.Response(status=HTTPStatus.BAD_REQUEST), aiohttp.web.Response(status=HTTPStatus.BAD_REQUEST),
@ -676,8 +694,13 @@ async def test_camera_web_rtc_offer_failure(
async def test_camera_multiple_streams( async def test_camera_multiple_streams(
hass, auth, hass_ws_client, create_device, setup_platform, mock_create_stream hass: HomeAssistant,
): auth,
hass_ws_client: WebSocketGenerator,
create_device,
setup_platform,
mock_create_stream,
) -> None:
"""Test a camera supporting multiple stream types.""" """Test a camera supporting multiple stream types."""
expiration = utcnow() + datetime.timedelta(seconds=100) expiration = utcnow() + datetime.timedelta(seconds=100)
auth.responses = [ auth.responses = [

View file

@ -113,7 +113,7 @@ async def test_climate_devices(
async def test_thermostat_off( async def test_thermostat_off(
hass: HomeAssistant, setup_platform: PlatformSetup, create_device: CreateDevice hass: HomeAssistant, setup_platform: PlatformSetup, create_device: CreateDevice
): ) -> None:
"""Test a thermostat that is not running.""" """Test a thermostat that is not running."""
create_device.create( create_device.create(
{ {
@ -152,7 +152,7 @@ async def test_thermostat_off(
async def test_thermostat_heat( async def test_thermostat_heat(
hass: HomeAssistant, setup_platform: PlatformSetup, create_device: CreateDevice hass: HomeAssistant, setup_platform: PlatformSetup, create_device: CreateDevice
): ) -> None:
"""Test a thermostat that is heating.""" """Test a thermostat that is heating."""
create_device.create( create_device.create(
{ {
@ -194,7 +194,7 @@ async def test_thermostat_heat(
async def test_thermostat_cool( async def test_thermostat_cool(
hass: HomeAssistant, setup_platform: PlatformSetup, create_device: CreateDevice hass: HomeAssistant, setup_platform: PlatformSetup, create_device: CreateDevice
): ) -> None:
"""Test a thermostat that is cooling.""" """Test a thermostat that is cooling."""
create_device.create( create_device.create(
{ {
@ -236,7 +236,7 @@ async def test_thermostat_cool(
async def test_thermostat_heatcool( async def test_thermostat_heatcool(
hass: HomeAssistant, setup_platform: PlatformSetup, create_device: CreateDevice hass: HomeAssistant, setup_platform: PlatformSetup, create_device: CreateDevice
): ) -> None:
"""Test a thermostat that is cooling in heatcool mode.""" """Test a thermostat that is cooling in heatcool mode."""
create_device.create( create_device.create(
{ {
@ -1489,7 +1489,7 @@ async def test_thermostat_hvac_mode_failure(
async def test_thermostat_available( async def test_thermostat_available(
hass: HomeAssistant, setup_platform: PlatformSetup, create_device: CreateDevice hass: HomeAssistant, setup_platform: PlatformSetup, create_device: CreateDevice
): ) -> None:
"""Test a thermostat that is available.""" """Test a thermostat that is available."""
create_device.create( create_device.create(
{ {
@ -1519,7 +1519,7 @@ async def test_thermostat_available(
async def test_thermostat_unavailable( async def test_thermostat_unavailable(
hass: HomeAssistant, setup_platform: PlatformSetup, create_device: CreateDevice hass: HomeAssistant, setup_platform: PlatformSetup, create_device: CreateDevice
): ) -> None:
"""Test a thermostat that is unavailable.""" """Test a thermostat that is unavailable."""
create_device.create( create_device.create(
{ {

View file

@ -1,5 +1,4 @@
"""Test the Google Nest Device Access config flow.""" """Test the Google Nest Device Access config flow."""
from __future__ import annotations from __future__ import annotations
from typing import Any from typing import Any
@ -21,6 +20,7 @@ from homeassistant.components.application_credentials import (
) )
from homeassistant.components.nest.const import DOMAIN, OAUTH2_AUTHORIZE, OAUTH2_TOKEN from homeassistant.components.nest.const import DOMAIN, OAUTH2_AUTHORIZE, OAUTH2_TOKEN
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResult from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers import config_entry_oauth2_flow from homeassistant.helpers import config_entry_oauth2_flow
@ -197,7 +197,9 @@ async def oauth(hass, hass_client_no_auth, aioclient_mock, current_request_with_
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS]) @pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_app_credentials(hass, oauth, subscriber, setup_platform): async def test_app_credentials(
hass: HomeAssistant, oauth, subscriber, setup_platform
) -> None:
"""Check full flow.""" """Check full flow."""
await setup_platform() await setup_platform()
@ -229,7 +231,9 @@ async def test_app_credentials(hass, oauth, subscriber, setup_platform):
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS]) @pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_config_flow_restart(hass, oauth, subscriber, setup_platform): async def test_config_flow_restart(
hass: HomeAssistant, oauth, subscriber, setup_platform
) -> None:
"""Check with auth implementation is re-initialized when aborting the flow.""" """Check with auth implementation is re-initialized when aborting the flow."""
await setup_platform() await setup_platform()
@ -280,7 +284,9 @@ async def test_config_flow_restart(hass, oauth, subscriber, setup_platform):
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS]) @pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_config_flow_wrong_project_id(hass, oauth, subscriber, setup_platform): async def test_config_flow_wrong_project_id(
hass: HomeAssistant, oauth, subscriber, setup_platform
) -> None:
"""Check the case where the wrong project ids are entered.""" """Check the case where the wrong project ids are entered."""
await setup_platform() await setup_platform()
@ -331,11 +337,11 @@ async def test_config_flow_wrong_project_id(hass, oauth, subscriber, setup_platf
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS]) @pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_config_flow_pubsub_configuration_error( async def test_config_flow_pubsub_configuration_error(
hass, hass: HomeAssistant,
oauth, oauth,
setup_platform, setup_platform,
mock_subscriber, mock_subscriber,
): ) -> None:
"""Check full flow fails with configuration error.""" """Check full flow fails with configuration error."""
await setup_platform() await setup_platform()
@ -354,8 +360,8 @@ async def test_config_flow_pubsub_configuration_error(
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS]) @pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_config_flow_pubsub_subscriber_error( async def test_config_flow_pubsub_subscriber_error(
hass, oauth, setup_platform, mock_subscriber hass: HomeAssistant, oauth, setup_platform, mock_subscriber
): ) -> None:
"""Check full flow with a subscriber error.""" """Check full flow with a subscriber error."""
await setup_platform() await setup_platform()
@ -374,7 +380,7 @@ async def test_config_flow_pubsub_subscriber_error(
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_YAML_ONLY]) @pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_YAML_ONLY])
async def test_config_yaml_ignored(hass, oauth, setup_platform): async def test_config_yaml_ignored(hass: HomeAssistant, oauth, setup_platform) -> None:
"""Check full flow.""" """Check full flow."""
await setup_platform() await setup_platform()
@ -391,7 +397,9 @@ async def test_config_yaml_ignored(hass, oauth, setup_platform):
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIG_YAML_ONLY]) @pytest.mark.parametrize("nest_test_config", [TEST_CONFIG_YAML_ONLY])
async def test_web_reauth(hass, oauth, setup_platform, config_entry): async def test_web_reauth(
hass: HomeAssistant, oauth, setup_platform, config_entry
) -> None:
"""Test Nest reauthentication.""" """Test Nest reauthentication."""
await setup_platform() await setup_platform()
@ -415,7 +423,9 @@ async def test_web_reauth(hass, oauth, setup_platform, config_entry):
assert entry.data.get("subscriber_id") == orig_subscriber_id # Not updated assert entry.data.get("subscriber_id") == orig_subscriber_id # Not updated
async def test_multiple_config_entries(hass, oauth, setup_platform): async def test_multiple_config_entries(
hass: HomeAssistant, oauth, setup_platform
) -> None:
"""Verify config flow can be started when existing config entry exists.""" """Verify config flow can be started when existing config entry exists."""
await setup_platform() await setup_platform()
@ -434,7 +444,9 @@ async def test_multiple_config_entries(hass, oauth, setup_platform):
assert len(entries) == 2 assert len(entries) == 2
async def test_duplicate_config_entries(hass, oauth, setup_platform): async def test_duplicate_config_entries(
hass: HomeAssistant, oauth, setup_platform
) -> None:
"""Verify that config entries must be for unique projects.""" """Verify that config entries must be for unique projects."""
await setup_platform() await setup_platform()
@ -457,8 +469,8 @@ async def test_duplicate_config_entries(hass, oauth, setup_platform):
async def test_reauth_multiple_config_entries( async def test_reauth_multiple_config_entries(
hass, oauth, setup_platform, config_entry hass: HomeAssistant, oauth, setup_platform, config_entry
): ) -> None:
"""Test Nest reauthentication with multiple existing config entries.""" """Test Nest reauthentication with multiple existing config entries."""
await setup_platform() await setup_platform()
@ -508,7 +520,9 @@ async def test_reauth_multiple_config_entries(
@pytest.mark.parametrize( @pytest.mark.parametrize(
"nest_test_config,auth_implementation", [(TEST_CONFIG_HYBRID, APP_AUTH_DOMAIN)] "nest_test_config,auth_implementation", [(TEST_CONFIG_HYBRID, APP_AUTH_DOMAIN)]
) )
async def test_app_auth_yaml_reauth(hass, oauth, setup_platform, config_entry): async def test_app_auth_yaml_reauth(
hass: HomeAssistant, oauth, setup_platform, config_entry
) -> None:
"""Test reauth for deprecated app auth credentails upgrade instructions.""" """Test reauth for deprecated app auth credentails upgrade instructions."""
await setup_platform() await setup_platform()
@ -571,7 +585,9 @@ async def test_app_auth_yaml_reauth(hass, oauth, setup_platform, config_entry):
@pytest.mark.parametrize( @pytest.mark.parametrize(
"nest_test_config,auth_implementation", [(TEST_CONFIG_YAML_ONLY, WEB_AUTH_DOMAIN)] "nest_test_config,auth_implementation", [(TEST_CONFIG_YAML_ONLY, WEB_AUTH_DOMAIN)]
) )
async def test_web_auth_yaml_reauth(hass, oauth, setup_platform, config_entry): async def test_web_auth_yaml_reauth(
hass: HomeAssistant, oauth, setup_platform, config_entry
) -> None:
"""Test Nest reauthentication for Installed App Auth.""" """Test Nest reauthentication for Installed App Auth."""
await setup_platform() await setup_platform()
@ -597,8 +613,8 @@ async def test_web_auth_yaml_reauth(hass, oauth, setup_platform, config_entry):
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS]) @pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_pubsub_subscription_strip_whitespace( async def test_pubsub_subscription_strip_whitespace(
hass, oauth, subscriber, setup_platform hass: HomeAssistant, oauth, subscriber, setup_platform
): ) -> None:
"""Check that project id has whitespace stripped on entry.""" """Check that project id has whitespace stripped on entry."""
await setup_platform() await setup_platform()
@ -626,8 +642,8 @@ async def test_pubsub_subscription_strip_whitespace(
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS]) @pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_pubsub_subscription_auth_failure( async def test_pubsub_subscription_auth_failure(
hass, oauth, setup_platform, mock_subscriber hass: HomeAssistant, oauth, setup_platform, mock_subscriber
): ) -> None:
"""Check flow that creates a pub/sub subscription.""" """Check flow that creates a pub/sub subscription."""
await setup_platform() await setup_platform()
@ -646,8 +662,13 @@ async def test_pubsub_subscription_auth_failure(
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIG_APP_CREDS]) @pytest.mark.parametrize("nest_test_config", [TEST_CONFIG_APP_CREDS])
async def test_pubsub_subscriber_config_entry_reauth( async def test_pubsub_subscriber_config_entry_reauth(
hass, oauth, setup_platform, subscriber, config_entry, auth_implementation hass: HomeAssistant,
): oauth,
setup_platform,
subscriber,
config_entry,
auth_implementation,
) -> None:
"""Test the pubsub subscriber id is preserved during reauth.""" """Test the pubsub subscriber id is preserved during reauth."""
await setup_platform() await setup_platform()
@ -670,7 +691,9 @@ async def test_pubsub_subscriber_config_entry_reauth(
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS]) @pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_config_entry_title_from_home(hass, oauth, setup_platform, subscriber): async def test_config_entry_title_from_home(
hass: HomeAssistant, oauth, setup_platform, subscriber
) -> None:
"""Test that the Google Home name is used for the config entry title.""" """Test that the Google Home name is used for the config entry title."""
device_manager = await subscriber.async_get_device_manager() device_manager = await subscriber.async_get_device_manager()
@ -703,8 +726,8 @@ async def test_config_entry_title_from_home(hass, oauth, setup_platform, subscri
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS]) @pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_config_entry_title_multiple_homes( async def test_config_entry_title_multiple_homes(
hass, oauth, setup_platform, subscriber hass: HomeAssistant, oauth, setup_platform, subscriber
): ) -> None:
"""Test handling of multiple Google Homes authorized.""" """Test handling of multiple Google Homes authorized."""
device_manager = await subscriber.async_get_device_manager() device_manager = await subscriber.async_get_device_manager()
@ -745,7 +768,9 @@ async def test_config_entry_title_multiple_homes(
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS]) @pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_title_failure_fallback(hass, oauth, setup_platform, mock_subscriber): async def test_title_failure_fallback(
hass: HomeAssistant, oauth, setup_platform, mock_subscriber
) -> None:
"""Test exception handling when determining the structure names.""" """Test exception handling when determining the structure names."""
await setup_platform() await setup_platform()
@ -763,7 +788,9 @@ async def test_title_failure_fallback(hass, oauth, setup_platform, mock_subscrib
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS]) @pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_structure_missing_trait(hass, oauth, setup_platform, subscriber): async def test_structure_missing_trait(
hass: HomeAssistant, oauth, setup_platform, subscriber
) -> None:
"""Test handling the case where a structure has no name set.""" """Test handling the case where a structure has no name set."""
device_manager = await subscriber.async_get_device_manager() device_manager = await subscriber.async_get_device_manager()
@ -790,7 +817,7 @@ async def test_structure_missing_trait(hass, oauth, setup_platform, subscriber):
@pytest.mark.parametrize("nest_test_config", [NestTestConfig()]) @pytest.mark.parametrize("nest_test_config", [NestTestConfig()])
async def test_dhcp_discovery(hass, oauth, subscriber): async def test_dhcp_discovery(hass: HomeAssistant, oauth, subscriber) -> None:
"""Exercise discovery dhcp starts the config flow and kicks user to frontend creds flow.""" """Exercise discovery dhcp starts the config flow and kicks user to frontend creds flow."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,
@ -807,7 +834,9 @@ async def test_dhcp_discovery(hass, oauth, subscriber):
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS]) @pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_dhcp_discovery_with_creds(hass, oauth, subscriber, setup_platform): async def test_dhcp_discovery_with_creds(
hass: HomeAssistant, oauth, subscriber, setup_platform
) -> None:
"""Exercise discovery dhcp with no config present (can't run).""" """Exercise discovery dhcp with no config present (can't run)."""
await setup_platform() await setup_platform()

View file

@ -233,7 +233,7 @@ async def test_no_triggers(
assert triggers == [] assert triggers == []
async def test_fires_on_camera_motion(hass, calls): async def test_fires_on_camera_motion(hass: HomeAssistant, calls) -> None:
"""Test camera_motion triggers firing.""" """Test camera_motion triggers firing."""
assert await setup_automation(hass, DEVICE_ID, "camera_motion") assert await setup_automation(hass, DEVICE_ID, "camera_motion")
@ -244,7 +244,7 @@ async def test_fires_on_camera_motion(hass, calls):
assert calls[0].data == DATA_MESSAGE assert calls[0].data == DATA_MESSAGE
async def test_fires_on_camera_person(hass, calls): async def test_fires_on_camera_person(hass: HomeAssistant, calls) -> None:
"""Test camera_person triggers firing.""" """Test camera_person triggers firing."""
assert await setup_automation(hass, DEVICE_ID, "camera_person") assert await setup_automation(hass, DEVICE_ID, "camera_person")
@ -255,7 +255,7 @@ async def test_fires_on_camera_person(hass, calls):
assert calls[0].data == DATA_MESSAGE assert calls[0].data == DATA_MESSAGE
async def test_fires_on_camera_sound(hass, calls): async def test_fires_on_camera_sound(hass: HomeAssistant, calls) -> None:
"""Test camera_person triggers firing.""" """Test camera_person triggers firing."""
assert await setup_automation(hass, DEVICE_ID, "camera_sound") assert await setup_automation(hass, DEVICE_ID, "camera_sound")
@ -266,7 +266,7 @@ async def test_fires_on_camera_sound(hass, calls):
assert calls[0].data == DATA_MESSAGE assert calls[0].data == DATA_MESSAGE
async def test_fires_on_doorbell_chime(hass, calls): async def test_fires_on_doorbell_chime(hass: HomeAssistant, calls) -> None:
"""Test doorbell_chime triggers firing.""" """Test doorbell_chime triggers firing."""
assert await setup_automation(hass, DEVICE_ID, "doorbell_chime") assert await setup_automation(hass, DEVICE_ID, "doorbell_chime")
@ -277,7 +277,7 @@ async def test_fires_on_doorbell_chime(hass, calls):
assert calls[0].data == DATA_MESSAGE assert calls[0].data == DATA_MESSAGE
async def test_trigger_for_wrong_device_id(hass, calls): async def test_trigger_for_wrong_device_id(hass: HomeAssistant, calls) -> None:
"""Test for turn_on and turn_off triggers firing.""" """Test for turn_on and turn_off triggers firing."""
assert await setup_automation(hass, DEVICE_ID, "camera_motion") assert await setup_automation(hass, DEVICE_ID, "camera_motion")
@ -291,7 +291,7 @@ async def test_trigger_for_wrong_device_id(hass, calls):
assert len(calls) == 0 assert len(calls) == 0
async def test_trigger_for_wrong_event_type(hass, calls): async def test_trigger_for_wrong_event_type(hass: HomeAssistant, calls) -> None:
"""Test for turn_on and turn_off triggers firing.""" """Test for turn_on and turn_off triggers firing."""
assert await setup_automation(hass, DEVICE_ID, "camera_motion") assert await setup_automation(hass, DEVICE_ID, "camera_motion")

View file

@ -1,5 +1,4 @@
"""Test nest diagnostics.""" """Test nest diagnostics."""
from unittest.mock import patch from unittest.mock import patch
from google_nest_sdm.exceptions import SubscriberException from google_nest_sdm.exceptions import SubscriberException
@ -7,6 +6,7 @@ import pytest
from homeassistant.components.nest.const import DOMAIN from homeassistant.components.nest.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr from homeassistant.helpers import device_registry as dr
from .common import TEST_CONFIG_LEGACY from .common import TEST_CONFIG_LEGACY
@ -15,6 +15,7 @@ from tests.components.diagnostics import (
get_diagnostics_for_config_entry, get_diagnostics_for_config_entry,
get_diagnostics_for_device, get_diagnostics_for_device,
) )
from tests.typing import ClientSessionGenerator
NEST_DEVICE_ID = "enterprises/project-id/devices/device-id" NEST_DEVICE_ID = "enterprises/project-id/devices/device-id"
@ -88,8 +89,12 @@ def platforms() -> list[str]:
async def test_entry_diagnostics( async def test_entry_diagnostics(
hass, hass_client, create_device, setup_platform, config_entry hass: HomeAssistant,
): hass_client: ClientSessionGenerator,
create_device,
setup_platform,
config_entry,
) -> None:
"""Test config entry diagnostics.""" """Test config entry diagnostics."""
create_device.create(raw_data=DEVICE_API_DATA) create_device.create(raw_data=DEVICE_API_DATA)
await setup_platform() await setup_platform()
@ -102,8 +107,12 @@ async def test_entry_diagnostics(
async def test_device_diagnostics( async def test_device_diagnostics(
hass, hass_client, create_device, setup_platform, config_entry hass: HomeAssistant,
): hass_client: ClientSessionGenerator,
create_device,
setup_platform,
config_entry,
) -> None:
"""Test config entry diagnostics.""" """Test config entry diagnostics."""
create_device.create(raw_data=DEVICE_API_DATA) create_device.create(raw_data=DEVICE_API_DATA)
await setup_platform() await setup_platform()
@ -120,11 +129,11 @@ async def test_device_diagnostics(
async def test_setup_susbcriber_failure( async def test_setup_susbcriber_failure(
hass, hass: HomeAssistant,
hass_client, hass_client: ClientSessionGenerator,
config_entry, config_entry,
setup_base_platform, setup_base_platform,
): ) -> None:
"""Test configuration error.""" """Test configuration error."""
with patch( with patch(
"homeassistant.components.nest.api.GoogleNestSubscriber.start_async", "homeassistant.components.nest.api.GoogleNestSubscriber.start_async",
@ -139,8 +148,11 @@ async def test_setup_susbcriber_failure(
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIG_LEGACY]) @pytest.mark.parametrize("nest_test_config", [TEST_CONFIG_LEGACY])
async def test_legacy_config_entry_diagnostics( async def test_legacy_config_entry_diagnostics(
hass, hass_client, config_entry, setup_base_platform hass: HomeAssistant,
): hass_client: ClientSessionGenerator,
config_entry,
setup_base_platform,
) -> None:
"""Test config entry diagnostics for legacy integration doesn't fail.""" """Test config entry diagnostics for legacy integration doesn't fail."""
with patch("homeassistant.components.nest.legacy.Nest"): with patch("homeassistant.components.nest.legacy.Nest"):
@ -150,8 +162,12 @@ async def test_legacy_config_entry_diagnostics(
async def test_camera_diagnostics( async def test_camera_diagnostics(
hass, hass_client, create_device, setup_platform, config_entry hass: HomeAssistant,
): hass_client: ClientSessionGenerator,
create_device,
setup_platform,
config_entry,
) -> None:
"""Test config entry diagnostics.""" """Test config entry diagnostics."""
create_device.create(raw_data=CAMERA_API_DATA) create_device.create(raw_data=CAMERA_API_DATA)
await setup_platform() await setup_platform()

View file

@ -3,7 +3,6 @@
These tests fake out the subscriber/devicemanager, and are not using a real These tests fake out the subscriber/devicemanager, and are not using a real
pubsub subscriber. pubsub subscriber.
""" """
from __future__ import annotations from __future__ import annotations
from collections.abc import Mapping from collections.abc import Mapping
@ -15,6 +14,7 @@ from google_nest_sdm.device import Device
from google_nest_sdm.event import EventMessage from google_nest_sdm.event import EventMessage
import pytest import pytest
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.util.dt import utcnow from homeassistant.util.dt import utcnow
@ -150,8 +150,14 @@ def create_events(events, device_id=DEVICE_ID, timestamp=None):
], ],
) )
async def test_event( async def test_event(
hass, auth, setup_platform, subscriber, event_trait, expected_model, expected_type hass: HomeAssistant,
): auth,
setup_platform,
subscriber,
event_trait,
expected_model,
expected_type,
) -> None:
"""Test a pubsub message for a doorbell event.""" """Test a pubsub message for a doorbell event."""
events = async_capture_events(hass, NEST_EVENT) events = async_capture_events(hass, NEST_EVENT)
await setup_platform() await setup_platform()
@ -187,7 +193,9 @@ async def test_event(
["sdm.devices.traits.CameraMotion", "sdm.devices.traits.CameraPerson"], ["sdm.devices.traits.CameraMotion", "sdm.devices.traits.CameraPerson"],
], ],
) )
async def test_camera_multiple_event(hass, subscriber, setup_platform): async def test_camera_multiple_event(
hass: HomeAssistant, subscriber, setup_platform
) -> None:
"""Test a pubsub message for a camera person event.""" """Test a pubsub message for a camera person event."""
events = async_capture_events(hass, NEST_EVENT) events = async_capture_events(hass, NEST_EVENT)
await setup_platform() await setup_platform()
@ -224,7 +232,7 @@ async def test_camera_multiple_event(hass, subscriber, setup_platform):
} }
async def test_unknown_event(hass, subscriber, setup_platform): async def test_unknown_event(hass: HomeAssistant, subscriber, setup_platform) -> None:
"""Test a pubsub message for an unknown event type.""" """Test a pubsub message for an unknown event type."""
events = async_capture_events(hass, NEST_EVENT) events = async_capture_events(hass, NEST_EVENT)
await setup_platform() await setup_platform()
@ -234,7 +242,9 @@ async def test_unknown_event(hass, subscriber, setup_platform):
assert len(events) == 0 assert len(events) == 0
async def test_unknown_device_id(hass, subscriber, setup_platform): async def test_unknown_device_id(
hass: HomeAssistant, subscriber, setup_platform
) -> None:
"""Test a pubsub message for an unknown event type.""" """Test a pubsub message for an unknown event type."""
events = async_capture_events(hass, NEST_EVENT) events = async_capture_events(hass, NEST_EVENT)
await setup_platform() await setup_platform()
@ -246,7 +256,9 @@ async def test_unknown_device_id(hass, subscriber, setup_platform):
assert len(events) == 0 assert len(events) == 0
async def test_event_message_without_device_event(hass, subscriber, setup_platform): async def test_event_message_without_device_event(
hass: HomeAssistant, subscriber, setup_platform
) -> None:
"""Test a pubsub message for an unknown event type.""" """Test a pubsub message for an unknown event type."""
events = async_capture_events(hass, NEST_EVENT) events = async_capture_events(hass, NEST_EVENT)
await setup_platform() await setup_platform()
@ -270,7 +282,9 @@ async def test_event_message_without_device_event(hass, subscriber, setup_platfo
["sdm.devices.traits.CameraClipPreview", "sdm.devices.traits.CameraPerson"], ["sdm.devices.traits.CameraClipPreview", "sdm.devices.traits.CameraPerson"],
], ],
) )
async def test_doorbell_event_thread(hass, subscriber, setup_platform): async def test_doorbell_event_thread(
hass: HomeAssistant, subscriber, setup_platform
) -> None:
"""Test a series of pubsub messages in the same thread.""" """Test a series of pubsub messages in the same thread."""
events = async_capture_events(hass, NEST_EVENT) events = async_capture_events(hass, NEST_EVENT)
await setup_platform() await setup_platform()
@ -339,7 +353,9 @@ async def test_doorbell_event_thread(hass, subscriber, setup_platform):
], ],
], ],
) )
async def test_doorbell_event_session_update(hass, subscriber, setup_platform): async def test_doorbell_event_session_update(
hass: HomeAssistant, subscriber, setup_platform
) -> None:
"""Test a pubsub message with updates to an existing session.""" """Test a pubsub message with updates to an existing session."""
events = async_capture_events(hass, NEST_EVENT) events = async_capture_events(hass, NEST_EVENT)
await setup_platform() await setup_platform()
@ -401,7 +417,9 @@ async def test_doorbell_event_session_update(hass, subscriber, setup_platform):
} }
async def test_structure_update_event(hass, subscriber, setup_platform): async def test_structure_update_event(
hass: HomeAssistant, subscriber, setup_platform
) -> None:
"""Test a pubsub message for a new device being added.""" """Test a pubsub message for a new device being added."""
events = async_capture_events(hass, NEST_EVENT) events = async_capture_events(hass, NEST_EVENT)
await setup_platform() await setup_platform()
@ -463,7 +481,7 @@ async def test_structure_update_event(hass, subscriber, setup_platform):
["sdm.devices.traits.CameraMotion"], ["sdm.devices.traits.CameraMotion"],
], ],
) )
async def test_event_zones(hass, subscriber, setup_platform): async def test_event_zones(hass: HomeAssistant, subscriber, setup_platform) -> None:
"""Test events published with zone information.""" """Test events published with zone information."""
events = async_capture_events(hass, NEST_EVENT) events = async_capture_events(hass, NEST_EVENT)
await setup_platform() await setup_platform()

View file

@ -1,9 +1,10 @@
"""Test basic initialization for the Legacy Nest API using mocks for the Nest python library.""" """Test basic initialization for the Legacy Nest API using mocks for the Nest python library."""
from unittest.mock import MagicMock, PropertyMock, patch from unittest.mock import MagicMock, PropertyMock, patch
import pytest import pytest
from homeassistant.core import HomeAssistant
from .common import TEST_CONFIG_ENTRY_LEGACY, TEST_CONFIG_LEGACY from .common import TEST_CONFIG_ENTRY_LEGACY, TEST_CONFIG_LEGACY
DOMAIN = "nest" DOMAIN = "nest"
@ -36,7 +37,7 @@ def make_thermostat():
@pytest.mark.parametrize( @pytest.mark.parametrize(
"nest_test_config", [TEST_CONFIG_LEGACY, TEST_CONFIG_ENTRY_LEGACY] "nest_test_config", [TEST_CONFIG_LEGACY, TEST_CONFIG_ENTRY_LEGACY]
) )
async def test_thermostat(hass, setup_base_platform): async def test_thermostat(hass: HomeAssistant, setup_base_platform) -> None:
"""Test simple initialization for thermostat entities.""" """Test simple initialization for thermostat entities."""
thermostat = make_thermostat() thermostat = make_thermostat()

View file

@ -7,7 +7,6 @@ By default all tests use test fixtures that run in each possible configuration
mode (e.g. yaml, ConfigEntry, etc) however some tests override and just run in mode (e.g. yaml, ConfigEntry, etc) however some tests override and just run in
relevant modes. relevant modes.
""" """
import logging import logging
from typing import Any from typing import Any
from unittest.mock import patch from unittest.mock import patch
@ -22,6 +21,7 @@ import pytest
from homeassistant.components.nest import DOMAIN from homeassistant.components.nest import DOMAIN
from homeassistant.config_entries import ConfigEntryState from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from .common import ( from .common import (
PROJECT_ID, PROJECT_ID,
@ -74,7 +74,7 @@ def failing_subscriber(subscriber_side_effect: Any) -> YieldFixture[FakeSubscrib
yield subscriber yield subscriber
async def test_setup_success(hass, error_caplog, setup_platform): async def test_setup_success(hass: HomeAssistant, error_caplog, setup_platform) -> None:
"""Test successful setup.""" """Test successful setup."""
await setup_platform() await setup_platform()
assert not error_caplog.records assert not error_caplog.records
@ -86,8 +86,11 @@ async def test_setup_success(hass, error_caplog, setup_platform):
@pytest.mark.parametrize("subscriber_id", [("invalid-subscriber-format")]) @pytest.mark.parametrize("subscriber_id", [("invalid-subscriber-format")])
async def test_setup_configuration_failure( async def test_setup_configuration_failure(
hass, caplog, subscriber_id, setup_base_platform hass: HomeAssistant,
): caplog: pytest.LogCaptureFixture,
subscriber_id,
setup_base_platform,
) -> None:
"""Test configuration error.""" """Test configuration error."""
await setup_base_platform() await setup_base_platform()
@ -102,8 +105,8 @@ async def test_setup_configuration_failure(
@pytest.mark.parametrize("subscriber_side_effect", [SubscriberException()]) @pytest.mark.parametrize("subscriber_side_effect", [SubscriberException()])
async def test_setup_susbcriber_failure( async def test_setup_susbcriber_failure(
hass, warning_caplog, failing_subscriber, setup_base_platform hass: HomeAssistant, warning_caplog, failing_subscriber, setup_base_platform
): ) -> None:
"""Test configuration error.""" """Test configuration error."""
await setup_base_platform() await setup_base_platform()
assert "Subscriber error:" in warning_caplog.text assert "Subscriber error:" in warning_caplog.text
@ -113,7 +116,9 @@ async def test_setup_susbcriber_failure(
assert entries[0].state is ConfigEntryState.SETUP_RETRY assert entries[0].state is ConfigEntryState.SETUP_RETRY
async def test_setup_device_manager_failure(hass, warning_caplog, setup_base_platform): async def test_setup_device_manager_failure(
hass: HomeAssistant, warning_caplog, setup_base_platform
) -> None:
"""Test device manager api failure.""" """Test device manager api failure."""
with patch( with patch(
"homeassistant.components.nest.api.GoogleNestSubscriber.start_async" "homeassistant.components.nest.api.GoogleNestSubscriber.start_async"
@ -132,8 +137,11 @@ async def test_setup_device_manager_failure(hass, warning_caplog, setup_base_pla
@pytest.mark.parametrize("subscriber_side_effect", [AuthException()]) @pytest.mark.parametrize("subscriber_side_effect", [AuthException()])
async def test_subscriber_auth_failure( async def test_subscriber_auth_failure(
hass, caplog, setup_base_platform, failing_subscriber hass: HomeAssistant,
): caplog: pytest.LogCaptureFixture,
setup_base_platform,
failing_subscriber,
) -> None:
"""Test subscriber throws an authentication error.""" """Test subscriber throws an authentication error."""
await setup_base_platform() await setup_base_platform()
@ -147,7 +155,9 @@ async def test_subscriber_auth_failure(
@pytest.mark.parametrize("subscriber_id", [(None)]) @pytest.mark.parametrize("subscriber_id", [(None)])
async def test_setup_missing_subscriber_id(hass, warning_caplog, setup_base_platform): async def test_setup_missing_subscriber_id(
hass: HomeAssistant, warning_caplog, setup_base_platform
) -> None:
"""Test missing susbcriber id from configuration.""" """Test missing susbcriber id from configuration."""
await setup_base_platform() await setup_base_platform()
assert "Configuration option" in warning_caplog.text assert "Configuration option" in warning_caplog.text
@ -159,8 +169,8 @@ async def test_setup_missing_subscriber_id(hass, warning_caplog, setup_base_plat
@pytest.mark.parametrize("subscriber_side_effect", [(ConfigurationException())]) @pytest.mark.parametrize("subscriber_side_effect", [(ConfigurationException())])
async def test_subscriber_configuration_failure( async def test_subscriber_configuration_failure(
hass, error_caplog, setup_base_platform, failing_subscriber hass: HomeAssistant, error_caplog, setup_base_platform, failing_subscriber
): ) -> None:
"""Test configuration error.""" """Test configuration error."""
await setup_base_platform() await setup_base_platform()
assert "Configuration error: " in error_caplog.text assert "Configuration error: " in error_caplog.text
@ -174,7 +184,9 @@ async def test_subscriber_configuration_failure(
"nest_test_config", "nest_test_config",
[TEST_CONFIGFLOW_APP_CREDS], [TEST_CONFIGFLOW_APP_CREDS],
) )
async def test_empty_config(hass, error_caplog, config, setup_platform): async def test_empty_config(
hass: HomeAssistant, error_caplog, config, setup_platform
) -> None:
"""Test setup is a no-op with not config.""" """Test setup is a no-op with not config."""
await setup_platform() await setup_platform()
assert not error_caplog.records assert not error_caplog.records
@ -183,7 +195,7 @@ async def test_empty_config(hass, error_caplog, config, setup_platform):
assert len(entries) == 0 assert len(entries) == 0
async def test_unload_entry(hass, setup_platform): async def test_unload_entry(hass: HomeAssistant, setup_platform) -> None:
"""Test successful unload of a ConfigEntry.""" """Test successful unload of a ConfigEntry."""
await setup_platform() await setup_platform()
@ -214,7 +226,9 @@ async def test_unload_entry(hass, setup_platform):
], ],
ids=["yaml-config-only", "hybrid-config", "config-entry"], ids=["yaml-config-only", "hybrid-config", "config-entry"],
) )
async def test_remove_entry(hass, nest_test_config, setup_base_platform, delete_called): async def test_remove_entry(
hass: HomeAssistant, nest_test_config, setup_base_platform, delete_called
) -> None:
"""Test successful unload of a ConfigEntry.""" """Test successful unload of a ConfigEntry."""
with patch( with patch(
"homeassistant.components.nest.api.GoogleNestSubscriber", "homeassistant.components.nest.api.GoogleNestSubscriber",
@ -248,8 +262,8 @@ async def test_remove_entry(hass, nest_test_config, setup_base_platform, delete_
ids=["hyrbid-config", "app-creds"], ids=["hyrbid-config", "app-creds"],
) )
async def test_remove_entry_delete_subscriber_failure( async def test_remove_entry_delete_subscriber_failure(
hass, nest_test_config, setup_base_platform hass: HomeAssistant, nest_test_config, setup_base_platform
): ) -> None:
"""Test a failure when deleting the subscription.""" """Test a failure when deleting the subscription."""
with patch( with patch(
"homeassistant.components.nest.api.GoogleNestSubscriber", "homeassistant.components.nest.api.GoogleNestSubscriber",
@ -275,8 +289,12 @@ async def test_remove_entry_delete_subscriber_failure(
@pytest.mark.parametrize("config_entry_unique_id", [DOMAIN, None]) @pytest.mark.parametrize("config_entry_unique_id", [DOMAIN, None])
async def test_migrate_unique_id( async def test_migrate_unique_id(
hass, error_caplog, setup_platform, config_entry, config_entry_unique_id hass: HomeAssistant,
): error_caplog,
setup_platform,
config_entry,
config_entry_unique_id,
) -> None:
"""Test successful setup.""" """Test successful setup."""
assert config_entry.state is ConfigEntryState.NOT_LOADED assert config_entry.state is ConfigEntryState.NOT_LOADED

View file

@ -2,7 +2,8 @@
from urllib.parse import parse_qsl from urllib.parse import parse_qsl
import pytest import pytest
import requests_mock as rmock import requests_mock
from requests_mock import create_response
from homeassistant.components.nest import config_flow, const from homeassistant.components.nest import config_flow, const
from homeassistant.components.nest.legacy import local_auth from homeassistant.components.nest.legacy import local_auth
@ -15,7 +16,7 @@ def registered_flow(hass):
return hass.data[config_flow.DATA_FLOW_IMPL][const.DOMAIN] return hass.data[config_flow.DATA_FLOW_IMPL][const.DOMAIN]
async def test_generate_auth_url(registered_flow): async def test_generate_auth_url(registered_flow) -> None:
"""Test generating an auth url. """Test generating an auth url.
Mainly testing that it doesn't blow up. Mainly testing that it doesn't blow up.
@ -24,7 +25,9 @@ async def test_generate_auth_url(registered_flow):
assert url is not None assert url is not None
async def test_convert_code(requests_mock, registered_flow): async def test_convert_code(
requests_mock: requests_mock.Mocker, registered_flow
) -> None:
"""Test converting a code.""" """Test converting a code."""
from nest.nest import ACCESS_TOKEN_URL from nest.nest import ACCESS_TOKEN_URL
@ -40,9 +43,7 @@ async def test_convert_code(requests_mock, registered_flow):
"grant_type": "authorization_code", "grant_type": "authorization_code",
} }
return rmock.create_response( return create_response(request, json={"access_token": "TEST-ACCESS-TOKEN"})
request, json={"access_token": "TEST-ACCESS-TOKEN"}
)
requests_mock.add_matcher(token_matcher) requests_mock.add_matcher(token_matcher)

View file

@ -3,7 +3,6 @@
These tests simulate recent camera events received by the subscriber exposed These tests simulate recent camera events received by the subscriber exposed
as media in the media source. as media in the media source.
""" """
from collections.abc import Generator from collections.abc import Generator
import datetime import datetime
from http import HTTPStatus from http import HTTPStatus
@ -25,6 +24,7 @@ from homeassistant.components.media_source import (
async_resolve_media, async_resolve_media,
) )
from homeassistant.config_entries import ConfigEntryState from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.template import DATE_STR_FORMAT from homeassistant.helpers.template import DATE_STR_FORMAT
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -32,7 +32,8 @@ import homeassistant.util.dt as dt_util
from .common import DEVICE_ID, CreateDevice, FakeSubscriber from .common import DEVICE_ID, CreateDevice, FakeSubscriber
from tests.common import async_capture_events from tests.common import MockUser, async_capture_events
from tests.typing import ClientSessionGenerator
DOMAIN = "nest" DOMAIN = "nest"
DEVICE_NAME = "Front" DEVICE_NAME = "Front"
@ -235,7 +236,7 @@ def create_battery_event_data(
) )
], ],
) )
async def test_no_eligible_devices(hass, setup_platform): async def test_no_eligible_devices(hass: HomeAssistant, setup_platform) -> None:
"""Test a media source with no eligible camera devices.""" """Test a media source with no eligible camera devices."""
await setup_platform() await setup_platform()
browse = await async_browse_media(hass, f"{URI_SCHEME}{DOMAIN}") browse = await async_browse_media(hass, f"{URI_SCHEME}{DOMAIN}")
@ -246,7 +247,7 @@ async def test_no_eligible_devices(hass, setup_platform):
@pytest.mark.parametrize("device_traits", [CAMERA_TRAITS, BATTERY_CAMERA_TRAITS]) @pytest.mark.parametrize("device_traits", [CAMERA_TRAITS, BATTERY_CAMERA_TRAITS])
async def test_supported_device(hass, setup_platform): async def test_supported_device(hass: HomeAssistant, setup_platform) -> None:
"""Test a media source with a supported camera.""" """Test a media source with a supported camera."""
await setup_platform() await setup_platform()
@ -276,7 +277,7 @@ async def test_supported_device(hass, setup_platform):
assert len(browse.children) == 0 assert len(browse.children) == 0
async def test_integration_unloaded(hass, auth, setup_platform): async def test_integration_unloaded(hass: HomeAssistant, auth, setup_platform) -> None:
"""Test the media player loads, but has no devices, when config unloaded.""" """Test the media player loads, but has no devices, when config unloaded."""
await setup_platform() await setup_platform()
@ -302,7 +303,13 @@ async def test_integration_unloaded(hass, auth, setup_platform):
assert len(browse.children) == 0 assert len(browse.children) == 0
async def test_camera_event(hass, hass_client, subscriber, auth, setup_platform): async def test_camera_event(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
subscriber,
auth,
setup_platform,
) -> None:
"""Test a media source and image created for an event.""" """Test a media source and image created for an event."""
await setup_platform() await setup_platform()
@ -400,7 +407,9 @@ async def test_camera_event(hass, hass_client, subscriber, auth, setup_platform)
assert media.mime_type == "image/jpeg" assert media.mime_type == "image/jpeg"
async def test_event_order(hass, auth, subscriber, setup_platform): async def test_event_order(
hass: HomeAssistant, auth, subscriber, setup_platform
) -> None:
"""Test multiple events are in descending timestamp order.""" """Test multiple events are in descending timestamp order."""
await setup_platform() await setup_platform()
@ -466,8 +475,12 @@ async def test_event_order(hass, auth, subscriber, setup_platform):
async def test_multiple_image_events_in_session( async def test_multiple_image_events_in_session(
hass, auth, hass_client, subscriber, setup_platform hass: HomeAssistant,
): auth,
hass_client: ClientSessionGenerator,
subscriber,
setup_platform,
) -> None:
"""Test multiple events published within the same event session.""" """Test multiple events published within the same event session."""
await setup_platform() await setup_platform()
@ -577,12 +590,12 @@ async def test_multiple_image_events_in_session(
@pytest.mark.parametrize("device_traits", [BATTERY_CAMERA_TRAITS]) @pytest.mark.parametrize("device_traits", [BATTERY_CAMERA_TRAITS])
async def test_multiple_clip_preview_events_in_session( async def test_multiple_clip_preview_events_in_session(
hass, hass: HomeAssistant,
auth, auth,
hass_client, hass_client: ClientSessionGenerator,
subscriber, subscriber,
setup_platform, setup_platform,
): ) -> None:
"""Test multiple events published within the same event session.""" """Test multiple events published within the same event session."""
await setup_platform() await setup_platform()
@ -675,7 +688,9 @@ async def test_multiple_clip_preview_events_in_session(
assert contents == IMAGE_BYTES_FROM_EVENT assert contents == IMAGE_BYTES_FROM_EVENT
async def test_browse_invalid_device_id(hass, auth, setup_platform): async def test_browse_invalid_device_id(
hass: HomeAssistant, auth, setup_platform
) -> None:
"""Test a media source request for an invalid device id.""" """Test a media source request for an invalid device id."""
await setup_platform() await setup_platform()
@ -694,7 +709,9 @@ async def test_browse_invalid_device_id(hass, auth, setup_platform):
) )
async def test_browse_invalid_event_id(hass, auth, setup_platform): async def test_browse_invalid_event_id(
hass: HomeAssistant, auth, setup_platform
) -> None:
"""Test a media source browsing for an invalid event id.""" """Test a media source browsing for an invalid event id."""
await setup_platform() await setup_platform()
@ -715,7 +732,9 @@ async def test_browse_invalid_event_id(hass, auth, setup_platform):
) )
async def test_resolve_missing_event_id(hass, auth, setup_platform): async def test_resolve_missing_event_id(
hass: HomeAssistant, auth, setup_platform
) -> None:
"""Test a media source request missing an event id.""" """Test a media source request missing an event id."""
await setup_platform() await setup_platform()
@ -732,7 +751,9 @@ async def test_resolve_missing_event_id(hass, auth, setup_platform):
) )
async def test_resolve_invalid_device_id(hass, auth, setup_platform): async def test_resolve_invalid_device_id(
hass: HomeAssistant, auth, setup_platform
) -> None:
"""Test resolving media for an invalid event id.""" """Test resolving media for an invalid event id."""
await setup_platform() await setup_platform()
with pytest.raises(Unresolvable): with pytest.raises(Unresolvable):
@ -743,7 +764,9 @@ async def test_resolve_invalid_device_id(hass, auth, setup_platform):
) )
async def test_resolve_invalid_event_id(hass, auth, setup_platform): async def test_resolve_invalid_event_id(
hass: HomeAssistant, auth, setup_platform
) -> None:
"""Test resolving media for an invalid event id.""" """Test resolving media for an invalid event id."""
await setup_platform() await setup_platform()
@ -767,8 +790,13 @@ async def test_resolve_invalid_event_id(hass, auth, setup_platform):
@pytest.mark.parametrize("device_traits", [BATTERY_CAMERA_TRAITS]) @pytest.mark.parametrize("device_traits", [BATTERY_CAMERA_TRAITS])
async def test_camera_event_clip_preview( async def test_camera_event_clip_preview(
hass, auth, hass_client, mp4, subscriber, setup_platform hass: HomeAssistant,
): auth,
hass_client: ClientSessionGenerator,
mp4,
subscriber,
setup_platform,
) -> None:
"""Test an event for a battery camera video clip.""" """Test an event for a battery camera video clip."""
# Capture any events published # Capture any events published
received_events = async_capture_events(hass, NEST_EVENT) received_events = async_capture_events(hass, NEST_EVENT)
@ -871,8 +899,8 @@ async def test_camera_event_clip_preview(
async def test_event_media_render_invalid_device_id( async def test_event_media_render_invalid_device_id(
hass, auth, hass_client, setup_platform hass: HomeAssistant, auth, hass_client: ClientSessionGenerator, setup_platform
): ) -> None:
"""Test event media API called with an invalid device id.""" """Test event media API called with an invalid device id."""
await setup_platform() await setup_platform()
client = await hass_client() client = await hass_client()
@ -883,8 +911,8 @@ async def test_event_media_render_invalid_device_id(
async def test_event_media_render_invalid_event_id( async def test_event_media_render_invalid_event_id(
hass, auth, hass_client, setup_platform hass: HomeAssistant, auth, hass_client: ClientSessionGenerator, setup_platform
): ) -> None:
"""Test event media API called with an invalid device id.""" """Test event media API called with an invalid device id."""
await setup_platform() await setup_platform()
device_registry = dr.async_get(hass) device_registry = dr.async_get(hass)
@ -899,7 +927,13 @@ async def test_event_media_render_invalid_event_id(
) )
async def test_event_media_failure(hass, auth, hass_client, subscriber, setup_platform): async def test_event_media_failure(
hass: HomeAssistant,
auth,
hass_client: ClientSessionGenerator,
subscriber,
setup_platform,
) -> None:
"""Test event media fetch sees a failure from the server.""" """Test event media fetch sees a failure from the server."""
received_events = async_capture_events(hass, NEST_EVENT) received_events = async_capture_events(hass, NEST_EVENT)
@ -951,8 +985,12 @@ async def test_event_media_failure(hass, auth, hass_client, subscriber, setup_pl
async def test_media_permission_unauthorized( async def test_media_permission_unauthorized(
hass, auth, hass_client, hass_admin_user, setup_platform hass: HomeAssistant,
): auth,
hass_client: ClientSessionGenerator,
hass_admin_user: MockUser,
setup_platform,
) -> None:
"""Test case where user does not have permissions to view media.""" """Test case where user does not have permissions to view media."""
await setup_platform() await setup_platform()
assert len(hass.states.async_all()) == 1 assert len(hass.states.async_all()) == 1
@ -977,8 +1015,13 @@ async def test_media_permission_unauthorized(
async def test_multiple_devices( async def test_multiple_devices(
hass, auth, hass_client, create_device, subscriber, setup_platform hass: HomeAssistant,
): auth,
hass_client: ClientSessionGenerator,
create_device,
subscriber,
setup_platform,
) -> None:
"""Test events received for multiple devices.""" """Test events received for multiple devices."""
device_id2 = f"{DEVICE_ID}-2" device_id2 = f"{DEVICE_ID}-2"
create_device.create( create_device.create(
@ -1066,14 +1109,14 @@ def event_store() -> Generator[None, None, None]:
@pytest.mark.parametrize("device_traits", [BATTERY_CAMERA_TRAITS]) @pytest.mark.parametrize("device_traits", [BATTERY_CAMERA_TRAITS])
async def test_media_store_persistence( async def test_media_store_persistence(
hass, hass: HomeAssistant,
auth, auth,
hass_client, hass_client: ClientSessionGenerator,
event_store, event_store,
subscriber, subscriber,
setup_platform, setup_platform,
config_entry, config_entry,
): ) -> None:
"""Test the disk backed media store persistence.""" """Test the disk backed media store persistence."""
await setup_platform() await setup_platform()
@ -1160,8 +1203,12 @@ async def test_media_store_persistence(
@pytest.mark.parametrize("device_traits", [BATTERY_CAMERA_TRAITS]) @pytest.mark.parametrize("device_traits", [BATTERY_CAMERA_TRAITS])
async def test_media_store_save_filesystem_error( async def test_media_store_save_filesystem_error(
hass, auth, hass_client, subscriber, setup_platform hass: HomeAssistant,
): auth,
hass_client: ClientSessionGenerator,
subscriber,
setup_platform,
) -> None:
"""Test a filesystem error writing event media.""" """Test a filesystem error writing event media."""
await setup_platform() await setup_platform()
@ -1211,8 +1258,12 @@ async def test_media_store_save_filesystem_error(
async def test_media_store_load_filesystem_error( async def test_media_store_load_filesystem_error(
hass, auth, hass_client, subscriber, setup_platform hass: HomeAssistant,
): auth,
hass_client: ClientSessionGenerator,
subscriber,
setup_platform,
) -> None:
"""Test a filesystem error reading event media.""" """Test a filesystem error reading event media."""
await setup_platform() await setup_platform()
@ -1261,8 +1312,12 @@ async def test_media_store_load_filesystem_error(
@pytest.mark.parametrize("device_traits,cache_size", [(BATTERY_CAMERA_TRAITS, 5)]) @pytest.mark.parametrize("device_traits,cache_size", [(BATTERY_CAMERA_TRAITS, 5)])
async def test_camera_event_media_eviction( async def test_camera_event_media_eviction(
hass, auth, hass_client, subscriber, setup_platform hass: HomeAssistant,
): auth,
hass_client: ClientSessionGenerator,
subscriber,
setup_platform,
) -> None:
"""Test media files getting evicted from the cache.""" """Test media files getting evicted from the cache."""
await setup_platform() await setup_platform()
@ -1333,7 +1388,13 @@ async def test_camera_event_media_eviction(
await hass.async_block_till_done() await hass.async_block_till_done()
async def test_camera_image_resize(hass, auth, hass_client, subscriber, setup_platform): async def test_camera_image_resize(
hass: HomeAssistant,
auth,
hass_client: ClientSessionGenerator,
subscriber,
setup_platform,
) -> None:
"""Test scaling a thumbnail for an event image.""" """Test scaling a thumbnail for an event image."""
await setup_platform() await setup_platform()

View file

@ -42,7 +42,7 @@ def device_traits() -> dict[str, Any]:
async def test_thermostat_device( async def test_thermostat_device(
hass: HomeAssistant, create_device: CreateDevice, setup_platform: PlatformSetup hass: HomeAssistant, create_device: CreateDevice, setup_platform: PlatformSetup
): ) -> None:
"""Test a thermostat with temperature and humidity sensors.""" """Test a thermostat with temperature and humidity sensors."""
create_device.create( create_device.create(
{ {
@ -95,7 +95,7 @@ async def test_thermostat_device(
async def test_thermostat_device_available( async def test_thermostat_device_available(
hass: HomeAssistant, create_device: CreateDevice, setup_platform: PlatformSetup hass: HomeAssistant, create_device: CreateDevice, setup_platform: PlatformSetup
): ) -> None:
"""Test a thermostat with temperature and humidity sensors that is Online.""" """Test a thermostat with temperature and humidity sensors that is Online."""
create_device.create( create_device.create(
{ {
@ -121,7 +121,7 @@ async def test_thermostat_device_available(
async def test_thermostat_device_unavailable( async def test_thermostat_device_unavailable(
hass: HomeAssistant, create_device: CreateDevice, setup_platform: PlatformSetup hass: HomeAssistant, create_device: CreateDevice, setup_platform: PlatformSetup
): ) -> None:
"""Test a thermostat with temperature and humidity sensors that is Offline.""" """Test a thermostat with temperature and humidity sensors that is Offline."""
create_device.create( create_device.create(
{ {
@ -145,7 +145,7 @@ async def test_thermostat_device_unavailable(
assert humidity.state == STATE_UNAVAILABLE assert humidity.state == STATE_UNAVAILABLE
async def test_no_devices(hass: HomeAssistant, setup_platform: PlatformSetup): async def test_no_devices(hass: HomeAssistant, setup_platform: PlatformSetup) -> None:
"""Test no devices returned by the api.""" """Test no devices returned by the api."""
await setup_platform() await setup_platform()

View file

@ -4,6 +4,7 @@ from unittest.mock import AsyncMock, patch
import pyatmo import pyatmo
import pytest import pytest
import requests_mock
from homeassistant.components import camera from homeassistant.components import camera
from homeassistant.components.camera import STATE_STREAMING from homeassistant.components.camera import STATE_STREAMING
@ -14,6 +15,7 @@ from homeassistant.components.netatmo.const import (
SERVICE_SET_PERSONS_HOME, SERVICE_SET_PERSONS_HOME,
) )
from homeassistant.const import CONF_WEBHOOK_ID from homeassistant.const import CONF_WEBHOOK_ID
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.util import dt from homeassistant.util import dt
@ -22,7 +24,9 @@ from .common import fake_post_request, selected_platforms, simulate_webhook
from tests.common import async_capture_events, async_fire_time_changed from tests.common import async_capture_events, async_fire_time_changed
async def test_setup_component_with_webhook(hass, config_entry, netatmo_auth): async def test_setup_component_with_webhook(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test setup with webhook.""" """Test setup with webhook."""
with selected_platforms(["camera"]): with selected_platforms(["camera"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -129,7 +133,9 @@ async def test_setup_component_with_webhook(hass, config_entry, netatmo_auth):
IMAGE_BYTES_FROM_STREAM = b"test stream image bytes" IMAGE_BYTES_FROM_STREAM = b"test stream image bytes"
async def test_camera_image_local(hass, config_entry, requests_mock, netatmo_auth): async def test_camera_image_local(
hass: HomeAssistant, config_entry, requests_mock: requests_mock.Mocker, netatmo_auth
) -> None:
"""Test retrieval or local camera image.""" """Test retrieval or local camera image."""
with selected_platforms(["camera"]): with selected_platforms(["camera"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -155,7 +161,9 @@ async def test_camera_image_local(hass, config_entry, requests_mock, netatmo_aut
assert image.content == IMAGE_BYTES_FROM_STREAM assert image.content == IMAGE_BYTES_FROM_STREAM
async def test_camera_image_vpn(hass, config_entry, requests_mock, netatmo_auth): async def test_camera_image_vpn(
hass: HomeAssistant, config_entry, requests_mock: requests_mock.Mocker, netatmo_auth
) -> None:
"""Test retrieval of remote camera image.""" """Test retrieval of remote camera image."""
with selected_platforms(["camera"]): with selected_platforms(["camera"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -179,7 +187,9 @@ async def test_camera_image_vpn(hass, config_entry, requests_mock, netatmo_auth)
assert image.content == IMAGE_BYTES_FROM_STREAM assert image.content == IMAGE_BYTES_FROM_STREAM
async def test_service_set_person_away(hass, config_entry, netatmo_auth): async def test_service_set_person_away(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test service to set person as away.""" """Test service to set person as away."""
with selected_platforms(["camera"]): with selected_platforms(["camera"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -216,7 +226,9 @@ async def test_service_set_person_away(hass, config_entry, netatmo_auth):
) )
async def test_service_set_person_away_invalid_person(hass, config_entry, netatmo_auth): async def test_service_set_person_away_invalid_person(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test service to set invalid person as away.""" """Test service to set invalid person as away."""
with selected_platforms(["camera"]): with selected_platforms(["camera"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -243,8 +255,8 @@ async def test_service_set_person_away_invalid_person(hass, config_entry, netatm
async def test_service_set_persons_home_invalid_person( async def test_service_set_persons_home_invalid_person(
hass, config_entry, netatmo_auth hass: HomeAssistant, config_entry, netatmo_auth
): ) -> None:
"""Test service to set invalid persons as home.""" """Test service to set invalid persons as home."""
with selected_platforms(["camera"]): with selected_platforms(["camera"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -270,7 +282,9 @@ async def test_service_set_persons_home_invalid_person(
assert excinfo.value.args == ("Person(s) not registered ['Batman']",) assert excinfo.value.args == ("Person(s) not registered ['Batman']",)
async def test_service_set_persons_home(hass, config_entry, netatmo_auth): async def test_service_set_persons_home(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test service to set persons as home.""" """Test service to set persons as home."""
with selected_platforms(["camera"]): with selected_platforms(["camera"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -294,7 +308,9 @@ async def test_service_set_persons_home(hass, config_entry, netatmo_auth):
) )
async def test_service_set_camera_light(hass, config_entry, netatmo_auth): async def test_service_set_camera_light(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test service to set the outdoor camera light mode.""" """Test service to set the outdoor camera light mode."""
with selected_platforms(["camera"]): with selected_platforms(["camera"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -324,7 +340,9 @@ async def test_service_set_camera_light(hass, config_entry, netatmo_auth):
mock_set_state.assert_called_once_with(expected_data) mock_set_state.assert_called_once_with(expected_data)
async def test_service_set_camera_light_invalid_type(hass, config_entry, netatmo_auth): async def test_service_set_camera_light_invalid_type(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test service to set the indoor camera light mode.""" """Test service to set the indoor camera light mode."""
with selected_platforms(["camera"]): with selected_platforms(["camera"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -353,7 +371,7 @@ async def test_service_set_camera_light_invalid_type(hass, config_entry, netatmo
assert excinfo.value.args == ("NACamera <Hall> does not have a floodlight",) assert excinfo.value.args == ("NACamera <Hall> does not have a floodlight",)
async def test_camera_reconnect_webhook(hass, config_entry): async def test_camera_reconnect_webhook(hass: HomeAssistant, config_entry) -> None:
"""Test webhook event on camera reconnect.""" """Test webhook event on camera reconnect."""
fake_post_hits = 0 fake_post_hits = 0
@ -408,7 +426,9 @@ async def test_camera_reconnect_webhook(hass, config_entry):
assert fake_post_hits >= calls assert fake_post_hits >= calls
async def test_webhook_person_event(hass, config_entry, netatmo_auth): async def test_webhook_person_event(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test that person events are handled.""" """Test that person events are handled."""
with selected_platforms(["camera"]): with selected_platforms(["camera"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -445,7 +465,7 @@ async def test_webhook_person_event(hass, config_entry, netatmo_auth):
assert test_netatmo_event assert test_netatmo_event
async def test_setup_component_no_devices(hass, config_entry): async def test_setup_component_no_devices(hass: HomeAssistant, config_entry) -> None:
"""Test setup with no devices.""" """Test setup with no devices."""
fake_post_hits = 0 fake_post_hits = 0
@ -474,7 +494,9 @@ async def test_setup_component_no_devices(hass, config_entry):
assert fake_post_hits == 11 assert fake_post_hits == 11
async def test_camera_image_raises_exception(hass, config_entry, requests_mock): async def test_camera_image_raises_exception(
hass: HomeAssistant, config_entry, requests_mock: requests_mock.Mocker
) -> None:
"""Test setup with no devices.""" """Test setup with no devices."""
fake_post_hits = 0 fake_post_hits = 0

View file

@ -1,6 +1,8 @@
"""The tests for the Netatmo climate platform.""" """The tests for the Netatmo climate platform."""
from unittest.mock import patch from unittest.mock import patch
import pytest
from homeassistant.components.climate import ( from homeassistant.components.climate import (
ATTR_HVAC_MODE, ATTR_HVAC_MODE,
ATTR_PRESET_MODE, ATTR_PRESET_MODE,
@ -20,11 +22,14 @@ from homeassistant.components.netatmo.const import (
SERVICE_SET_SCHEDULE, SERVICE_SET_SCHEDULE,
) )
from homeassistant.const import ATTR_ENTITY_ID, ATTR_TEMPERATURE, CONF_WEBHOOK_ID from homeassistant.const import ATTR_ENTITY_ID, ATTR_TEMPERATURE, CONF_WEBHOOK_ID
from homeassistant.core import HomeAssistant
from .common import selected_platforms, simulate_webhook from .common import selected_platforms, simulate_webhook
async def test_webhook_event_handling_thermostats(hass, config_entry, netatmo_auth): async def test_webhook_event_handling_thermostats(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test service and webhook event handling with thermostats.""" """Test service and webhook event handling with thermostats."""
with selected_platforms(["climate"]): with selected_platforms(["climate"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -197,8 +202,8 @@ async def test_webhook_event_handling_thermostats(hass, config_entry, netatmo_au
async def test_service_preset_mode_frost_guard_thermostat( async def test_service_preset_mode_frost_guard_thermostat(
hass, config_entry, netatmo_auth hass: HomeAssistant, config_entry, netatmo_auth
): ) -> None:
"""Test service with frost guard preset for thermostats.""" """Test service with frost guard preset for thermostats."""
with selected_platforms(["climate"]): with selected_platforms(["climate"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -269,7 +274,9 @@ async def test_service_preset_mode_frost_guard_thermostat(
) )
async def test_service_preset_modes_thermostat(hass, config_entry, netatmo_auth): async def test_service_preset_modes_thermostat(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test service with preset modes for thermostats.""" """Test service with preset modes for thermostats."""
with selected_platforms(["climate"]): with selected_platforms(["climate"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -347,7 +354,9 @@ async def test_service_preset_modes_thermostat(hass, config_entry, netatmo_auth)
assert hass.states.get(climate_entity_livingroom).attributes["temperature"] == 30 assert hass.states.get(climate_entity_livingroom).attributes["temperature"] == 30
async def test_webhook_event_handling_no_data(hass, config_entry, netatmo_auth): async def test_webhook_event_handling_no_data(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test service and webhook event handling with erroneous data.""" """Test service and webhook event handling with erroneous data."""
with selected_platforms(["climate"]): with selected_platforms(["climate"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -396,7 +405,9 @@ async def test_webhook_event_handling_no_data(hass, config_entry, netatmo_auth):
await simulate_webhook(hass, webhook_id, response) await simulate_webhook(hass, webhook_id, response)
async def test_service_schedule_thermostats(hass, config_entry, caplog, netatmo_auth): async def test_service_schedule_thermostats(
hass: HomeAssistant, config_entry, caplog: pytest.LogCaptureFixture, netatmo_auth
) -> None:
"""Test service for selecting Netatmo schedule with thermostats.""" """Test service for selecting Netatmo schedule with thermostats."""
with selected_platforms(["climate"]): with selected_platforms(["climate"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -448,8 +459,8 @@ async def test_service_schedule_thermostats(hass, config_entry, caplog, netatmo_
async def test_service_preset_mode_already_boost_valves( async def test_service_preset_mode_already_boost_valves(
hass, config_entry, netatmo_auth hass: HomeAssistant, config_entry, netatmo_auth
): ) -> None:
"""Test service with boost preset for valves when already in boost mode.""" """Test service with boost preset for valves when already in boost mode."""
with selected_platforms(["climate"]): with selected_platforms(["climate"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -527,7 +538,9 @@ async def test_service_preset_mode_already_boost_valves(
assert hass.states.get(climate_entity_entrada).attributes["temperature"] == 30 assert hass.states.get(climate_entity_entrada).attributes["temperature"] == 30
async def test_service_preset_mode_boost_valves(hass, config_entry, netatmo_auth): async def test_service_preset_mode_boost_valves(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test service with boost preset for valves.""" """Test service with boost preset for valves."""
with selected_platforms(["climate"]): with selected_platforms(["climate"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -577,7 +590,9 @@ async def test_service_preset_mode_boost_valves(hass, config_entry, netatmo_auth
assert hass.states.get(climate_entity_entrada).attributes["temperature"] == 30 assert hass.states.get(climate_entity_entrada).attributes["temperature"] == 30
async def test_service_preset_mode_invalid(hass, config_entry, caplog, netatmo_auth): async def test_service_preset_mode_invalid(
hass: HomeAssistant, config_entry, caplog: pytest.LogCaptureFixture, netatmo_auth
) -> None:
"""Test service with invalid preset.""" """Test service with invalid preset."""
with selected_platforms(["climate"]): with selected_platforms(["climate"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -595,7 +610,9 @@ async def test_service_preset_mode_invalid(hass, config_entry, caplog, netatmo_a
assert "Preset mode 'invalid' not available" in caplog.text assert "Preset mode 'invalid' not available" in caplog.text
async def test_valves_service_turn_off(hass, config_entry, netatmo_auth): async def test_valves_service_turn_off(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test service turn off for valves.""" """Test service turn off for valves."""
with selected_platforms(["climate"]): with selected_platforms(["climate"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -645,7 +662,9 @@ async def test_valves_service_turn_off(hass, config_entry, netatmo_auth):
assert hass.states.get(climate_entity_entrada).state == "off" assert hass.states.get(climate_entity_entrada).state == "off"
async def test_valves_service_turn_on(hass, config_entry, netatmo_auth): async def test_valves_service_turn_on(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test service turn on for valves.""" """Test service turn on for valves."""
with selected_platforms(["climate"]): with selected_platforms(["climate"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -690,7 +709,9 @@ async def test_valves_service_turn_on(hass, config_entry, netatmo_auth):
assert hass.states.get(climate_entity_entrada).state == "auto" assert hass.states.get(climate_entity_entrada).state == "auto"
async def test_webhook_home_id_mismatch(hass, config_entry, netatmo_auth): async def test_webhook_home_id_mismatch(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test service turn on for valves.""" """Test service turn on for valves."""
with selected_platforms(["climate"]): with selected_platforms(["climate"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -728,7 +749,9 @@ async def test_webhook_home_id_mismatch(hass, config_entry, netatmo_auth):
assert hass.states.get(climate_entity_entrada).state == "auto" assert hass.states.get(climate_entity_entrada).state == "auto"
async def test_webhook_set_point(hass, config_entry, netatmo_auth): async def test_webhook_set_point(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test service turn on for valves.""" """Test service turn on for valves."""
with selected_platforms(["climate"]): with selected_platforms(["climate"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)

View file

@ -18,6 +18,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 = "1234" CLIENT_ID = "1234"
CLIENT_SECRET = "5678" CLIENT_SECRET = "5678"
@ -56,8 +58,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,
@ -228,8 +233,11 @@ async def test_option_flow_wrong_coordinates(hass: HomeAssistant) -> None:
async def test_reauth( async def test_reauth(
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:
"""Test initialization of the reauth flow.""" """Test initialization of the reauth flow."""
assert await setup.async_setup_component( assert await setup.async_setup_component(
hass, hass,

View file

@ -10,11 +10,14 @@ from homeassistant.components.cover import (
SERVICE_STOP_COVER, SERVICE_STOP_COVER,
) )
from homeassistant.const import ATTR_ENTITY_ID from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from .common import selected_platforms from .common import selected_platforms
async def test_cover_setup_and_services(hass, config_entry, netatmo_auth): async def test_cover_setup_and_services(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test setup and services.""" """Test setup and services."""
with selected_platforms(["cover"]): with selected_platforms(["cover"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)

View file

@ -12,7 +12,8 @@ from homeassistant.components.netatmo.const import (
) )
from homeassistant.components.netatmo.device_trigger import SUBTYPES from homeassistant.components.netatmo.device_trigger import SUBTYPES
from homeassistant.const import ATTR_DEVICE_ID from homeassistant.const import ATTR_DEVICE_ID
from homeassistant.helpers import device_registry as dr from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import ( from tests.common import (
@ -40,8 +41,13 @@ def calls(hass):
], ],
) )
async def test_get_triggers( async def test_get_triggers(
hass, device_registry, entity_registry, platform, device_type, event_types hass: HomeAssistant,
): device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
platform,
device_type,
event_types,
) -> None:
"""Test we get the expected triggers from a netatmo devices.""" """Test we get the expected triggers from a netatmo devices."""
config_entry = MockConfigEntry(domain=NETATMO_DOMAIN, data={}) config_entry = MockConfigEntry(domain=NETATMO_DOMAIN, data={})
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
@ -105,8 +111,14 @@ async def test_get_triggers(
], ],
) )
async def test_if_fires_on_event( async def test_if_fires_on_event(
hass, calls, device_registry, entity_registry, platform, camera_type, event_type hass: HomeAssistant,
): calls,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
platform,
camera_type,
event_type,
) -> None:
"""Test for event triggers firing.""" """Test for event triggers firing."""
mac_address = "12:34:56:AB:CD:EF" mac_address = "12:34:56:AB:CD:EF"
connection = (dr.CONNECTION_NETWORK_MAC, mac_address) connection = (dr.CONNECTION_NETWORK_MAC, mac_address)
@ -180,15 +192,15 @@ async def test_if_fires_on_event(
], ],
) )
async def test_if_fires_on_event_with_subtype( async def test_if_fires_on_event_with_subtype(
hass, hass: HomeAssistant,
calls, calls,
device_registry, device_registry: dr.DeviceRegistry,
entity_registry, entity_registry: er.EntityRegistry,
platform, platform,
camera_type, camera_type,
event_type, event_type,
sub_type, sub_type,
): ) -> None:
"""Test for event triggers firing.""" """Test for event triggers firing."""
mac_address = "12:34:56:AB:CD:EF" mac_address = "12:34:56:AB:CD:EF"
connection = (dr.CONNECTION_NETWORK_MAC, mac_address) connection = (dr.CONNECTION_NETWORK_MAC, mac_address)
@ -258,8 +270,13 @@ async def test_if_fires_on_event_with_subtype(
[("climate", "NAPlug", trigger) for trigger in CLIMATE_TRIGGERS], [("climate", "NAPlug", trigger) for trigger in CLIMATE_TRIGGERS],
) )
async def test_if_invalid_device( async def test_if_invalid_device(
hass, device_registry, entity_registry, platform, device_type, event_type hass: HomeAssistant,
): device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
platform,
device_type,
event_type,
) -> None:
"""Test for event triggers firing.""" """Test for event triggers firing."""
mac_address = "12:34:56:AB:CD:EF" mac_address = "12:34:56:AB:CD:EF"
connection = (dr.CONNECTION_NETWORK_MAC, mac_address) connection = (dr.CONNECTION_NETWORK_MAC, mac_address)

View file

@ -2,14 +2,18 @@
from unittest.mock import AsyncMock, patch from unittest.mock import AsyncMock, patch
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 .common import fake_post_request from .common import fake_post_request
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, hass_client, config_entry): async def test_entry_diagnostics(
hass: HomeAssistant, hass_client: ClientSessionGenerator, config_entry
) -> None:
"""Test config entry diagnostics.""" """Test config entry diagnostics."""
with patch( with patch(
"homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth", "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth",

View file

@ -5,6 +5,7 @@ from unittest.mock import AsyncMock, patch
import aiohttp import aiohttp
from pyatmo.const import ALL_SCOPES from pyatmo.const import ALL_SCOPES
import pytest
from homeassistant import config_entries from homeassistant import config_entries
from homeassistant.components.netatmo import DOMAIN from homeassistant.components.netatmo import DOMAIN
@ -49,7 +50,7 @@ FAKE_WEBHOOK = {
} }
async def test_setup_component(hass, config_entry): async def test_setup_component(hass: HomeAssistant, config_entry) -> None:
"""Test setup and teardown of the netatmo component.""" """Test setup and teardown of the netatmo component."""
with patch( with patch(
"homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth", "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth",
@ -81,7 +82,7 @@ async def test_setup_component(hass, config_entry):
assert not hass.config_entries.async_entries(DOMAIN) assert not hass.config_entries.async_entries(DOMAIN)
async def test_setup_component_with_config(hass, config_entry): async def test_setup_component_with_config(hass: HomeAssistant, config_entry) -> None:
"""Test setup of the netatmo component with dev account.""" """Test setup of the netatmo component with dev account."""
fake_post_hits = 0 fake_post_hits = 0
@ -118,7 +119,9 @@ async def test_setup_component_with_config(hass, config_entry):
assert len(hass.states.async_all()) > 0 assert len(hass.states.async_all()) > 0
async def test_setup_component_with_webhook(hass, config_entry, netatmo_auth): async def test_setup_component_with_webhook(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test setup and teardown of the netatmo component with webhook registration.""" """Test setup and teardown of the netatmo component with webhook registration."""
with selected_platforms(["camera", "climate", "light", "sensor"]): with selected_platforms(["camera", "climate", "light", "sensor"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -147,7 +150,9 @@ async def test_setup_component_with_webhook(hass, config_entry, netatmo_auth):
assert len(hass.config_entries.async_entries(DOMAIN)) == 0 assert len(hass.config_entries.async_entries(DOMAIN)) == 0
async def test_setup_without_https(hass, config_entry, caplog): async def test_setup_without_https(
hass: HomeAssistant, config_entry, caplog: pytest.LogCaptureFixture
) -> None:
"""Test if set up with cloud link and without https.""" """Test if set up with cloud link and without https."""
hass.config.components.add("cloud") hass.config.components.add("cloud")
with patch( with patch(
@ -173,7 +178,7 @@ async def test_setup_without_https(hass, config_entry, caplog):
assert "https and port 443 is required to register the webhook" in caplog.text assert "https and port 443 is required to register the webhook" in caplog.text
async def test_setup_with_cloud(hass, config_entry): async def test_setup_with_cloud(hass: HomeAssistant, config_entry) -> None:
"""Test if set up with active cloud subscription.""" """Test if set up with active cloud subscription."""
await mock_cloud(hass) await mock_cloud(hass)
await hass.async_block_till_done() await hass.async_block_till_done()
@ -287,7 +292,7 @@ async def test_setup_with_cloudhook(hass: HomeAssistant) -> None:
assert not hass.config_entries.async_entries(DOMAIN) assert not hass.config_entries.async_entries(DOMAIN)
async def test_setup_component_with_delay(hass, config_entry): async def test_setup_component_with_delay(hass: HomeAssistant, config_entry) -> None:
"""Test setup of the netatmo component with delayed startup.""" """Test setup of the netatmo component with delayed startup."""
hass.state = CoreState.not_running hass.state = CoreState.not_running
@ -392,7 +397,7 @@ async def test_setup_component_invalid_token_scope(hass: HomeAssistant) -> None:
await hass.config_entries.async_remove(config_entry.entry_id) await hass.config_entries.async_remove(config_entry.entry_id)
async def test_setup_component_invalid_token(hass, config_entry): async def test_setup_component_invalid_token(hass: HomeAssistant, config_entry) -> None:
"""Test handling of invalid token.""" """Test handling of invalid token."""
async def fake_ensure_valid_token(*args, **kwargs): async def fake_ensure_valid_token(*args, **kwargs):

View file

@ -8,13 +8,16 @@ from homeassistant.components.light import (
) )
from homeassistant.components.netatmo import DOMAIN from homeassistant.components.netatmo import DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, CONF_WEBHOOK_ID from homeassistant.const import ATTR_ENTITY_ID, CONF_WEBHOOK_ID
from homeassistant.core import HomeAssistant
from .common import FAKE_WEBHOOK_ACTIVATION, selected_platforms, simulate_webhook from .common import FAKE_WEBHOOK_ACTIVATION, selected_platforms, simulate_webhook
from tests.test_util.aiohttp import AiohttpClientMockResponse from tests.test_util.aiohttp import AiohttpClientMockResponse
async def test_camera_light_setup_and_services(hass, config_entry, netatmo_auth): async def test_camera_light_setup_and_services(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test camera ligiht setup and services.""" """Test camera ligiht setup and services."""
with selected_platforms(["light"]): with selected_platforms(["light"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -79,7 +82,7 @@ async def test_camera_light_setup_and_services(hass, config_entry, netatmo_auth)
) )
async def test_setup_component_no_devices(hass, config_entry): async def test_setup_component_no_devices(hass: HomeAssistant, config_entry) -> None:
"""Test setup with no devices.""" """Test setup with no devices."""
fake_post_hits = 0 fake_post_hits = 0
@ -123,7 +126,9 @@ async def test_setup_component_no_devices(hass, config_entry):
assert len(hass.states.async_all()) == 0 assert len(hass.states.async_all()) == 0
async def test_light_setup_and_services(hass, config_entry, netatmo_auth): async def test_light_setup_and_services(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test setup and services.""" """Test setup and services."""
with selected_platforms(["light"]): with selected_platforms(["light"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)

View file

@ -1,17 +1,22 @@
"""The tests for the Netatmo climate platform.""" """The tests for the Netatmo climate platform."""
from unittest.mock import patch from unittest.mock import patch
import pytest
from homeassistant.components.select import ( from homeassistant.components.select import (
ATTR_OPTION, ATTR_OPTION,
ATTR_OPTIONS, ATTR_OPTIONS,
DOMAIN as SELECT_DOMAIN, DOMAIN as SELECT_DOMAIN,
) )
from homeassistant.const import ATTR_ENTITY_ID, CONF_WEBHOOK_ID, SERVICE_SELECT_OPTION from homeassistant.const import ATTR_ENTITY_ID, CONF_WEBHOOK_ID, SERVICE_SELECT_OPTION
from homeassistant.core import HomeAssistant
from .common import selected_platforms, simulate_webhook from .common import selected_platforms, simulate_webhook
async def test_select_schedule_thermostats(hass, config_entry, caplog, netatmo_auth): async def test_select_schedule_thermostats(
hass: HomeAssistant, config_entry, caplog: pytest.LogCaptureFixture, netatmo_auth
) -> None:
"""Test service for selecting Netatmo schedule with thermostats.""" """Test service for selecting Netatmo schedule with thermostats."""
with selected_platforms(["climate", "select"]): with selected_platforms(["climate", "select"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)

View file

@ -4,12 +4,13 @@ from unittest.mock import patch
import pytest import pytest
from homeassistant.components.netatmo import sensor from homeassistant.components.netatmo import sensor
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from .common import TEST_TIME, selected_platforms from .common import TEST_TIME, selected_platforms
async def test_weather_sensor(hass, config_entry, netatmo_auth): async def test_weather_sensor(hass: HomeAssistant, config_entry, netatmo_auth) -> None:
"""Test weather sensor setup.""" """Test weather sensor setup."""
with patch("time.time", return_value=TEST_TIME), selected_platforms(["sensor"]): with patch("time.time", return_value=TEST_TIME), selected_platforms(["sensor"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -24,7 +25,9 @@ async def test_weather_sensor(hass, config_entry, netatmo_auth):
assert hass.states.get(f"{prefix}pressure").state == "1014.5" assert hass.states.get(f"{prefix}pressure").state == "1014.5"
async def test_public_weather_sensor(hass, config_entry, netatmo_auth): async def test_public_weather_sensor(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test public weather sensor setup.""" """Test public weather sensor setup."""
with patch("time.time", return_value=TEST_TIME), selected_platforms(["sensor"]): with patch("time.time", return_value=TEST_TIME), selected_platforms(["sensor"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
@ -78,7 +81,7 @@ async def test_public_weather_sensor(hass, config_entry, netatmo_auth):
"strength, expected", "strength, expected",
[(50, "Full"), (60, "High"), (80, "Medium"), (90, "Low")], [(50, "Full"), (60, "High"), (80, "Medium"), (90, "Low")],
) )
async def test_process_wifi(strength, expected): async def test_process_wifi(strength, expected) -> None:
"""Test wifi strength translation.""" """Test wifi strength translation."""
assert sensor.process_wifi(strength) == expected assert sensor.process_wifi(strength) == expected
@ -87,7 +90,7 @@ async def test_process_wifi(strength, expected):
"strength, expected", "strength, expected",
[(50, "Full"), (70, "High"), (80, "Medium"), (90, "Low")], [(50, "Full"), (70, "High"), (80, "Medium"), (90, "Low")],
) )
async def test_process_rf(strength, expected): async def test_process_rf(strength, expected) -> None:
"""Test radio strength translation.""" """Test radio strength translation."""
assert sensor.process_rf(strength) == expected assert sensor.process_rf(strength) == expected
@ -96,7 +99,7 @@ async def test_process_rf(strength, expected):
"health, expected", "health, expected",
[(4, "Unhealthy"), (3, "Poor"), (2, "Fair"), (1, "Fine"), (0, "Healthy")], [(4, "Unhealthy"), (3, "Poor"), (2, "Fair"), (1, "Fine"), (0, "Healthy")],
) )
async def test_process_health(health, expected): async def test_process_health(health, expected) -> None:
"""Test health index translation.""" """Test health index translation."""
assert sensor.process_health(health) == expected assert sensor.process_health(health) == expected
@ -167,8 +170,8 @@ async def test_process_health(health, expected):
], ],
) )
async def test_weather_sensor_enabling( async def test_weather_sensor_enabling(
hass, config_entry, uid, name, expected, netatmo_auth hass: HomeAssistant, config_entry, uid, name, expected, netatmo_auth
): ) -> None:
"""Test enabling of by default disabled sensors.""" """Test enabling of by default disabled sensors."""
with patch("time.time", return_value=TEST_TIME), selected_platforms(["sensor"]): with patch("time.time", return_value=TEST_TIME), selected_platforms(["sensor"]):
states_before = len(hass.states.async_all()) states_before = len(hass.states.async_all())
@ -190,7 +193,9 @@ async def test_weather_sensor_enabling(
assert hass.states.get(f"sensor.{name}").state == expected assert hass.states.get(f"sensor.{name}").state == expected
async def test_climate_battery_sensor(hass, config_entry, netatmo_auth): async def test_climate_battery_sensor(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test climate device battery sensor.""" """Test climate device battery sensor."""
with patch("time.time", return_value=TEST_TIME), selected_platforms( with patch("time.time", return_value=TEST_TIME), selected_platforms(
["sensor", "climate"] ["sensor", "climate"]

View file

@ -7,11 +7,14 @@ from homeassistant.components.switch import (
SERVICE_TURN_ON, SERVICE_TURN_ON,
) )
from homeassistant.const import ATTR_ENTITY_ID from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from .common import selected_platforms from .common import selected_platforms
async def test_switch_setup_and_services(hass, config_entry, netatmo_auth): async def test_switch_setup_and_services(
hass: HomeAssistant, config_entry, netatmo_auth
) -> None:
"""Test setup and services.""" """Test setup and services."""
with selected_platforms(["switch"]): with selected_platforms(["switch"]):
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)

View file

@ -111,7 +111,7 @@ def mock_controller_service_failed():
yield service_mock yield service_mock
async def test_user(hass, service): async def test_user(hass: HomeAssistant, service) -> None:
"""Test user step.""" """Test user step."""
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}
@ -138,7 +138,7 @@ async def test_user(hass, service):
assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_PASSWORD] == PASSWORD
async def test_user_connect_error(hass, service_failed): async def test_user_connect_error(hass: HomeAssistant, service_failed) -> None:
"""Test user step with connection failure.""" """Test user step with connection failure."""
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}
@ -160,7 +160,7 @@ async def test_user_connect_error(hass, service_failed):
assert result["errors"] == {"base": "config"} assert result["errors"] == {"base": "config"}
async def test_user_incomplete_info(hass, service_incomplete): async def test_user_incomplete_info(hass: HomeAssistant, service_incomplete) -> None:
"""Test user step with incomplete device info.""" """Test user step with incomplete device info."""
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}
@ -187,7 +187,7 @@ async def test_user_incomplete_info(hass, service_incomplete):
assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_PASSWORD] == PASSWORD
async def test_abort_if_already_setup(hass, service): async def test_abort_if_already_setup(hass: HomeAssistant, service) -> None:
"""Test we abort if the router is already setup.""" """Test we abort if the router is already setup."""
MockConfigEntry( MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,
@ -281,7 +281,7 @@ async def test_ssdp_ipv6(hass: HomeAssistant) -> None:
assert result["reason"] == "not_ipv4_address" assert result["reason"] == "not_ipv4_address"
async def test_ssdp(hass, service): async def test_ssdp(hass: HomeAssistant, service) -> None:
"""Test ssdp step.""" """Test ssdp step."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,
@ -313,7 +313,7 @@ async def test_ssdp(hass, service):
assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_PASSWORD] == PASSWORD
async def test_ssdp_port_5555(hass, service_5555): async def test_ssdp_port_5555(hass: HomeAssistant, service_5555) -> None:
"""Test ssdp step with port 5555.""" """Test ssdp step with port 5555."""
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,
@ -345,7 +345,7 @@ async def test_ssdp_port_5555(hass, service_5555):
assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_PASSWORD] == PASSWORD
async def test_options_flow(hass, service): async def test_options_flow(hass: HomeAssistant, service) -> None:
"""Test specifying non default settings using options flow.""" """Test specifying non default settings using options flow."""
config_entry = MockConfigEntry( config_entry = MockConfigEntry(
domain=DOMAIN, domain=DOMAIN,

View file

@ -1,5 +1,6 @@
"""Test the Network Configuration.""" """Test the Network Configuration."""
from ipaddress import IPv4Address from ipaddress import IPv4Address
from typing import Any
from unittest.mock import MagicMock, Mock, patch from unittest.mock import MagicMock, Mock, patch
import ifaddr import ifaddr
@ -14,6 +15,7 @@ from homeassistant.components.network.const import (
STORAGE_KEY, STORAGE_KEY,
STORAGE_VERSION, STORAGE_VERSION,
) )
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -68,7 +70,9 @@ def _generate_mock_adapters():
return [mock_eth0, mock_lo0, mock_eth1, mock_vtun0] return [mock_eth0, mock_lo0, mock_eth1, mock_vtun0]
async def test_async_detect_interfaces_setting_non_loopback_route(hass, hass_storage): async def test_async_detect_interfaces_setting_non_loopback_route(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test without default interface config and the route returns a non-loopback address.""" """Test without default interface config and the route returns a non-loopback address."""
with patch( with patch(
"homeassistant.components.network.util.socket.socket", "homeassistant.components.network.util.socket.socket",
@ -130,7 +134,9 @@ async def test_async_detect_interfaces_setting_non_loopback_route(hass, hass_sto
] ]
async def test_async_detect_interfaces_setting_loopback_route(hass, hass_storage): async def test_async_detect_interfaces_setting_loopback_route(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test without default interface config and the route returns a loopback address.""" """Test without default interface config and the route returns a loopback address."""
with patch( with patch(
"homeassistant.components.network.util.socket.socket", "homeassistant.components.network.util.socket.socket",
@ -191,7 +197,9 @@ async def test_async_detect_interfaces_setting_loopback_route(hass, hass_storage
] ]
async def test_async_detect_interfaces_setting_empty_route(hass, hass_storage): async def test_async_detect_interfaces_setting_empty_route(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test without default interface config and the route returns nothing.""" """Test without default interface config and the route returns nothing."""
with patch( with patch(
"homeassistant.components.network.util.socket.socket", "homeassistant.components.network.util.socket.socket",
@ -252,7 +260,9 @@ async def test_async_detect_interfaces_setting_empty_route(hass, hass_storage):
] ]
async def test_async_detect_interfaces_setting_exception(hass, hass_storage): async def test_async_detect_interfaces_setting_exception(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test without default interface config and the route throws an exception.""" """Test without default interface config and the route throws an exception."""
with patch( with patch(
"homeassistant.components.network.util.socket.socket", "homeassistant.components.network.util.socket.socket",
@ -313,7 +323,9 @@ async def test_async_detect_interfaces_setting_exception(hass, hass_storage):
] ]
async def test_interfaces_configured_from_storage(hass, hass_storage): async def test_interfaces_configured_from_storage(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test settings from storage are preferred over auto configure.""" """Test settings from storage are preferred over auto configure."""
hass_storage[STORAGE_KEY] = { hass_storage[STORAGE_KEY] = {
"version": STORAGE_VERSION, "version": STORAGE_VERSION,
@ -381,8 +393,8 @@ async def test_interfaces_configured_from_storage(hass, hass_storage):
async def test_interfaces_configured_from_storage_websocket_update( async def test_interfaces_configured_from_storage_websocket_update(
hass, hass_ws_client, hass_storage hass: HomeAssistant, hass_ws_client, hass_storage: dict[str, Any]
): ) -> None:
"""Test settings from storage can be updated via websocket api.""" """Test settings from storage can be updated via websocket api."""
hass_storage[STORAGE_KEY] = { hass_storage[STORAGE_KEY] = {
"version": STORAGE_VERSION, "version": STORAGE_VERSION,
@ -510,7 +522,9 @@ async def test_interfaces_configured_from_storage_websocket_update(
] ]
async def test_async_get_source_ip_matching_interface(hass, hass_storage): async def test_async_get_source_ip_matching_interface(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test getting the source ip address with interface matching.""" """Test getting the source ip address with interface matching."""
hass_storage[STORAGE_KEY] = { hass_storage[STORAGE_KEY] = {
"version": STORAGE_VERSION, "version": STORAGE_VERSION,
@ -531,7 +545,9 @@ async def test_async_get_source_ip_matching_interface(hass, hass_storage):
assert await network.async_get_source_ip(hass, MDNS_TARGET_IP) == "192.168.1.5" assert await network.async_get_source_ip(hass, MDNS_TARGET_IP) == "192.168.1.5"
async def test_async_get_source_ip_interface_not_match(hass, hass_storage): async def test_async_get_source_ip_interface_not_match(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test getting the source ip address with interface does not match.""" """Test getting the source ip address with interface does not match."""
hass_storage[STORAGE_KEY] = { hass_storage[STORAGE_KEY] = {
"version": STORAGE_VERSION, "version": STORAGE_VERSION,
@ -552,7 +568,9 @@ async def test_async_get_source_ip_interface_not_match(hass, hass_storage):
assert await network.async_get_source_ip(hass, MDNS_TARGET_IP) == "169.254.3.2" assert await network.async_get_source_ip(hass, MDNS_TARGET_IP) == "169.254.3.2"
async def test_async_get_source_ip_cannot_determine_target(hass, hass_storage): async def test_async_get_source_ip_cannot_determine_target(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test getting the source ip address when getsockname fails.""" """Test getting the source ip address when getsockname fails."""
hass_storage[STORAGE_KEY] = { hass_storage[STORAGE_KEY] = {
"version": STORAGE_VERSION, "version": STORAGE_VERSION,
@ -573,7 +591,9 @@ async def test_async_get_source_ip_cannot_determine_target(hass, hass_storage):
assert await network.async_get_source_ip(hass, MDNS_TARGET_IP) == "192.168.1.5" assert await network.async_get_source_ip(hass, MDNS_TARGET_IP) == "192.168.1.5"
async def test_async_get_ipv4_broadcast_addresses_default(hass, hass_storage): async def test_async_get_ipv4_broadcast_addresses_default(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test getting ipv4 broadcast addresses when only the default address is enabled.""" """Test getting ipv4 broadcast addresses when only the default address is enabled."""
hass_storage[STORAGE_KEY] = { hass_storage[STORAGE_KEY] = {
"version": STORAGE_VERSION, "version": STORAGE_VERSION,
@ -596,7 +616,9 @@ async def test_async_get_ipv4_broadcast_addresses_default(hass, hass_storage):
} }
async def test_async_get_ipv4_broadcast_addresses_multiple(hass, hass_storage): async def test_async_get_ipv4_broadcast_addresses_multiple(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test getting ipv4 broadcast addresses when multiple adapters are enabled.""" """Test getting ipv4 broadcast addresses when multiple adapters are enabled."""
hass_storage[STORAGE_KEY] = { hass_storage[STORAGE_KEY] = {
"version": STORAGE_VERSION, "version": STORAGE_VERSION,
@ -621,7 +643,9 @@ async def test_async_get_ipv4_broadcast_addresses_multiple(hass, hass_storage):
} }
async def test_async_get_source_ip_no_enabled_addresses(hass, hass_storage, caplog): async def test_async_get_source_ip_no_enabled_addresses(
hass: HomeAssistant, hass_storage: dict[str, Any], caplog: pytest.LogCaptureFixture
) -> None:
"""Test getting the source ip address when all adapters are disabled.""" """Test getting the source ip address when all adapters are disabled."""
hass_storage[STORAGE_KEY] = { hass_storage[STORAGE_KEY] = {
"version": STORAGE_VERSION, "version": STORAGE_VERSION,
@ -645,8 +669,8 @@ async def test_async_get_source_ip_no_enabled_addresses(hass, hass_storage, capl
async def test_async_get_source_ip_cannot_be_determined_and_no_enabled_addresses( async def test_async_get_source_ip_cannot_be_determined_and_no_enabled_addresses(
hass, hass_storage, caplog hass: HomeAssistant, hass_storage: dict[str, Any], caplog: pytest.LogCaptureFixture
): ) -> None:
"""Test getting the source ip address when all adapters are disabled and getting it fails.""" """Test getting the source ip address when all adapters are disabled and getting it fails."""
hass_storage[STORAGE_KEY] = { hass_storage[STORAGE_KEY] = {
"version": STORAGE_VERSION, "version": STORAGE_VERSION,
@ -667,7 +691,9 @@ async def test_async_get_source_ip_cannot_be_determined_and_no_enabled_addresses
await network.async_get_source_ip(hass, MDNS_TARGET_IP) await network.async_get_source_ip(hass, MDNS_TARGET_IP)
async def test_async_get_source_ip_no_ip_loopback(hass, hass_storage, caplog): async def test_async_get_source_ip_no_ip_loopback(
hass: HomeAssistant, hass_storage: dict[str, Any], caplog: pytest.LogCaptureFixture
) -> None:
"""Test getting the source ip address when all adapters are disabled no target is specified.""" """Test getting the source ip address when all adapters are disabled no target is specified."""
hass_storage[STORAGE_KEY] = { hass_storage[STORAGE_KEY] = {
"version": STORAGE_VERSION, "version": STORAGE_VERSION,

View file

@ -13,7 +13,7 @@ from homeassistant.core import HomeAssistant
@pytest.mark.parametrize("brand", [BRAND_ASAIR, BRAND_NEXIA]) @pytest.mark.parametrize("brand", [BRAND_ASAIR, BRAND_NEXIA])
async def test_form(hass, brand): async def test_form(hass: HomeAssistant, brand) -> 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(

View file

@ -6,6 +6,7 @@ import pytest
import homeassistant.components.nextbus.sensor as nextbus import homeassistant.components.nextbus.sensor as nextbus
import homeassistant.components.sensor as sensor import homeassistant.components.sensor as sensor
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
@ -87,17 +88,23 @@ def mock_nextbus_lists(mock_nextbus):
} }
async def test_valid_config(hass, mock_nextbus, mock_nextbus_lists): async def test_valid_config(
hass: HomeAssistant, mock_nextbus, mock_nextbus_lists
) -> None:
"""Test that sensor is set up properly with valid config.""" """Test that sensor is set up properly with valid config."""
await assert_setup_sensor(hass, CONFIG_BASIC) await assert_setup_sensor(hass, CONFIG_BASIC)
async def test_invalid_config(hass, mock_nextbus, mock_nextbus_lists): async def test_invalid_config(
hass: HomeAssistant, mock_nextbus, mock_nextbus_lists
) -> None:
"""Checks that component is not setup when missing information.""" """Checks that component is not setup when missing information."""
await assert_setup_sensor(hass, CONFIG_INVALID_MISSING, count=0) await assert_setup_sensor(hass, CONFIG_INVALID_MISSING, count=0)
async def test_validate_tags(hass, mock_nextbus, mock_nextbus_lists): async def test_validate_tags(
hass: HomeAssistant, mock_nextbus, mock_nextbus_lists
) -> None:
"""Test that additional validation against the API is successful.""" """Test that additional validation against the API is successful."""
# with self.subTest('Valid everything'): # with self.subTest('Valid everything'):
assert nextbus.validate_tags(mock_nextbus(), VALID_AGENCY, VALID_ROUTE, VALID_STOP) assert nextbus.validate_tags(mock_nextbus(), VALID_AGENCY, VALID_ROUTE, VALID_STOP)
@ -114,8 +121,8 @@ async def test_validate_tags(hass, mock_nextbus, mock_nextbus_lists):
async def test_verify_valid_state( async def test_verify_valid_state(
hass, mock_nextbus, mock_nextbus_lists, mock_nextbus_predictions hass: HomeAssistant, mock_nextbus, mock_nextbus_lists, mock_nextbus_predictions
): ) -> None:
"""Verify all attributes are set from a valid response.""" """Verify all attributes are set from a valid response."""
await assert_setup_sensor(hass, CONFIG_BASIC) await assert_setup_sensor(hass, CONFIG_BASIC)
mock_nextbus_predictions.assert_called_once_with( mock_nextbus_predictions.assert_called_once_with(
@ -133,8 +140,8 @@ async def test_verify_valid_state(
async def test_message_dict( async def test_message_dict(
hass, mock_nextbus, mock_nextbus_lists, mock_nextbus_predictions hass: HomeAssistant, mock_nextbus, mock_nextbus_lists, mock_nextbus_predictions
): ) -> None:
"""Verify that a single dict message is rendered correctly.""" """Verify that a single dict message is rendered correctly."""
mock_nextbus_predictions.return_value = { mock_nextbus_predictions.return_value = {
"predictions": { "predictions": {
@ -161,8 +168,8 @@ async def test_message_dict(
async def test_message_list( async def test_message_list(
hass, mock_nextbus, mock_nextbus_lists, mock_nextbus_predictions hass: HomeAssistant, mock_nextbus, mock_nextbus_lists, mock_nextbus_predictions
): ) -> None:
"""Verify that a list of messages are rendered correctly.""" """Verify that a list of messages are rendered correctly."""
mock_nextbus_predictions.return_value = { mock_nextbus_predictions.return_value = {
"predictions": { "predictions": {
@ -189,8 +196,8 @@ async def test_message_list(
async def test_direction_list( async def test_direction_list(
hass, mock_nextbus, mock_nextbus_lists, mock_nextbus_predictions hass: HomeAssistant, mock_nextbus, mock_nextbus_lists, mock_nextbus_predictions
): ) -> None:
"""Verify that a list of messages are rendered correctly.""" """Verify that a list of messages are rendered correctly."""
mock_nextbus_predictions.return_value = { mock_nextbus_predictions.return_value = {
"predictions": { "predictions": {
@ -228,8 +235,8 @@ async def test_direction_list(
async def test_custom_name( async def test_custom_name(
hass, mock_nextbus, mock_nextbus_lists, mock_nextbus_predictions hass: HomeAssistant, mock_nextbus, mock_nextbus_lists, mock_nextbus_predictions
): ) -> None:
"""Verify that a custom name can be set via config.""" """Verify that a custom name can be set via config."""
config = deepcopy(CONFIG_BASIC) config = deepcopy(CONFIG_BASIC)
config["sensor"]["name"] = "Custom Name" config["sensor"]["name"] = "Custom Name"
@ -240,8 +247,8 @@ async def test_custom_name(
async def test_no_predictions( async def test_no_predictions(
hass, mock_nextbus, mock_nextbus_predictions, mock_nextbus_lists hass: HomeAssistant, mock_nextbus, mock_nextbus_predictions, mock_nextbus_lists
): ) -> None:
"""Verify there are no exceptions when no predictions are returned.""" """Verify there are no exceptions when no predictions are returned."""
mock_nextbus_predictions.return_value = {} mock_nextbus_predictions.return_value = {}
@ -253,8 +260,8 @@ async def test_no_predictions(
async def test_verify_no_upcoming( async def test_verify_no_upcoming(
hass, mock_nextbus, mock_nextbus_lists, mock_nextbus_predictions hass: HomeAssistant, mock_nextbus, mock_nextbus_lists, mock_nextbus_predictions
): ) -> None:
"""Verify attributes are set despite no upcoming times.""" """Verify attributes are set despite no upcoming times."""
mock_nextbus_predictions.return_value = { mock_nextbus_predictions.return_value = {
"predictions": { "predictions": {

View file

@ -1,5 +1,6 @@
"""The tests for notify services that change targets.""" """The tests for notify services that change targets."""
import asyncio import asyncio
from pathlib import Path
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
import pytest import pytest
@ -38,7 +39,7 @@ def mock_notify_platform(
return loaded_platform return loaded_platform
async def test_same_targets(hass: HomeAssistant): async def test_same_targets(hass: HomeAssistant) -> None:
"""Test not changing the targets in a notify service.""" """Test not changing the targets in a notify service."""
test = NotificationService(hass) test = NotificationService(hass)
await test.async_setup(hass, "notify", "test") await test.async_setup(hass, "notify", "test")
@ -53,7 +54,7 @@ async def test_same_targets(hass: HomeAssistant):
assert test.registered_targets == {"test_a": 1, "test_b": 2} assert test.registered_targets == {"test_a": 1, "test_b": 2}
async def test_change_targets(hass: HomeAssistant): async def test_change_targets(hass: HomeAssistant) -> None:
"""Test changing the targets in a notify service.""" """Test changing the targets in a notify service."""
test = NotificationService(hass) test = NotificationService(hass)
await test.async_setup(hass, "notify", "test") await test.async_setup(hass, "notify", "test")
@ -70,7 +71,7 @@ async def test_change_targets(hass: HomeAssistant):
assert test.registered_targets == {"test_a": 0} assert test.registered_targets == {"test_a": 0}
async def test_add_targets(hass: HomeAssistant): async def test_add_targets(hass: HomeAssistant) -> None:
"""Test adding the targets in a notify service.""" """Test adding the targets in a notify service."""
test = NotificationService(hass) test = NotificationService(hass)
await test.async_setup(hass, "notify", "test") await test.async_setup(hass, "notify", "test")
@ -87,7 +88,7 @@ async def test_add_targets(hass: HomeAssistant):
assert test.registered_targets == {"test_a": 1, "test_b": 2, "test_c": 3} assert test.registered_targets == {"test_a": 1, "test_b": 2, "test_c": 3}
async def test_remove_targets(hass: HomeAssistant): async def test_remove_targets(hass: HomeAssistant) -> None:
"""Test removing targets from the targets in a notify service.""" """Test removing targets from the targets in a notify service."""
test = NotificationService(hass) test = NotificationService(hass)
await test.async_setup(hass, "notify", "test") await test.async_setup(hass, "notify", "test")
@ -141,7 +142,9 @@ async def test_warn_template(
assert hass.states.get("persistent_notification.notification") is not None assert hass.states.get("persistent_notification.notification") is not None
async def test_invalid_platform(hass, caplog, tmp_path): async def test_invalid_platform(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, tmp_path: Path
) -> None:
"""Test service setup with an invalid platform.""" """Test service setup with an invalid platform."""
mock_notify_platform(hass, tmp_path, "testnotify1") mock_notify_platform(hass, tmp_path, "testnotify1")
# Setup the platform # Setup the platform
@ -164,7 +167,9 @@ async def test_invalid_platform(hass, caplog, tmp_path):
assert "Invalid notify platform" in caplog.text assert "Invalid notify platform" in caplog.text
async def test_invalid_service(hass, caplog, tmp_path): async def test_invalid_service(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, tmp_path: Path
) -> None:
"""Test service setup with an invalid service object or platform.""" """Test service setup with an invalid service object or platform."""
def get_service(hass, config, discovery_info=None): def get_service(hass, config, discovery_info=None):
@ -195,7 +200,9 @@ async def test_invalid_service(hass, caplog, tmp_path):
assert "Unknown notification service specified" in caplog.text assert "Unknown notification service specified" in caplog.text
async def test_platform_setup_with_error(hass, caplog, tmp_path): async def test_platform_setup_with_error(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, tmp_path: Path
) -> None:
"""Test service setup with an invalid setup.""" """Test service setup with an invalid setup."""
async def async_get_service(hass, config, discovery_info=None): async def async_get_service(hass, config, discovery_info=None):
@ -217,7 +224,9 @@ async def test_platform_setup_with_error(hass, caplog, tmp_path):
assert "Error setting up platform testnotify" in caplog.text assert "Error setting up platform testnotify" in caplog.text
async def test_reload_with_notify_builtin_platform_reload(hass, caplog, tmp_path): async def test_reload_with_notify_builtin_platform_reload(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, tmp_path: Path
) -> None:
"""Test reload using the notify platform reload method.""" """Test reload using the notify platform reload method."""
async def async_get_service(hass, config, discovery_info=None): async def async_get_service(hass, config, discovery_info=None):
@ -247,7 +256,9 @@ async def test_reload_with_notify_builtin_platform_reload(hass, caplog, tmp_path
assert hass.services.has_service(notify.DOMAIN, "testnotify_b") assert hass.services.has_service(notify.DOMAIN, "testnotify_b")
async def test_setup_platform_and_reload(hass, caplog, tmp_path): async def test_setup_platform_and_reload(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, tmp_path: Path
) -> None:
"""Test service setup and reload.""" """Test service setup and reload."""
get_service_called = Mock() get_service_called = Mock()
@ -335,7 +346,9 @@ async def test_setup_platform_and_reload(hass, caplog, tmp_path):
assert not hass.services.has_service(notify.DOMAIN, "testnotify2_d") assert not hass.services.has_service(notify.DOMAIN, "testnotify2_d")
async def test_setup_platform_before_notify_setup(hass, caplog, tmp_path): async def test_setup_platform_before_notify_setup(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, tmp_path: Path
) -> None:
"""Test trying to setup a platform before notify is setup.""" """Test trying to setup a platform before notify is setup."""
get_service_called = Mock() get_service_called = Mock()
@ -383,7 +396,9 @@ async def test_setup_platform_before_notify_setup(hass, caplog, tmp_path):
assert hass.services.has_service(notify.DOMAIN, "testnotify2_d") assert hass.services.has_service(notify.DOMAIN, "testnotify2_d")
async def test_setup_platform_after_notify_setup(hass, caplog, tmp_path): async def test_setup_platform_after_notify_setup(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, tmp_path: Path
) -> None:
"""Test trying to setup a platform after notify is setup.""" """Test trying to setup a platform after notify is setup."""
get_service_called = Mock() get_service_called = Mock()

View file

@ -5,7 +5,7 @@ from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
async def test_async_send_message(hass: HomeAssistant): async def test_async_send_message(hass: HomeAssistant) -> None:
"""Test sending a message to notify.persistent_notification service.""" """Test sending a message to notify.persistent_notification service."""
await async_setup_component(hass, pn.DOMAIN, {"core": {}}) await async_setup_component(hass, pn.DOMAIN, {"core": {}})
await async_setup_component(hass, notify.DOMAIN, {}) await async_setup_component(hass, notify.DOMAIN, {})