Enable Ruff PT012 (#113957)

This commit is contained in:
Sid 2024-06-08 17:59:08 +02:00 committed by GitHub
parent 915658daa1
commit 721b2c2ca8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
90 changed files with 341 additions and 429 deletions

View File

@ -767,7 +767,6 @@ ignore = [
"PLW2901", # Outer {outer_kind} variable {name} overwritten by inner {inner_kind} target
"PT004", # Fixture {fixture} does not return anything, add leading underscore
"PT011", # pytest.raises({exception}) is too broad, set the `match` parameter or use a more specific exception
"PT012", # `pytest.raises()` block should contain a single simple statement
"PT018", # Assertion should be broken down into multiple parts
"RUF001", # String contains ambiguous unicode character.
"RUF002", # Docstring contains ambiguous unicode character.

View File

@ -254,13 +254,14 @@ async def test_climate_async_failed_update(
) -> None:
"""Test climate change failure."""
mock_update.side_effect = ApiError
await add_mock_config(hass)
with pytest.raises(HomeAssistantError):
mock_update.side_effect = ApiError
await add_mock_config(hass)
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
{ATTR_ENTITY_ID: ["climate.myzone"], ATTR_TEMPERATURE: 25},
blocking=True,
)
mock_update.assert_called_once()
mock_update.assert_called_once()

View File

@ -882,7 +882,7 @@ async def test_direction_fan(hass: HomeAssistant) -> None:
payload={},
instance=None,
)
assert call.data
assert call.data
async def test_preset_mode_fan(
@ -1823,12 +1823,6 @@ async def test_media_player_seek_error(hass: HomeAssistant) -> None:
payload={"deltaPositionMilliseconds": 30000},
)
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa.Video"
assert msg["payload"]["type"] == "ACTION_NOT_PERMITTED_FOR_CONTENT"
@pytest.mark.freeze_time("2022-04-19 07:53:05")
async def test_alert(hass: HomeAssistant) -> None:
@ -3827,7 +3821,6 @@ async def test_disabled(hass: HomeAssistant) -> None:
await smart_home.async_handle_message(
hass, get_default_config(hass), request, enabled=False
)
await hass.async_block_till_done()
async def test_endpoint_good_health(hass: HomeAssistant) -> None:

View File

@ -373,7 +373,6 @@ async def test_lock_throws_exception_on_unknown_status_code(
data = {ATTR_ENTITY_ID: "lock.online_with_doorsense_name"}
with pytest.raises(ClientResponseError):
await hass.services.async_call(LOCK_DOMAIN, SERVICE_UNLOCK, data, blocking=True)
await hass.async_block_till_done()
async def test_one_lock_unknown_state(hass: HomeAssistant) -> None:

View File

@ -62,6 +62,8 @@ async def test_config_exceptions(
config_error: IntegrationError,
) -> None:
"""Test if the correct config error is raised when connecting to the api fails."""
config_entry.add_to_hass(hass)
with (
patch(
"homeassistant.components.blue_current.Client.validate_api_token",
@ -69,7 +71,6 @@ async def test_config_exceptions(
),
pytest.raises(config_error),
):
config_entry.add_to_hass(hass)
await async_setup_entry(hass, config_entry)

View File

@ -396,7 +396,6 @@ async def test_set_speed_belief_speed_api_error(hass: HomeAssistant) -> None:
{ATTR_ENTITY_ID: "fan.name_1", "speed": 100},
blocking=True,
)
await hass.async_block_till_done()
async def test_set_speed_belief_speed_100(hass: HomeAssistant) -> None:

View File

@ -341,7 +341,6 @@ async def test_light_set_brightness_belief_api_error(hass: HomeAssistant) -> Non
{ATTR_ENTITY_ID: "light.name_1", ATTR_BRIGHTNESS: 255},
blocking=True,
)
await hass.async_block_till_done()
async def test_fp_light_set_brightness_belief_full(hass: HomeAssistant) -> None:
@ -387,7 +386,6 @@ async def test_fp_light_set_brightness_belief_api_error(hass: HomeAssistant) ->
{ATTR_ENTITY_ID: "light.name_1", ATTR_BRIGHTNESS: 255},
blocking=True,
)
await hass.async_block_till_done()
async def test_light_set_brightness_belief_brightness_not_supported(
@ -408,7 +406,6 @@ async def test_light_set_brightness_belief_brightness_not_supported(
{ATTR_ENTITY_ID: "light.name_1", ATTR_BRIGHTNESS: 255},
blocking=True,
)
await hass.async_block_till_done()
async def test_light_set_brightness_belief_zero(hass: HomeAssistant) -> None:
@ -500,7 +497,6 @@ async def test_light_set_power_belief_api_error(hass: HomeAssistant) -> None:
{ATTR_ENTITY_ID: "light.name_1", ATTR_POWER_STATE: False},
blocking=True,
)
await hass.async_block_till_done()
async def test_fp_light_set_power_belief(hass: HomeAssistant) -> None:
@ -546,7 +542,6 @@ async def test_fp_light_set_power_belief_api_error(hass: HomeAssistant) -> None:
{ATTR_ENTITY_ID: "light.name_1", ATTR_POWER_STATE: False},
blocking=True,
)
await hass.async_block_till_done()
async def test_fp_light_set_brightness_belief_brightness_not_supported(
@ -567,7 +562,6 @@ async def test_fp_light_set_brightness_belief_brightness_not_supported(
{ATTR_ENTITY_ID: "light.name_1", ATTR_BRIGHTNESS: 255},
blocking=True,
)
await hass.async_block_till_done()
async def test_light_start_increasing_brightness(hass: HomeAssistant) -> None:
@ -608,7 +602,6 @@ async def test_light_start_increasing_brightness_missing_service(
{ATTR_ENTITY_ID: "light.name_1"},
blocking=True,
)
await hass.async_block_till_done()
async def test_light_start_decreasing_brightness(hass: HomeAssistant) -> None:
@ -652,7 +645,6 @@ async def test_light_start_decreasing_brightness_missing_service(
{ATTR_ENTITY_ID: "light.name_1"},
blocking=True,
)
await hass.async_block_till_done()
async def test_light_stop(hass: HomeAssistant) -> None:
@ -694,7 +686,6 @@ async def test_light_stop_missing_service(
{ATTR_ENTITY_ID: "light.name_1"},
blocking=True,
)
await hass.async_block_till_done()
async def test_turn_on_light(hass: HomeAssistant) -> None:

View File

@ -123,7 +123,6 @@ async def test_switch_set_power_belief_api_error(hass: HomeAssistant) -> None:
{ATTR_ENTITY_ID: "switch.name_1", ATTR_POWER_STATE: False},
blocking=True,
)
await hass.async_block_till_done()
async def test_update_reports_switch_is_on(hass: HomeAssistant) -> None:

View File

@ -140,7 +140,6 @@ async def test_integration_services_with_issue(hass: HomeAssistant, cfupdate) ->
{},
blocking=True,
)
await hass.async_block_till_done()
instance.update_dns_record.assert_not_called()

View File

@ -111,7 +111,6 @@ async def test_missing_url_and_path(hass: HomeAssistant, setup_integration) -> N
await hass.services.async_call(
DOMAIN, SERVICE_TURN_ON, service_data, blocking=True
)
await hass.async_block_till_done()
# check light is still off, unchanged due to bad parameters on service call
state = hass.states.get(LIGHT_ENTITY)

View File

@ -150,7 +150,6 @@ async def test_configure_service_with_faulty_field(
await hass.services.async_call(
DECONZ_DOMAIN, SERVICE_CONFIGURE_DEVICE, service_data=data
)
await hass.async_block_till_done()
async def test_configure_service_with_faulty_entity(

View File

@ -83,7 +83,7 @@ async def test_turn_off_image(hass: HomeAssistant) -> None:
with pytest.raises(HomeAssistantError) as error:
await async_get_image(hass, ENTITY_CAMERA)
assert error.args[0] == "Camera is off"
assert error.value.args[0] == "Camera is off"
async def test_turn_off_invalid_camera(hass: HomeAssistant) -> None:

View File

@ -189,7 +189,6 @@ async def test_turn_on_with_preset_mode_only(
{ATTR_ENTITY_ID: fan_entity_id, fan.ATTR_PRESET_MODE: "invalid"},
blocking=True,
)
await hass.async_block_till_done()
assert exc.value.translation_domain == fan.DOMAIN
assert exc.value.translation_key == "not_valid_preset_mode"
assert exc.value.translation_placeholders == {
@ -263,7 +262,6 @@ async def test_turn_on_with_preset_mode_and_speed(
{ATTR_ENTITY_ID: fan_entity_id, fan.ATTR_PRESET_MODE: "invalid"},
blocking=True,
)
await hass.async_block_till_done()
assert exc.value.translation_domain == fan.DOMAIN
assert exc.value.translation_key == "not_valid_preset_mode"
assert exc.value.translation_placeholders == {
@ -362,7 +360,6 @@ async def test_set_preset_mode_invalid(hass: HomeAssistant, fan_entity_id) -> No
{ATTR_ENTITY_ID: fan_entity_id, fan.ATTR_PRESET_MODE: "invalid"},
blocking=True,
)
await hass.async_block_till_done()
assert exc.value.translation_domain == fan.DOMAIN
assert exc.value.translation_key == "not_valid_preset_mode"
@ -373,7 +370,6 @@ async def test_set_preset_mode_invalid(hass: HomeAssistant, fan_entity_id) -> No
{ATTR_ENTITY_ID: fan_entity_id, fan.ATTR_PRESET_MODE: "invalid"},
blocking=True,
)
await hass.async_block_till_done()
assert exc.value.translation_domain == fan.DOMAIN
assert exc.value.translation_key == "not_valid_preset_mode"

View File

@ -106,7 +106,6 @@ async def test_button(
{ATTR_ENTITY_ID: state_key},
blocking=True,
)
await hass.async_block_till_done()
await hass.config_entries.async_unload(entry.entry_id)

View File

@ -514,7 +514,6 @@ async def test_zero_conf_malformed_serial_property(
type="mock_type",
),
)
await hass.async_block_till_done()
assert "serialnum" in str(ex.value)
result3 = await hass.config_entries.flow.async_configure(

View File

@ -629,12 +629,9 @@ async def test_send_tts_wrong_sample_rate(
wav_file.writeframes(bytes(_ONE_SECOND))
wav_bytes = wav_io.getvalue()
with (
patch(
"homeassistant.components.esphome.voice_assistant.tts.async_get_media_source_audio",
return_value=("wav", wav_bytes),
),
pytest.raises(ValueError),
with patch(
"homeassistant.components.esphome.voice_assistant.tts.async_get_media_source_audio",
return_value=("wav", wav_bytes),
):
voice_assistant_api_pipeline.started = True
voice_assistant_api_pipeline.transport = Mock(spec=asyncio.DatagramTransport)
@ -649,7 +646,8 @@ async def test_send_tts_wrong_sample_rate(
)
assert voice_assistant_api_pipeline._tts_task is not None
await voice_assistant_api_pipeline._tts_task # raises ValueError
with pytest.raises(ValueError):
await voice_assistant_api_pipeline._tts_task
async def test_send_tts_wrong_format(
@ -662,7 +660,6 @@ async def test_send_tts_wrong_format(
"homeassistant.components.esphome.voice_assistant.tts.async_get_media_source_audio",
return_value=("raw", bytes(1024)),
),
pytest.raises(ValueError),
):
voice_assistant_api_pipeline.started = True
voice_assistant_api_pipeline.transport = Mock(spec=asyncio.DatagramTransport)
@ -677,7 +674,8 @@ async def test_send_tts_wrong_format(
)
assert voice_assistant_api_pipeline._tts_task is not None
await voice_assistant_api_pipeline._tts_task # raises ValueError
with pytest.raises(ValueError):
await voice_assistant_api_pipeline._tts_task
async def test_send_tts_not_started(

View File

@ -148,7 +148,7 @@ async def test_preset_mode_validation(
},
blocking=True,
)
assert exc.value.translation_key == "not_valid_preset_mode"
assert exc.value.translation_key == "not_valid_preset_mode"
with pytest.raises(NotValidPresetModeError) as exc:
await test_fan._valid_preset_mode_or_raise("invalid")

View File

@ -106,5 +106,4 @@ async def test_services(
},
blocking=True,
)
await hass.async_block_till_done()
assert aioclient_mock.call_count == 13
assert aioclient_mock.call_count == 13

View File

@ -43,9 +43,8 @@ async def test_sync_button(hass: HomeAssistant, hass_owner_user: MockUser) -> No
)
mock_sync_entities.assert_called_once_with(hass_owner_user.id)
mock_sync_entities.return_value = 400
with pytest.raises(HomeAssistantError):
mock_sync_entities.return_value = 400
await hass.services.async_call(
"button",
"press",

View File

@ -1782,16 +1782,16 @@ async def test_arm_disarm_arm_away(hass: HomeAssistant) -> None:
# Test with no secure_pin configured
trt = trait.ArmDisArmTrait(
hass,
State(
"alarm_control_panel.alarm",
STATE_ALARM_DISARMED,
{alarm_control_panel.ATTR_CODE_ARM_REQUIRED: True},
),
BASIC_CONFIG,
)
with pytest.raises(error.SmartHomeError) as err:
trt = trait.ArmDisArmTrait(
hass,
State(
"alarm_control_panel.alarm",
STATE_ALARM_DISARMED,
{alarm_control_panel.ATTR_CODE_ARM_REQUIRED: True},
),
BASIC_CONFIG,
)
await trt.execute(
trait.COMMAND_ARMDISARM,
BASIC_DATA,
@ -1845,16 +1845,16 @@ async def test_arm_disarm_arm_away(hass: HomeAssistant) -> None:
assert len(calls) == 1
# Test already armed
trt = trait.ArmDisArmTrait(
hass,
State(
"alarm_control_panel.alarm",
STATE_ALARM_ARMED_AWAY,
{alarm_control_panel.ATTR_CODE_ARM_REQUIRED: True},
),
PIN_CONFIG,
)
with pytest.raises(error.SmartHomeError) as err:
trt = trait.ArmDisArmTrait(
hass,
State(
"alarm_control_panel.alarm",
STATE_ALARM_ARMED_AWAY,
{alarm_control_panel.ATTR_CODE_ARM_REQUIRED: True},
),
PIN_CONFIG,
)
await trt.execute(
trait.COMMAND_ARMDISARM,
PIN_DATA,
@ -1940,16 +1940,16 @@ async def test_arm_disarm_disarm(hass: HomeAssistant) -> None:
)
# Test without secure_pin configured
trt = trait.ArmDisArmTrait(
hass,
State(
"alarm_control_panel.alarm",
STATE_ALARM_ARMED_AWAY,
{alarm_control_panel.ATTR_CODE_ARM_REQUIRED: True},
),
BASIC_CONFIG,
)
with pytest.raises(error.SmartHomeError) as err:
trt = trait.ArmDisArmTrait(
hass,
State(
"alarm_control_panel.alarm",
STATE_ALARM_ARMED_AWAY,
{alarm_control_panel.ATTR_CODE_ARM_REQUIRED: True},
),
BASIC_CONFIG,
)
await trt.execute(trait.COMMAND_ARMDISARM, BASIC_DATA, {"arm": False}, {})
assert len(calls) == 0
@ -1989,31 +1989,32 @@ async def test_arm_disarm_disarm(hass: HomeAssistant) -> None:
assert len(calls) == 1
# Test already disarmed
trt = trait.ArmDisArmTrait(
hass,
State(
"alarm_control_panel.alarm",
STATE_ALARM_DISARMED,
{alarm_control_panel.ATTR_CODE_ARM_REQUIRED: True},
),
PIN_CONFIG,
)
with pytest.raises(error.SmartHomeError) as err:
trt = trait.ArmDisArmTrait(
hass,
State(
"alarm_control_panel.alarm",
STATE_ALARM_DISARMED,
{alarm_control_panel.ATTR_CODE_ARM_REQUIRED: True},
),
PIN_CONFIG,
)
await trt.execute(trait.COMMAND_ARMDISARM, PIN_DATA, {"arm": False}, {})
assert len(calls) == 1
assert err.value.code == const.ERR_ALREADY_DISARMED
trt = trait.ArmDisArmTrait(
hass,
State(
"alarm_control_panel.alarm",
STATE_ALARM_ARMED_AWAY,
{alarm_control_panel.ATTR_CODE_ARM_REQUIRED: False},
),
PIN_CONFIG,
)
# Cancel arming after already armed will require pin
with pytest.raises(error.SmartHomeError) as err:
trt = trait.ArmDisArmTrait(
hass,
State(
"alarm_control_panel.alarm",
STATE_ALARM_ARMED_AWAY,
{alarm_control_panel.ATTR_CODE_ARM_REQUIRED: False},
),
PIN_CONFIG,
)
await trt.execute(
trait.COMMAND_ARMDISARM, PIN_DATA, {"arm": True, "cancel": True}, {}
)

View File

@ -94,22 +94,20 @@ async def test_generate_content_service_error(
mock_config_entry: MockConfigEntry,
) -> None:
"""Test generate content service handles errors."""
with (
patch("google.generativeai.GenerativeModel") as mock_model,
pytest.raises(
HomeAssistantError, match="Error generating content: None reason"
),
):
with patch("google.generativeai.GenerativeModel") as mock_model:
mock_model.return_value.generate_content_async = AsyncMock(
side_effect=ClientError("reason")
)
await hass.services.async_call(
"google_generative_ai_conversation",
"generate_content",
{"prompt": "write a story about an epic fail"},
blocking=True,
return_response=True,
)
with pytest.raises(
HomeAssistantError, match="Error generating content: None reason"
):
await hass.services.async_call(
"google_generative_ai_conversation",
"generate_content",
{"prompt": "write a story about an epic fail"},
blocking=True,
return_response=True,
)
@pytest.mark.usefixtures("mock_init_component")
@ -120,20 +118,20 @@ async def test_generate_content_response_has_empty_parts(
"""Test generate content service handles response with empty parts."""
with (
patch("google.generativeai.GenerativeModel") as mock_model,
pytest.raises(HomeAssistantError, match="Error generating content"),
):
mock_response = MagicMock()
mock_response.parts = []
mock_model.return_value.generate_content_async = AsyncMock(
return_value=mock_response
)
await hass.services.async_call(
"google_generative_ai_conversation",
"generate_content",
{"prompt": "write a story about an epic fail"},
blocking=True,
return_response=True,
)
with pytest.raises(HomeAssistantError, match="Error generating content"):
await hass.services.async_call(
"google_generative_ai_conversation",
"generate_content",
{"prompt": "write a story about an epic fail"},
blocking=True,
return_response=True,
)
async def test_generate_content_service_with_image_not_allowed_path(

View File

@ -140,7 +140,6 @@ async def test_async_setup_entry_connect_failure(
controller.connect.side_effect = HeosError()
with pytest.raises(ConfigEntryNotReady):
await async_setup_entry(hass, config_entry)
await hass.async_block_till_done()
assert controller.connect.call_count == 1
assert controller.disconnect.call_count == 1
controller.connect.reset_mock()
@ -155,7 +154,6 @@ async def test_async_setup_entry_player_failure(
controller.get_players.side_effect = HeosError()
with pytest.raises(ConfigEntryNotReady):
await async_setup_entry(hass, config_entry)
await hass.async_block_till_done()
assert controller.connect.call_count == 1
assert controller.disconnect.call_count == 1
controller.connect.reset_mock()

View File

@ -295,7 +295,7 @@ async def test_services_exception(
service_call = SERVICE_KV_CALL_PARAMS[0]
service_call["service_data"]["device_id"] = "DOES_NOT_EXISTS"
with pytest.raises(ValueError):
service_call["service_data"]["device_id"] = "DOES_NOT_EXISTS"
await hass.services.async_call(**service_call)
await hass.async_block_till

View File

@ -355,7 +355,6 @@ async def test_require_admin(
context=ha.Context(user_id=hass_read_only_user.id),
blocking=True,
)
pytest.fail(f"Should have raises for {service}")
with pytest.raises(Unauthorized):
await hass.services.async_call(
@ -485,8 +484,8 @@ async def test_raises_when_db_upgrade_in_progress(
service,
blocking=True,
)
assert "The system cannot" in caplog.text
assert "while a database upgrade in progress" in caplog.text
assert "The system cannot" in caplog.text
assert "while a database upgrade is in progress" in caplog.text
assert mock_async_migration_in_progress.called
caplog.clear()
@ -530,9 +529,9 @@ async def test_raises_when_config_is_invalid(
SERVICE_HOMEASSISTANT_RESTART,
blocking=True,
)
assert "The system cannot" in caplog.text
assert "because the configuration is not valid" in caplog.text
assert "Error 1" in caplog.text
assert "The system cannot" in caplog.text
assert "because the configuration is not valid" in caplog.text
assert "Error 1" in caplog.text
assert mock_async_check_ha_config_file.called
caplog.clear()

View File

@ -198,7 +198,6 @@ async def test_delete_service(
},
blocking=True,
)
await hass.async_block_till_done()
with pytest.raises(ServiceValidationError):
await hass.services.async_call(
@ -209,7 +208,6 @@ async def test_delete_service(
},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get("scene.hallo_2") is not None
assert hass.states.get("scene.hallo") is not None
@ -303,7 +301,6 @@ async def test_ensure_no_intersection(hass: HomeAssistant) -> None:
},
blocking=True,
)
await hass.async_block_till_done()
assert "entities and snapshot_entities must not overlap" in str(ex.value)
assert hass.states.get("scene.hallo") is None

View File

@ -357,7 +357,6 @@ async def test_media_player_television(
with pytest.raises(ValueError):
acc.char_remote_key.client_update_value(20)
await hass.async_block_till_done()
acc.char_remote_key.client_update_value(7)
await hass.async_block_till_done()

View File

@ -133,7 +133,6 @@ async def test_activity_remote(
with pytest.raises(ValueError):
acc.char_remote_key.client_update_value(20)
await hass.async_block_till_done()
acc.char_remote_key.client_update_value(7)
await hass.async_block_till_done()

View File

@ -16,10 +16,9 @@ async def test_await_or_reraise(hass: HomeAssistant) -> None:
await await_or_reraise(async_noop())
with pytest.raises(Exception) as exc_info:
async_ex = async_raises(Exception("Test exception"))
await await_or_reraise(async_ex())
await await_or_reraise(async_raises(Exception("Test exception"))())
assert str(exc_info.value) == "Test exception"
async_ex = async_raises(AqualinkServiceException)
with pytest.raises(HomeAssistantError):
async_ex = async_raises(AqualinkServiceException)
await await_or_reraise(async_ex())

View File

@ -299,4 +299,4 @@ async def test_service_setup_failed(hass: HomeAssistant, knx: KNXTestKit) -> Non
{"address": "1/2/3", "payload": True, "response": False},
blocking=True,
)
assert str(exc_info.value) == "KNX entry not loaded"
assert str(exc_info.value) == "KNX entry not loaded"

View File

@ -227,7 +227,6 @@ async def test_button_error(
{ATTR_ENTITY_ID: "button.frenck_s_lametric_next_app"},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get("button.frenck_s_lametric_next_app")
assert state
@ -250,7 +249,6 @@ async def test_button_connection_error(
{ATTR_ENTITY_ID: "button.frenck_s_lametric_next_app"},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get("button.frenck_s_lametric_next_app")
assert state

View File

@ -150,7 +150,6 @@ async def test_number_error(
},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get("number.frenck_s_lametric_volume")
assert state
@ -180,7 +179,6 @@ async def test_number_connection_error(
},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get("number.frenck_s_lametric_volume")
assert state

View File

@ -94,7 +94,6 @@ async def test_select_error(
},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get("select.frenck_s_lametric_brightness_mode")
assert state
@ -124,7 +123,6 @@ async def test_select_connection_error(
},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get("select.frenck_s_lametric_brightness_mode")
assert state

View File

@ -114,7 +114,6 @@ async def test_switch_error(
},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get("switch.frenck_s_lametric_bluetooth")
assert state
@ -143,7 +142,6 @@ async def test_switch_connection_error(
},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get("switch.frenck_s_lametric_bluetooth")
assert state

View File

@ -115,9 +115,9 @@ async def test_lock_requires_pin(
# set door state to unlocked
set_node_attribute(door_lock, 1, 257, 0, 2)
await trigger_subscription_callback(hass, matter_client)
with pytest.raises(ServiceValidationError):
# Lock door using invalid code format
await trigger_subscription_callback(hass, matter_client)
await hass.services.async_call(
"lock",
"lock",

View File

@ -227,7 +227,7 @@ async def test_thermostat_set_no_temperature(
},
blocking=True,
)
cube.set_temperature_mode.assert_not_called()
cube.set_temperature_mode.assert_not_called()
async def test_thermostat_set_preset_on(

View File

@ -66,7 +66,6 @@ async def test_pause_media_player_intent(hass: HomeAssistant) -> None:
"test",
media_player_intent.INTENT_MEDIA_PAUSE,
)
await hass.async_block_till_done()
# Test feature not supported
hass.states.async_set(
@ -81,7 +80,6 @@ async def test_pause_media_player_intent(hass: HomeAssistant) -> None:
"test",
media_player_intent.INTENT_MEDIA_PAUSE,
)
await hass.async_block_till_done()
async def test_unpause_media_player_intent(hass: HomeAssistant) -> None:
@ -118,7 +116,6 @@ async def test_unpause_media_player_intent(hass: HomeAssistant) -> None:
"test",
media_player_intent.INTENT_MEDIA_UNPAUSE,
)
await hass.async_block_till_done()
async def test_next_media_player_intent(hass: HomeAssistant) -> None:
@ -155,7 +152,6 @@ async def test_next_media_player_intent(hass: HomeAssistant) -> None:
"test",
media_player_intent.INTENT_MEDIA_NEXT,
)
await hass.async_block_till_done()
# Test feature not supported
hass.states.async_set(
@ -171,7 +167,6 @@ async def test_next_media_player_intent(hass: HomeAssistant) -> None:
media_player_intent.INTENT_MEDIA_NEXT,
{"name": {"value": "test media player"}},
)
await hass.async_block_till_done()
async def test_previous_media_player_intent(hass: HomeAssistant) -> None:
@ -208,7 +203,6 @@ async def test_previous_media_player_intent(hass: HomeAssistant) -> None:
"test",
media_player_intent.INTENT_MEDIA_PREVIOUS,
)
await hass.async_block_till_done()
# Test feature not supported
hass.states.async_set(
@ -224,7 +218,6 @@ async def test_previous_media_player_intent(hass: HomeAssistant) -> None:
media_player_intent.INTENT_MEDIA_PREVIOUS,
{"name": {"value": "test media player"}},
)
await hass.async_block_till_done()
async def test_volume_media_player_intent(hass: HomeAssistant) -> None:
@ -262,7 +255,6 @@ async def test_volume_media_player_intent(hass: HomeAssistant) -> None:
media_player_intent.INTENT_SET_VOLUME,
{"volume_level": {"value": 50}},
)
await hass.async_block_till_done()
# Test feature not supported
hass.states.async_set(
@ -278,7 +270,6 @@ async def test_volume_media_player_intent(hass: HomeAssistant) -> None:
media_player_intent.INTENT_SET_VOLUME,
{"volume_level": {"value": 50}},
)
await hass.async_block_till_done()
async def test_multiple_media_players(
@ -402,7 +393,6 @@ async def test_multiple_media_players(
media_player_intent.INTENT_MEDIA_PAUSE,
{"name": {"value": "TV"}},
)
await hass.async_block_till_done()
# Pause the upstairs TV
calls = async_mock_service(hass, DOMAIN, SERVICE_MEDIA_PAUSE)

View File

@ -432,7 +432,6 @@ async def test_set_text_overlay_bad_entity_identifier(hass: HomeAssistant) -> No
client.reset_mock()
with pytest.raises(vol.error.MultipleInvalid):
await hass.services.async_call(DOMAIN, SERVICE_SET_TEXT_OVERLAY, data)
await hass.async_block_till_done()
async def test_set_text_overlay_bad_empty(hass: HomeAssistant) -> None:
@ -441,7 +440,6 @@ async def test_set_text_overlay_bad_empty(hass: HomeAssistant) -> None:
await setup_mock_motioneye_config_entry(hass, client=client)
with pytest.raises(vol.error.MultipleInvalid):
await hass.services.async_call(DOMAIN, SERVICE_SET_TEXT_OVERLAY, {})
await hass.async_block_till_done()
async def test_set_text_overlay_bad_no_left_or_right(hass: HomeAssistant) -> None:
@ -452,7 +450,6 @@ async def test_set_text_overlay_bad_no_left_or_right(hass: HomeAssistant) -> Non
data = {ATTR_ENTITY_ID: TEST_CAMERA_ENTITY_ID}
with pytest.raises(vol.error.MultipleInvalid):
await hass.services.async_call(DOMAIN, SERVICE_SET_TEXT_OVERLAY, data)
await hass.async_block_till_done()
async def test_set_text_overlay_good(hass: HomeAssistant) -> None:

View File

@ -1463,7 +1463,6 @@ async def test_reload_after_invalid_config(
{},
blocking=True,
)
await hass.async_block_till_done()
# Make sure the config is loaded now
assert hass.states.get("alarm_control_panel.test") is not None

View File

@ -1088,9 +1088,9 @@ async def test_set_preset_mode_optimistic(
state = hass.states.get(ENTITY_CLIMATE)
assert state.attributes.get("preset_mode") == "comfort"
with pytest.raises(ServiceValidationError):
with pytest.raises(ServiceValidationError) as excinfo:
await common.async_set_preset_mode(hass, "invalid", ENTITY_CLIMATE)
assert "'invalid' is not a valid preset mode" in caplog.text
assert "Preset mode invalid is not valid." in str(excinfo.value)
@pytest.mark.parametrize(
@ -1146,9 +1146,9 @@ async def test_set_preset_mode_explicit_optimistic(
state = hass.states.get(ENTITY_CLIMATE)
assert state.attributes.get("preset_mode") == "comfort"
with pytest.raises(ServiceValidationError):
with pytest.raises(ServiceValidationError) as excinfo:
await common.async_set_preset_mode(hass, "invalid", ENTITY_CLIMATE)
assert "'invalid' is not a valid preset mode" in caplog.text
assert "Preset mode invalid is not valid." in str(excinfo.value)
@pytest.mark.parametrize(

View File

@ -74,16 +74,15 @@ async def test_api_failure(
) -> None:
"""Test handling of exception from API."""
mock_myuplink_client.async_set_device_points.side_effect = ClientError
with pytest.raises(HomeAssistantError):
mock_myuplink_client.async_set_device_points.side_effect = ClientError
await hass.services.async_call(
TEST_PLATFORM,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: ENTITY_ID, "value": -125},
blocking=True,
)
await hass.async_block_till_done()
mock_myuplink_client.async_set_device_points.assert_called_once()
mock_myuplink_client.async_set_device_points.assert_called_once()
@pytest.mark.parametrize(

View File

@ -86,14 +86,13 @@ async def test_api_failure(
service: str,
) -> None:
"""Test handling of exception from API."""
mock_myuplink_client.async_set_device_points.side_effect = ClientError
with pytest.raises(HomeAssistantError):
mock_myuplink_client.async_set_device_points.side_effect = ClientError
await hass.services.async_call(
TEST_PLATFORM, service, {ATTR_ENTITY_ID: ENTITY_ID}, blocking=True
)
await hass.async_block_till_done()
mock_myuplink_client.async_set_device_points.assert_called_once()
mock_myuplink_client.async_set_device_points.assert_called_once()
@pytest.mark.parametrize(

View File

@ -516,7 +516,6 @@ async def test_thermostat_invalid_hvac_mode(
with pytest.raises(ValueError):
await common.async_set_hvac_mode(hass, HVACMode.DRY)
await hass.async_block_till_done()
assert thermostat.state == HVACMode.OFF
assert auth.method is None # No communication with API
@ -1206,7 +1205,6 @@ async def test_thermostat_invalid_fan_mode(
with pytest.raises(ServiceValidationError):
await common.async_set_fan_mode(hass, FAN_LOW)
await hass.async_block_till_done()
async def test_thermostat_target_temp(
@ -1378,7 +1376,6 @@ async def test_thermostat_unexpected_hvac_status(
with pytest.raises(ValueError):
await common.async_set_hvac_mode(hass, HVACMode.DRY)
await hass.async_block_till_done()
assert thermostat.state == HVACMode.OFF
@ -1488,7 +1485,6 @@ async def test_thermostat_invalid_set_preset_mode(
# Set preset mode that is invalid
with pytest.raises(ServiceValidationError):
await common.async_set_preset_mode(hass, PRESET_SLEEP)
await hass.async_block_till_done()
# No RPC sent
assert auth.method is None
@ -1538,7 +1534,6 @@ async def test_thermostat_hvac_mode_failure(
auth.responses = [aiohttp.web.Response(status=HTTPStatus.BAD_REQUEST)]
with pytest.raises(HomeAssistantError) as e_info:
await common.async_set_hvac_mode(hass, HVACMode.HEAT)
await hass.async_block_till_done()
assert "HVAC mode" in str(e_info)
assert "climate.my_thermostat" in str(e_info)
assert HVACMode.HEAT in str(e_info)
@ -1546,7 +1541,6 @@ async def test_thermostat_hvac_mode_failure(
auth.responses = [aiohttp.web.Response(status=HTTPStatus.BAD_REQUEST)]
with pytest.raises(HomeAssistantError) as e_info:
await common.async_set_temperature(hass, temperature=25.0)
await hass.async_block_till_done()
assert "temperature" in str(e_info)
assert "climate.my_thermostat" in str(e_info)
assert "25.0" in str(e_info)
@ -1554,7 +1548,6 @@ async def test_thermostat_hvac_mode_failure(
auth.responses = [aiohttp.web.Response(status=HTTPStatus.BAD_REQUEST)]
with pytest.raises(HomeAssistantError) as e_info:
await common.async_set_fan_mode(hass, FAN_ON)
await hass.async_block_till_done()
assert "fan mode" in str(e_info)
assert "climate.my_thermostat" in str(e_info)
assert FAN_ON in str(e_info)
@ -1562,7 +1555,6 @@ async def test_thermostat_hvac_mode_failure(
auth.responses = [aiohttp.web.Response(status=HTTPStatus.BAD_REQUEST)]
with pytest.raises(HomeAssistantError) as e_info:
await common.async_set_preset_mode(hass, PRESET_ECO)
await hass.async_block_till_done()
assert "preset mode" in str(e_info)
assert "climate.my_thermostat" in str(e_info)
assert PRESET_ECO in str(e_info)

View File

@ -750,7 +750,6 @@ async def test_service_preset_mode_with_end_time_thermostats(
},
blocking=True,
)
await hass.async_block_till_done()
# Test setting a valid preset mode (that allow an end datetime in Netatmo == THERM_MODES) without an end datetime
with pytest.raises(MultipleInvalid):
@ -763,7 +762,6 @@ async def test_service_preset_mode_with_end_time_thermostats(
},
blocking=True,
)
await hass.async_block_till_done()
async def test_service_preset_mode_already_boost_valves(
@ -914,7 +912,6 @@ async def test_service_preset_mode_invalid(
{ATTR_ENTITY_ID: "climate.cocina", ATTR_PRESET_MODE: "invalid"},
blocking=True,
)
await hass.async_block_till_done()
async def test_valves_service_turn_off(

View File

@ -373,6 +373,5 @@ async def test_set_invalid_hvac_mode(
},
blocking=True,
)
await hass.async_block_till_done()
assert mock_connection.write_coil.mock_calls == []

View File

@ -507,7 +507,6 @@ async def test_sending_none_message(hass: HomeAssistant, tmp_path: Path) -> None
await hass.services.async_call(
notify.DOMAIN, notify.SERVICE_NOTIFY, {notify.ATTR_MESSAGE: None}
)
await hass.async_block_till_done()
assert (
str(exc.value)
== "template value is None for dictionary value @ data['message']"

View File

@ -47,10 +47,12 @@ async def test_hass_numato_api_wrong_port_directions(
api = numato.NumatoAPI()
api.setup_output(0, 5)
api.setup_input(0, 2)
api.setup_input(0, 6)
api.setup_output(0, 6)
with pytest.raises(NumatoGpioError):
api.read_adc_input(0, 5) # adc_read from output
with pytest.raises(NumatoGpioError):
api.read_input(0, 6) # read from output
with pytest.raises(NumatoGpioError):
api.write_output(0, 2, 1) # write to input
@ -66,8 +68,11 @@ async def test_hass_numato_api_errors(
api = numato.NumatoAPI()
with pytest.raises(NumatoGpioError):
api.setup_input(0, 5)
with pytest.raises(NumatoGpioError):
api.read_adc_input(0, 1)
with pytest.raises(NumatoGpioError):
api.read_input(0, 2)
with pytest.raises(NumatoGpioError):
api.write_output(0, 2, 1)

View File

@ -57,24 +57,22 @@ async def test_pause_job(hass: HomeAssistant) -> None:
assert len(pause_command.mock_calls) == 0
# Test pausing the printer when it is stopped
with (
patch("pyoctoprintapi.OctoprintClient.pause_job") as pause_command,
pytest.raises(InvalidPrinterState),
):
with patch("pyoctoprintapi.OctoprintClient.pause_job") as pause_command:
coordinator.data["printer"] = OctoprintPrinterInfo(
{
"state": {"flags": {"printing": False, "paused": False}},
"temperature": [],
}
)
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{
ATTR_ENTITY_ID: "button.octoprint_pause_job",
},
blocking=True,
)
with pytest.raises(InvalidPrinterState):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{
ATTR_ENTITY_ID: "button.octoprint_pause_job",
},
blocking=True,
)
async def test_resume_job(hass: HomeAssistant) -> None:
@ -118,24 +116,22 @@ async def test_resume_job(hass: HomeAssistant) -> None:
assert len(resume_command.mock_calls) == 0
# Test resuming the printer when it is stopped
with (
patch("pyoctoprintapi.OctoprintClient.resume_job") as resume_command,
pytest.raises(InvalidPrinterState),
):
with patch("pyoctoprintapi.OctoprintClient.resume_job") as resume_command:
coordinator.data["printer"] = OctoprintPrinterInfo(
{
"state": {"flags": {"printing": False, "paused": False}},
"temperature": [],
}
)
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{
ATTR_ENTITY_ID: "button.octoprint_resume_job",
},
blocking=True,
)
with pytest.raises(InvalidPrinterState):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{
ATTR_ENTITY_ID: "button.octoprint_resume_job",
},
blocking=True,
)
async def test_stop_job(hass: HomeAssistant) -> None:

View File

@ -62,7 +62,6 @@ async def test_invalid_county(hass: HomeAssistant) -> None:
"county": "INVALID_COUNTY_THAT_SHOULDNT_EXIST",
},
)
await hass.async_block_till_done()
async def test_meter_value_error(hass: HomeAssistant) -> None:

View File

@ -114,7 +114,6 @@ async def test_send_code_no_protocol(hass: HomeAssistant) -> None:
service_data={"noprotocol": "test", "value": 42},
blocking=True,
)
await hass.async_block_till_done()
assert "required key not provided @ data['protocol']" in str(excinfo.value)

View File

@ -59,14 +59,13 @@ async def test_media_lookups(
# TV show searches
with pytest.raises(MediaNotFound) as excinfo:
payload = '{"library_name": "Not a Library", "show_name": "TV Show"}'
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_PLAY_MEDIA,
{
ATTR_ENTITY_ID: media_player_id,
ATTR_MEDIA_CONTENT_TYPE: MediaType.EPISODE,
ATTR_MEDIA_CONTENT_ID: payload,
ATTR_MEDIA_CONTENT_ID: '{"library_name": "Not a Library", "show_name": "TV Show"}',
},
True,
)
@ -251,36 +250,36 @@ async def test_media_lookups(
search.assert_called_with(title="Movie 1", libtype=None)
with pytest.raises(MediaNotFound) as excinfo:
payload = '{"title": "Movie 1"}'
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_PLAY_MEDIA,
{
ATTR_ENTITY_ID: media_player_id,
ATTR_MEDIA_CONTENT_TYPE: MediaType.VIDEO,
ATTR_MEDIA_CONTENT_ID: payload,
ATTR_MEDIA_CONTENT_ID: '{"title": "Movie 1"}',
},
True,
)
assert "Must specify 'library_name' for this search" in str(excinfo.value)
with pytest.raises(MediaNotFound) as excinfo:
payload = '{"library_name": "Movies", "title": "Not a Movie"}'
with patch(
with (
pytest.raises(MediaNotFound) as excinfo,
patch(
"plexapi.library.LibrarySection.search",
side_effect=BadRequest,
__qualname__="search",
):
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_PLAY_MEDIA,
{
ATTR_ENTITY_ID: media_player_id,
ATTR_MEDIA_CONTENT_TYPE: MediaType.VIDEO,
ATTR_MEDIA_CONTENT_ID: payload,
},
True,
)
),
):
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_PLAY_MEDIA,
{
ATTR_ENTITY_ID: media_player_id,
ATTR_MEDIA_CONTENT_TYPE: MediaType.VIDEO,
ATTR_MEDIA_CONTENT_ID: '{"library_name": "Movies", "title": "Not a Movie"}',
},
True,
)
assert "Problem in query" in str(excinfo.value)
# Playlist searches
@ -296,28 +295,26 @@ async def test_media_lookups(
)
with pytest.raises(MediaNotFound) as excinfo:
payload = '{"playlist_name": "Not a Playlist"}'
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_PLAY_MEDIA,
{
ATTR_ENTITY_ID: media_player_id,
ATTR_MEDIA_CONTENT_TYPE: MediaType.PLAYLIST,
ATTR_MEDIA_CONTENT_ID: payload,
ATTR_MEDIA_CONTENT_ID: '{"playlist_name": "Not a Playlist"}',
},
True,
)
assert "Playlist 'Not a Playlist' not found" in str(excinfo.value)
with pytest.raises(MediaNotFound) as excinfo:
payload = "{}"
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_PLAY_MEDIA,
{
ATTR_ENTITY_ID: media_player_id,
ATTR_MEDIA_CONTENT_TYPE: MediaType.PLAYLIST,
ATTR_MEDIA_CONTENT_ID: payload,
ATTR_MEDIA_CONTENT_ID: "{}",
},
True,
)

View File

@ -83,7 +83,7 @@ async def test_media_player_playback(
},
True,
)
assert not playmedia_mock.called
assert not playmedia_mock.called
assert f"No {MediaType.MOVIE} results in 'Movies' for" in str(excinfo.value)
movie1 = MockPlexMedia("Movie", "movie")
@ -197,24 +197,25 @@ async def test_media_player_playback(
# Test multiple choices without exact match
playmedia_mock.reset()
movies = [movie2, movie3]
with pytest.raises(HomeAssistantError) as excinfo:
payload = '{"library_name": "Movies", "title": "Movie" }'
with patch(
with (
pytest.raises(HomeAssistantError) as excinfo,
patch(
"plexapi.library.LibrarySection.search",
return_value=movies,
__qualname__="search",
):
await hass.services.async_call(
MP_DOMAIN,
SERVICE_PLAY_MEDIA,
{
ATTR_ENTITY_ID: media_player,
ATTR_MEDIA_CONTENT_TYPE: MediaType.MOVIE,
ATTR_MEDIA_CONTENT_ID: payload,
},
True,
)
assert not playmedia_mock.called
),
):
await hass.services.async_call(
MP_DOMAIN,
SERVICE_PLAY_MEDIA,
{
ATTR_ENTITY_ID: media_player,
ATTR_MEDIA_CONTENT_TYPE: MediaType.MOVIE,
ATTR_MEDIA_CONTENT_ID: '{"library_name": "Movies", "title": "Movie" }',
},
True,
)
assert not playmedia_mock.called
assert "Multiple matches, make content_id more specific" in str(excinfo.value)
# Test multiple choices with allow_multiple

View File

@ -95,9 +95,8 @@ async def test_exception_on_powerwall_error(
) -> None:
"""Ensure that an exception in the tesla_powerwall library causes a HomeAssistantError."""
mock_powerwall.set_island_mode.side_effect = PowerwallError("Mock exception")
with pytest.raises(HomeAssistantError, match="Setting off-grid operation to"):
mock_powerwall.set_island_mode.side_effect = PowerwallError("Mock exception")
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,

View File

@ -40,9 +40,9 @@ async def test_camera_fail(
):
await camera.async_get_image(hass, "camera.contract_1234abcd_test_cam")
assert "Unable to get image" in str(exc.value)
assert "Unable to get image" in str(exc.value)
assert "Image test_cam doesn't exist" in caplog.text
assert "Image test_cam doesn't exist" in caplog.text
async def test_request_image(

View File

@ -270,13 +270,11 @@ async def test_switch_error(
with pytest.raises(HomeAssistantError, match=expected_msg):
await switch_common.async_turn_on(hass, "switch.rain_bird_sprinkler_3")
await hass.async_block_till_done()
responses.append(mock_response_error(status=status))
with pytest.raises(HomeAssistantError, match=expected_msg):
await switch_common.async_turn_off(hass, "switch.rain_bird_sprinkler_3")
await hass.async_block_till_done()
@pytest.mark.parametrize(

View File

@ -31,7 +31,7 @@ async def test_async_pre_backup_with_timeout(
pytest.raises(TimeoutError),
):
await async_pre_backup(hass)
assert lock_mock.called
assert lock_mock.called
async def test_async_pre_backup_with_migration(
@ -69,4 +69,4 @@ async def test_async_post_backup_failure(
pytest.raises(HomeAssistantError),
):
await async_post_backup(hass)
assert unlock_mock.called
assert unlock_mock.called

View File

@ -1853,8 +1853,8 @@ async def test_database_lock_and_unlock(
# Recording can't be finished while lock is held
with pytest.raises(TimeoutError):
await asyncio.wait_for(asyncio.shield(task), timeout=0.25)
db_events = await hass.async_add_executor_job(_get_db_events)
assert len(db_events) == 0
db_events = await hass.async_add_executor_job(_get_db_events)
assert len(db_events) == 0
assert instance.unlock_database()

View File

@ -155,7 +155,6 @@ async def test_siren_errors_when_turned_on(
{"entity_id": "siren.downstairs_siren", "tone": "motion"},
blocking=True,
)
await hass.async_block_till_done()
downstairs_chime_mock.test_sound.assert_called_once_with(kind="motion")
assert (
any(

View File

@ -248,8 +248,9 @@ async def test_clean_room_error(
hass: HomeAssistant, room_list: list, exception: Exception
) -> None:
"""Test clean_room errors."""
data = {ATTR_ENTITY_ID: VAC_ENTITY_ID, ATTR_ROOMS: room_list}
with pytest.raises(exception):
data = {ATTR_ENTITY_ID: VAC_ENTITY_ID, ATTR_ROOMS: room_list}
await hass.services.async_call(DOMAIN, SERVICE_CLEAN_ROOM, data, blocking=True)

View File

@ -173,14 +173,14 @@ async def test_block_update_connection_error(
)
await init_integration(hass, 1)
with pytest.raises(HomeAssistantError):
with pytest.raises(HomeAssistantError) as excinfo:
await hass.services.async_call(
UPDATE_DOMAIN,
SERVICE_INSTALL,
{ATTR_ENTITY_ID: "update.test_name_firmware_update"},
blocking=True,
)
assert "Error starting OTA update" in caplog.text
assert "Error starting OTA update" in str(excinfo.value)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
@ -597,7 +597,7 @@ async def test_rpc_beta_update(
@pytest.mark.parametrize(
("exc", "error"),
[
(DeviceConnectionError, "Error starting OTA update"),
(DeviceConnectionError, "OTA update connection error: DeviceConnectionError()"),
(RpcCallError(-1, "error"), "OTA update request error"),
],
)
@ -625,14 +625,14 @@ async def test_rpc_update_errors(
)
await init_integration(hass, 2)
with pytest.raises(HomeAssistantError):
with pytest.raises(HomeAssistantError) as excinfo:
await hass.services.async_call(
UPDATE_DOMAIN,
SERVICE_INSTALL,
{ATTR_ENTITY_ID: "update.test_name_firmware_update"},
blocking=True,
)
assert error in caplog.text
assert error in str(excinfo.value)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")

View File

@ -97,8 +97,7 @@ def test_send_message_with_bad_data_throws_vol_error(
),
pytest.raises(vol.Invalid) as exc,
):
data = {"test": "test"}
signal_notification_service.send_message(MESSAGE, data=data)
signal_notification_service.send_message(MESSAGE, data={"test": "test"})
assert "Sending signal message" in caplog.text
assert "extra keys not allowed" in str(exc.value)
@ -192,8 +191,9 @@ def test_get_attachments_with_large_attachment(
"""Test getting attachments as URL with large attachment (per Content-Length header) throws error."""
signal_requests_mock = signal_requests_mock_factory(True, str(len(CONTENT) + 1))
with pytest.raises(ValueError) as exc:
data = {"urls": [URL_ATTACHMENT]}
signal_notification_service.get_attachments_as_bytes(data, len(CONTENT), hass)
signal_notification_service.get_attachments_as_bytes(
{"urls": [URL_ATTACHMENT]}, len(CONTENT), hass
)
assert signal_requests_mock.called
assert signal_requests_mock.call_count == 1
@ -208,9 +208,8 @@ def test_get_attachments_with_large_attachment_no_header(
"""Test getting attachments as URL with large attachment (per content length) throws error."""
signal_requests_mock = signal_requests_mock_factory()
with pytest.raises(ValueError) as exc:
data = {"urls": [URL_ATTACHMENT]}
signal_notification_service.get_attachments_as_bytes(
data, len(CONTENT) - 1, hass
{"urls": [URL_ATTACHMENT]}, len(CONTENT) - 1, hass
)
assert signal_requests_mock.called

View File

@ -173,7 +173,6 @@ def test_sending_insecure_files_fails(
pytest.raises(ServiceValidationError) as exc,
):
result, _ = message.send_message(message_data, data=data)
assert content_type in result
assert exc.value.translation_key == "remote_path_not_allowed"
assert exc.value.translation_domain == DOMAIN
assert (

View File

@ -341,9 +341,10 @@ async def test_stream_open_fails(hass: HomeAssistant) -> None:
dynamic_stream_settings(),
)
stream.add_provider(HLS_PROVIDER)
with patch("av.open") as av_open, pytest.raises(StreamWorkerError):
with patch("av.open") as av_open:
av_open.side_effect = av.error.InvalidDataError(-2, "error")
run_worker(hass, stream, STREAM_SOURCE)
with pytest.raises(StreamWorkerError):
run_worker(hass, stream, STREAM_SOURCE)
await hass.async_block_till_done()
av_open.assert_called_once()
@ -768,9 +769,10 @@ async def test_worker_log(
)
stream.add_provider(HLS_PROVIDER)
with patch("av.open") as av_open, pytest.raises(StreamWorkerError) as err:
with patch("av.open") as av_open:
av_open.side_effect = av.error.InvalidDataError(-2, "error")
run_worker(hass, stream, stream_url)
with pytest.raises(StreamWorkerError) as err:
run_worker(hass, stream, stream_url)
await hass.async_block_till_done()
assert (
str(err.value) == f"Error opening stream (ERRORTYPE_-2, error) {redacted_url}"

View File

@ -61,8 +61,7 @@ async def test_lock_cmd_fails(hass: HomeAssistant, ev_entry) -> None:
await hass.services.async_call(
LOCK_DOMAIN, SERVICE_UNLOCK, {ATTR_ENTITY_ID: DEVICE_ID}, blocking=True
)
await hass.async_block_till_done()
mock_lock.assert_called_once()
mock_lock.assert_not_called()
async def test_unlock_specific_door(hass: HomeAssistant, ev_entry) -> None:
@ -87,5 +86,4 @@ async def test_unlock_specific_door_invalid(hass: HomeAssistant, ev_entry) -> No
{ATTR_ENTITY_ID: DEVICE_ID, ATTR_DOOR: "bad_value"},
blocking=True,
)
await hass.async_block_till_done()
mock_unlock.assert_not_called()
mock_unlock.assert_not_called()

View File

@ -80,7 +80,7 @@ async def test_add_meter_readings_exception(
blocking=True,
)
assert "Could not set meter reading" in str(exc)
assert "Could not set meter reading" in str(exc)
async def test_add_meter_readings_invalid(
@ -109,7 +109,7 @@ async def test_add_meter_readings_invalid(
blocking=True,
)
assert "invalid new reading" in str(exc)
assert "invalid new reading" in str(exc)
async def test_add_meter_readings_duplicate(
@ -138,4 +138,4 @@ async def test_add_meter_readings_duplicate(
blocking=True,
)
assert "reading already exists for date" in str(exc)
assert "reading already exists for date" in str(exc)

View File

@ -154,8 +154,11 @@ async def test_invalid_error(hass: HomeAssistant) -> None:
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_on.assert_called_once()
assert error.from_exception == InvalidCommand
mock_on.assert_called_once()
assert (
str(error.value)
== "Teslemetry command failed, The data request or command is unknown."
)
@pytest.mark.parametrize("response", COMMAND_ERRORS)
@ -178,7 +181,7 @@ async def test_errors(hass: HomeAssistant, response: str) -> None:
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_on.assert_called_once()
mock_on.assert_called_once()
async def test_ignored_error(
@ -232,7 +235,7 @@ async def test_asleep_or_offline(
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
assert error
assert str(error.value) == "The data request or command is unknown."
mock_wake_up.assert_called_once()
mock_wake_up.side_effect = None
@ -251,7 +254,7 @@ async def test_asleep_or_offline(
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
assert error
assert str(error.value) == "Could not wake up vehicle"
mock_wake_up.assert_called_once()
mock_vehicle.assert_called()

View File

@ -21,7 +21,7 @@ TEST_VEHICLE_STATUS_AWAKE = {"status": TessieStatus.AWAKE}
TEST_VEHICLE_STATUS_ASLEEP = {"status": TessieStatus.ASLEEP}
TEST_RESPONSE = {"result": True}
TEST_RESPONSE_ERROR = {"result": False, "reason": "reason why"}
TEST_RESPONSE_ERROR = {"result": False, "reason": "reason_why"}
TEST_CONFIG = {CONF_ACCESS_TOKEN: "1234567890"}
TESSIE_URL = "https://api.tessie.com/"

View File

@ -128,5 +128,5 @@ async def test_errors(hass: HomeAssistant) -> None:
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_set.assert_called_once()
assert error.from_exception == ERROR_UNKNOWN
mock_set.assert_called_once()
assert error.value.__cause__ == ERROR_UNKNOWN

View File

@ -94,8 +94,8 @@ async def test_errors(hass: HomeAssistant) -> None:
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_set.assert_called_once()
assert error.from_exception == ERROR_UNKNOWN
mock_set.assert_called_once()
assert error.value.__cause__ == ERROR_UNKNOWN
# Test setting cover open with unknown error
with (
@ -111,5 +111,5 @@ async def test_errors(hass: HomeAssistant) -> None:
{ATTR_ENTITY_ID: [entity_id]},
blocking=True,
)
mock_set.assert_called_once()
assert str(error) == TEST_RESPONSE_ERROR["reason"]
mock_set.assert_called_once()
assert str(error.value) == TEST_RESPONSE_ERROR["reason"]

View File

@ -66,5 +66,5 @@ async def test_errors(hass: HomeAssistant) -> None:
{ATTR_ENTITY_ID: [entity_id], ATTR_OPTION: TessieSeatHeaterOptions.LOW},
blocking=True,
)
mock_set.assert_called_once()
assert error.from_exception == ERROR_UNKNOWN
mock_set.assert_called_once()
assert error.value.__cause__ == ERROR_UNKNOWN

View File

@ -46,16 +46,22 @@ async def test_notification_services(
with pytest.raises(HomeAssistantError):
# Test legacy notify service
service = "tibber"
service_data = {"message": "The message", "title": "A title"}
await hass.services.async_call("notify", service, service_data, blocking=True)
await hass.services.async_call(
"notify",
service="tibber",
service_data={"message": "The message", "title": "A title"},
blocking=True,
)
with pytest.raises(HomeAssistantError):
# Test notify entity service
service = "send_message"
service_data = {
"entity_id": "notify.tibber",
"message": "The message",
"title": "A title",
}
await hass.services.async_call("notify", service, service_data, blocking=True)
await hass.services.async_call(
"notify",
service="send_message",
service_data={
"entity_id": "notify.tibber",
"message": "The message",
"title": "A title",
},
blocking=True,
)

View File

@ -308,7 +308,6 @@ async def test_start_service(hass: HomeAssistant) -> None:
{CONF_ENTITY_ID: "timer.test1", CONF_DURATION: 10},
blocking=True,
)
await hass.async_block_till_done()
await hass.services.async_call(
DOMAIN,

View File

@ -48,7 +48,7 @@ async def test_bypass_button(hass: HomeAssistant, entity_id: str) -> None:
service_data={ATTR_ENTITY_ID: entity_id},
blocking=True,
)
assert mock_request.call_count == 1
assert mock_request.call_count == 1
# try to bypass, works this time
await hass.services.async_call(

View File

@ -260,5 +260,4 @@ async def test_switch_services(
blocking=True,
)
await hass.async_block_till_done()
assert str(exc_info.value) == "Entity is not a WiLight valve switch"

View File

@ -58,7 +58,6 @@ async def test_button_restart(
{ATTR_ENTITY_ID: "button.wled_rgb_light_restart"},
blocking=True,
)
await hass.async_block_till_done()
# Ensure this didn't made the entity unavailable
assert (state := hass.states.get("button.wled_rgb_light_restart"))

View File

@ -1262,7 +1262,7 @@ async def test_set_fan_mode_not_supported(
{ATTR_ENTITY_ID: entity_id, ATTR_FAN_MODE: FAN_LOW},
blocking=True,
)
assert fan_cluster.write_attributes.await_count == 0
assert fan_cluster.write_attributes.await_count == 0
async def test_set_fan_mode(hass: HomeAssistant, device_climate_fan) -> None:

View File

@ -986,30 +986,30 @@ async def test_quirks_v2_metadata_errors(
validate_metadata(validate_method)
# ensure the error is caught and raised
with pytest.raises(ValueError, match=expected_exception_string):
try:
# introduce an error
zigpy_device = _get_test_device(
zigpy_device_mock,
try:
# introduce an error
zigpy_device = _get_test_device(
zigpy_device_mock,
"Ikea of Sweden4",
"TRADFRI remote control4",
augment_method=augment_method,
)
await zha_device_joined(zigpy_device)
validate_metadata(validate_method)
# if the device was created we remove it
# so we don't pollute the rest of the tests
zigpy.quirks._DEVICE_REGISTRY.remove(zigpy_device)
except ValueError:
# if the device was not created we remove it
# so we don't pollute the rest of the tests
zigpy.quirks._DEVICE_REGISTRY._registry_v2.pop(
(
"Ikea of Sweden4",
"TRADFRI remote control4",
augment_method=augment_method,
)
await zha_device_joined(zigpy_device)
validate_metadata(validate_method)
# if the device was created we remove it
# so we don't pollute the rest of the tests
zigpy.quirks._DEVICE_REGISTRY.remove(zigpy_device)
except ValueError:
# if the device was not created we remove it
# so we don't pollute the rest of the tests
zigpy.quirks._DEVICE_REGISTRY._registry_v2.pop(
(
"Ikea of Sweden4",
"TRADFRI remote control4",
)
)
)
with pytest.raises(ValueError, match=expected_exception_string):
raise

View File

@ -34,12 +34,12 @@ def test_validate_version_no_key(integration: Integration) -> None:
def test_validate_custom_integration_manifest(integration: Integration) -> None:
"""Test validate custom integration manifest."""
integration.manifest["version"] = "lorem_ipsum"
with pytest.raises(vol.Invalid):
integration.manifest["version"] = "lorem_ipsum"
CUSTOM_INTEGRATION_MANIFEST_SCHEMA(integration.manifest)
integration.manifest["version"] = None
with pytest.raises(vol.Invalid):
integration.manifest["version"] = None
CUSTOM_INTEGRATION_MANIFEST_SCHEMA(integration.manifest)
integration.manifest["version"] = "1"

View File

@ -85,12 +85,11 @@ async def test_create_area_with_name_already_in_use(
) -> None:
"""Make sure that we can't create an area with a name already in use."""
update_events = async_capture_events(hass, ar.EVENT_AREA_REGISTRY_UPDATED)
area1 = area_registry.async_create("mock")
area_registry.async_create("mock")
with pytest.raises(ValueError) as e_info:
area2 = area_registry.async_create("mock")
assert area1 != area2
assert e_info == "The name mock 2 (mock2) is already in use"
area_registry.async_create("mock")
assert str(e_info.value) == "The name mock (mock) is already in use"
await hass.async_block_till_done()
@ -226,7 +225,7 @@ async def test_update_area_with_name_already_in_use(
with pytest.raises(ValueError) as e_info:
area_registry.async_update(area1.id, name="mock2")
assert e_info == "The name mock 2 (mock2) is already in use"
assert str(e_info.value) == "The name mock2 (mock2) is already in use"
assert area1.name == "mock1"
assert area2.name == "mock2"
@ -242,7 +241,7 @@ async def test_update_area_with_normalized_name_already_in_use(
with pytest.raises(ValueError) as e_info:
area_registry.async_update(area1.id, name="mock2")
assert e_info == "The name mock 2 (mock2) is already in use"
assert str(e_info.value) == "The name mock2 (mock2) is already in use"
assert area1.name == "mock1"
assert area2.name == "Moc k2"

View File

@ -1104,17 +1104,18 @@ async def test_state_raises(hass: HomeAssistant) -> None:
test(hass)
# Unknown state entity
with pytest.raises(ConditionError, match="input_text.missing"):
config = {
"condition": "state",
"entity_id": "sensor.door",
"state": "input_text.missing",
}
config = cv.CONDITION_SCHEMA(config)
config = await condition.async_validate_condition_config(hass, config)
test = await condition.async_from_config(hass, config)
hass.states.async_set("sensor.door", "open")
config = {
"condition": "state",
"entity_id": "sensor.door",
"state": "input_text.missing",
}
config = cv.CONDITION_SCHEMA(config)
config = await condition.async_validate_condition_config(hass, config)
test = await condition.async_from_config(hass, config)
hass.states.async_set("sensor.door", "open")
with pytest.raises(ConditionError, match="input_text.missing"):
test(hass)
@ -1549,76 +1550,76 @@ async def test_numeric_state_raises(hass: HomeAssistant) -> None:
test(hass)
# Template error
with pytest.raises(ConditionError, match="ZeroDivisionError"):
config = {
"condition": "numeric_state",
"entity_id": "sensor.temperature",
"value_template": "{{ 1 / 0 }}",
"above": 0,
}
config = cv.CONDITION_SCHEMA(config)
config = await condition.async_validate_condition_config(hass, config)
test = await condition.async_from_config(hass, config)
config = {
"condition": "numeric_state",
"entity_id": "sensor.temperature",
"value_template": "{{ 1 / 0 }}",
"above": 0,
}
config = cv.CONDITION_SCHEMA(config)
config = await condition.async_validate_condition_config(hass, config)
test = await condition.async_from_config(hass, config)
hass.states.async_set("sensor.temperature", 50)
hass.states.async_set("sensor.temperature", 50)
with pytest.raises(ConditionError, match="ZeroDivisionError"):
test(hass)
# Bad number
with pytest.raises(ConditionError, match="cannot be processed as a number"):
config = {
"condition": "numeric_state",
"entity_id": "sensor.temperature",
"above": 0,
}
config = cv.CONDITION_SCHEMA(config)
config = await condition.async_validate_condition_config(hass, config)
test = await condition.async_from_config(hass, config)
config = {
"condition": "numeric_state",
"entity_id": "sensor.temperature",
"above": 0,
}
config = cv.CONDITION_SCHEMA(config)
config = await condition.async_validate_condition_config(hass, config)
test = await condition.async_from_config(hass, config)
hass.states.async_set("sensor.temperature", "fifty")
hass.states.async_set("sensor.temperature", "fifty")
with pytest.raises(ConditionError, match="cannot be processed as a number"):
test(hass)
# Below entity missing
with pytest.raises(ConditionError, match="'below' entity"):
config = {
"condition": "numeric_state",
"entity_id": "sensor.temperature",
"below": "input_number.missing",
}
config = cv.CONDITION_SCHEMA(config)
config = await condition.async_validate_condition_config(hass, config)
test = await condition.async_from_config(hass, config)
config = {
"condition": "numeric_state",
"entity_id": "sensor.temperature",
"below": "input_number.missing",
}
config = cv.CONDITION_SCHEMA(config)
config = await condition.async_validate_condition_config(hass, config)
test = await condition.async_from_config(hass, config)
hass.states.async_set("sensor.temperature", 50)
hass.states.async_set("sensor.temperature", 50)
with pytest.raises(ConditionError, match="'below' entity"):
test(hass)
# Below entity not a number
hass.states.async_set("input_number.missing", "number")
with pytest.raises(
ConditionError,
match="'below'.*input_number.missing.*cannot be processed as a number",
):
hass.states.async_set("input_number.missing", "number")
test(hass)
# Above entity missing
with pytest.raises(ConditionError, match="'above' entity"):
config = {
"condition": "numeric_state",
"entity_id": "sensor.temperature",
"above": "input_number.missing",
}
config = cv.CONDITION_SCHEMA(config)
config = await condition.async_validate_condition_config(hass, config)
test = await condition.async_from_config(hass, config)
config = {
"condition": "numeric_state",
"entity_id": "sensor.temperature",
"above": "input_number.missing",
}
config = cv.CONDITION_SCHEMA(config)
config = await condition.async_validate_condition_config(hass, config)
test = await condition.async_from_config(hass, config)
hass.states.async_set("sensor.temperature", 50)
hass.states.async_set("sensor.temperature", 50)
with pytest.raises(ConditionError, match="'above' entity"):
test(hass)
# Above entity not a number
hass.states.async_set("input_number.missing", "number")
with pytest.raises(
ConditionError,
match="'above'.*input_number.missing.*cannot be processed as a number",
):
hass.states.async_set("input_number.missing", "number")
test(hass)

View File

@ -602,7 +602,9 @@ def test_x10_address() -> None:
schema = vol.Schema(cv.x10_address)
with pytest.raises(vol.Invalid):
schema("Q1")
with pytest.raises(vol.Invalid):
schema("q55")
with pytest.raises(vol.Invalid):
schema("garbage_addr")
schema("a1")
@ -809,6 +811,7 @@ def test_multi_select() -> None:
with pytest.raises(vol.Invalid):
schema("robban")
with pytest.raises(vol.Invalid):
schema(["paulus", "martinhj"])
schema(["robban", "paulus"])
@ -1335,7 +1338,7 @@ def test_key_value_schemas() -> None:
with pytest.raises(vol.Invalid) as excinfo:
schema(True)
assert str(excinfo.value) == "Expected a dictionary"
assert str(excinfo.value) == "Expected a dictionary"
for mode in None, {"a": "dict"}, "invalid":
with pytest.raises(vol.Invalid) as excinfo:
@ -1373,7 +1376,7 @@ def test_key_value_schemas_with_default() -> None:
with pytest.raises(vol.Invalid) as excinfo:
schema(True)
assert str(excinfo.value) == "Expected a dictionary"
assert str(excinfo.value) == "Expected a dictionary"
for mode in None, {"a": "dict"}, "invalid":
with pytest.raises(vol.Invalid) as excinfo:

View File

@ -510,7 +510,7 @@ async def test_register_entity_service(hass: HomeAssistant) -> None:
{"entity_id": entity.entity_id, "invalid": "data"},
blocking=True,
)
assert len(calls) == 0
assert len(calls) == 0
await hass.services.async_call(
DOMAIN, "hello", {"entity_id": entity.entity_id, "some": "data"}, blocking=True

View File

@ -1855,7 +1855,6 @@ async def test_cancellation_is_not_blocked(
with pytest.raises(asyncio.CancelledError):
assert await platform.async_setup_entry(config_entry)
await hass.async_block_till_done()
full_name = f"{config_entry.domain}.{platform.domain}"
assert full_name not in hass.config.components

View File

@ -60,9 +60,9 @@ def test_key_already_in_use(
# should raise ValueError if we update a
# key with a entry with the same normalized name
entry = NormalizedNameBaseRegistryEntry(
name="Hello World 2", normalized_name="helloworld2"
)
registry_items["key2"] = entry
with pytest.raises(ValueError):
entry = NormalizedNameBaseRegistryEntry(
name="Hello World 2", normalized_name="helloworld2"
)
registry_items["key2"] = entry
registry_items["key"] = entry

View File

@ -450,7 +450,6 @@ async def test_service_response_data_errors(
with pytest.raises(vol.Invalid, match=expected_error):
await script_obj.async_run(context=context)
await hass.async_block_till_done()
async def test_data_template_with_templated_key(hass: HomeAssistant) -> None:
@ -4903,15 +4902,15 @@ async def test_script_mode_queued_cancel(hass: HomeAssistant) -> None:
assert script_obj.is_running
assert script_obj.runs == 2
task2.cancel()
with pytest.raises(asyncio.CancelledError):
task2.cancel()
await task2
assert script_obj.is_running
assert script_obj.runs == 2
task1.cancel()
with pytest.raises(asyncio.CancelledError):
task1.cancel()
await task1
assert not script_obj.is_running

View File

@ -3879,8 +3879,8 @@ async def test_device_attr(
assert_result_info(info, None)
assert info.rate_limit is None
info = render_to_info(hass, "{{ device_attr(56, 'id') }}")
with pytest.raises(TemplateError):
info = render_to_info(hass, "{{ device_attr(56, 'id') }}")
assert_result_info(info, None)
# Test non existing device ids (is_device_attr)
@ -3888,8 +3888,8 @@ async def test_device_attr(
assert_result_info(info, False)
assert info.rate_limit is None
info = render_to_info(hass, "{{ is_device_attr(56, 'id', 'test') }}")
with pytest.raises(TemplateError):
info = render_to_info(hass, "{{ is_device_attr(56, 'id', 'test') }}")
assert_result_info(info, False)
# Test non existing entity id (device_attr)

View File

@ -113,7 +113,6 @@ async def test_protect_loop_importlib_import_module_non_integration(
]
)
with (
pytest.raises(ImportError),
patch.object(block_async_io, "_IN_TESTS", False),
patch(
"homeassistant.block_async_io.get_current_frame",
@ -125,7 +124,8 @@ async def test_protect_loop_importlib_import_module_non_integration(
),
):
block_async_io.enable()
importlib.import_module("not_loaded_module")
with pytest.raises(ImportError):
importlib.import_module("not_loaded_module")
assert "Detected blocking call to import_module" in caplog.text
@ -184,7 +184,6 @@ async def test_protect_loop_importlib_import_module_in_integration(
]
)
with (
pytest.raises(ImportError),
patch.object(block_async_io, "_IN_TESTS", False),
patch(
"homeassistant.block_async_io.get_current_frame",
@ -196,7 +195,8 @@ async def test_protect_loop_importlib_import_module_in_integration(
),
):
block_async_io.enable()
importlib.import_module("not_loaded_module")
with pytest.raises(ImportError):
importlib.import_module("not_loaded_module")
assert (
"Detected blocking call to import_module inside the event loop by "

View File

@ -1835,7 +1835,6 @@ async def test_serviceregistry_return_response_invalid(
blocking=True,
return_response=True,
)
await hass.async_block_till_done()
@pytest.mark.parametrize(

View File

@ -356,8 +356,6 @@ async def test_get_integration_with_requirements_pip_install_fails_two_passes(
integration = await async_get_integration_with_requirements(
hass, "test_component"
)
assert integration
assert integration.domain == "test_component"
assert len(mock_is_installed.mock_calls) == 3
assert sorted(mock_call[1][0] for mock_call in mock_is_installed.mock_calls) == [
@ -391,8 +389,6 @@ async def test_get_integration_with_requirements_pip_install_fails_two_passes(
integration = await async_get_integration_with_requirements(
hass, "test_component"
)
assert integration
assert integration.domain == "test_component"
assert len(mock_is_installed.mock_calls) == 0
# On another attempt we remember failures and don't try again
@ -414,8 +410,6 @@ async def test_get_integration_with_requirements_pip_install_fails_two_passes(
integration = await async_get_integration_with_requirements(
hass, "test_component"
)
assert integration
assert integration.domain == "test_component"
assert len(mock_is_installed.mock_calls) == 2
assert sorted(mock_call[1][0] for mock_call in mock_is_installed.mock_calls) == [

View File

@ -110,7 +110,7 @@ async def test_mix_global_timeout_freeze_and_zone_freeze_other_zone_inside_execu
with timeout.freeze("not_recorder"):
time.sleep(0.3)
with pytest.raises(TimeoutError):
with pytest.raises(TimeoutError): # noqa: PT012
async with timeout.async_timeout(0.1):
async with (
timeout.async_timeout(0.2, zone_name="recorder"),
@ -129,7 +129,7 @@ async def test_mix_global_timeout_freeze_and_zone_freeze_inside_executor_job_sec
with timeout.freeze("recorder"):
time.sleep(0.3)
with pytest.raises(TimeoutError):
with pytest.raises(TimeoutError): # noqa: PT012
async with timeout.async_timeout(0.1):
async with timeout.async_timeout(0.2, zone_name="recorder"):
await hass.async_add_executor_job(_some_sync_work)
@ -150,7 +150,7 @@ async def test_simple_global_timeout_freeze_reset() -> None:
"""Test a simple global timeout freeze reset."""
timeout = TimeoutManager()
with pytest.raises(TimeoutError):
with pytest.raises(TimeoutError): # noqa: PT012
async with timeout.async_timeout(0.2):
async with timeout.async_freeze():
await asyncio.sleep(0.1)
@ -170,7 +170,7 @@ async def test_multiple_zone_timeout() -> None:
"""Test a simple zone timeout."""
timeout = TimeoutManager()
with pytest.raises(TimeoutError):
with pytest.raises(TimeoutError): # noqa: PT012
async with timeout.async_timeout(0.1, "test"):
async with timeout.async_timeout(0.5, "test"):
await asyncio.sleep(0.3)
@ -180,7 +180,7 @@ async def test_different_zone_timeout() -> None:
"""Test a simple zone timeout."""
timeout = TimeoutManager()
with pytest.raises(TimeoutError):
with pytest.raises(TimeoutError): # noqa: PT012
async with timeout.async_timeout(0.1, "test"):
async with timeout.async_timeout(0.5, "other"):
await asyncio.sleep(0.3)
@ -206,7 +206,7 @@ async def test_simple_zone_timeout_freeze_reset() -> None:
"""Test a simple zone timeout freeze reset."""
timeout = TimeoutManager()
with pytest.raises(TimeoutError):
with pytest.raises(TimeoutError): # noqa: PT012
async with timeout.async_timeout(0.2, "test"):
async with timeout.async_freeze("test"):
await asyncio.sleep(0.1)
@ -259,7 +259,7 @@ async def test_mix_zone_timeout_trigger_global() -> None:
"""Test a mix zone timeout global with trigger it."""
timeout = TimeoutManager()
with pytest.raises(TimeoutError):
with pytest.raises(TimeoutError): # noqa: PT012
async with timeout.async_timeout(0.1):
with suppress(TimeoutError):
async with timeout.async_timeout(0.1, "test"):
@ -308,7 +308,7 @@ async def test_simple_zone_timeout_freeze_without_timeout_cleanup2(
async with timeout.async_freeze("test"):
await asyncio.sleep(0.2)
with pytest.raises(TimeoutError):
with pytest.raises(TimeoutError): # noqa: PT012
async with timeout.async_timeout(0.1):
hass.async_create_task(background())
await asyncio.sleep(0.3)
@ -318,7 +318,7 @@ async def test_simple_zone_timeout_freeze_without_timeout_exeption() -> None:
"""Test a simple zone timeout freeze on a zone that does not have a timeout set."""
timeout = TimeoutManager()
with pytest.raises(TimeoutError):
with pytest.raises(TimeoutError): # noqa: PT012
async with timeout.async_timeout(0.1):
with suppress(RuntimeError):
async with timeout.async_freeze("test"):
@ -331,7 +331,7 @@ async def test_simple_zone_timeout_zone_with_timeout_exeption() -> None:
"""Test a simple zone timeout freeze on a zone that does not have a timeout set."""
timeout = TimeoutManager()
with pytest.raises(TimeoutError):
with pytest.raises(TimeoutError): # noqa: PT012
async with timeout.async_timeout(0.1):
with suppress(RuntimeError):
async with timeout.async_timeout(0.3, "test"):

View File

@ -596,10 +596,8 @@ async def test_loading_actual_file_with_syntax_error(
hass: HomeAssistant, try_both_loaders
) -> None:
"""Test loading a real file with syntax errors."""
fixture_path = pathlib.Path(__file__).parent.joinpath("fixtures", "bad.yaml.txt")
with pytest.raises(HomeAssistantError):
fixture_path = pathlib.Path(__file__).parent.joinpath(
"fixtures", "bad.yaml.txt"
)
await hass.async_add_executor_job(load_yaml_config_file, fixture_path)