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."""
with pytest.raises(HomeAssistantError):
mock_update.side_effect = ApiError
await add_mock_config(hass)
with pytest.raises(HomeAssistantError):
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()

View file

@ -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(
with patch(
"homeassistant.components.esphome.voice_assistant.tts.async_get_media_source_audio",
return_value=("wav", wav_bytes),
),
pytest.raises(ValueError),
):
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

@ -106,5 +106,4 @@ async def test_services(
},
blocking=True,
)
await hass.async_block_till_done()
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)
with pytest.raises(HomeAssistantError):
mock_sync_entities.return_value = 400
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
"button",
"press",

View file

@ -1782,7 +1782,6 @@ async def test_arm_disarm_arm_away(hass: HomeAssistant) -> None:
# Test with no secure_pin configured
with pytest.raises(error.SmartHomeError) as err:
trt = trait.ArmDisArmTrait(
hass,
State(
@ -1792,6 +1791,7 @@ async def test_arm_disarm_arm_away(hass: HomeAssistant) -> None:
),
BASIC_CONFIG,
)
with pytest.raises(error.SmartHomeError) as err:
await trt.execute(
trait.COMMAND_ARMDISARM,
BASIC_DATA,
@ -1845,7 +1845,6 @@ async def test_arm_disarm_arm_away(hass: HomeAssistant) -> None:
assert len(calls) == 1
# Test already armed
with pytest.raises(error.SmartHomeError) as err:
trt = trait.ArmDisArmTrait(
hass,
State(
@ -1855,6 +1854,7 @@ async def test_arm_disarm_arm_away(hass: HomeAssistant) -> None:
),
PIN_CONFIG,
)
with pytest.raises(error.SmartHomeError) as err:
await trt.execute(
trait.COMMAND_ARMDISARM,
PIN_DATA,
@ -1940,7 +1940,6 @@ async def test_arm_disarm_disarm(hass: HomeAssistant) -> None:
)
# Test without secure_pin configured
with pytest.raises(error.SmartHomeError) as err:
trt = trait.ArmDisArmTrait(
hass,
State(
@ -1950,6 +1949,7 @@ async def test_arm_disarm_disarm(hass: HomeAssistant) -> None:
),
BASIC_CONFIG,
)
with pytest.raises(error.SmartHomeError) as err:
await trt.execute(trait.COMMAND_ARMDISARM, BASIC_DATA, {"arm": False}, {})
assert len(calls) == 0
@ -1989,7 +1989,6 @@ async def test_arm_disarm_disarm(hass: HomeAssistant) -> None:
assert len(calls) == 1
# Test already disarmed
with pytest.raises(error.SmartHomeError) as err:
trt = trait.ArmDisArmTrait(
hass,
State(
@ -1999,12 +1998,11 @@ async def test_arm_disarm_disarm(hass: HomeAssistant) -> None:
),
PIN_CONFIG,
)
with pytest.raises(error.SmartHomeError) as err:
await trt.execute(trait.COMMAND_ARMDISARM, PIN_DATA, {"arm": False}, {})
assert len(calls) == 1
assert err.value.code == const.ERR_ALREADY_DISARMED
# Cancel arming after already armed will require pin
with pytest.raises(error.SmartHomeError) as err:
trt = trait.ArmDisArmTrait(
hass,
State(
@ -2014,6 +2012,9 @@ async def test_arm_disarm_disarm(hass: HomeAssistant) -> None:
),
PIN_CONFIG,
)
# Cancel arming after already armed will require pin
with pytest.raises(error.SmartHomeError) as err:
await trt.execute(
trait.COMMAND_ARMDISARM, PIN_DATA, {"arm": True, "cancel": True}, {}
)

View file

@ -94,15 +94,13 @@ 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")
)
with pytest.raises(
HomeAssistantError, match="Error generating content: None reason"
):
await hass.services.async_call(
"google_generative_ai_conversation",
"generate_content",
@ -120,13 +118,13 @@ 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
)
with pytest.raises(HomeAssistantError, match="Error generating content"):
await hass.services.async_call(
"google_generative_ai_conversation",
"generate_content",

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]
with pytest.raises(ValueError):
service_call["service_data"]["device_id"] = "DOES_NOT_EXISTS"
with pytest.raises(ValueError):
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(
@ -486,7 +485,7 @@ async def test_raises_when_db_upgrade_in_progress(
blocking=True,
)
assert "The system cannot" in caplog.text
assert "while a database upgrade in progress" in caplog.text
assert "while a database upgrade is in progress" in caplog.text
assert mock_async_migration_in_progress.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"
with pytest.raises(HomeAssistantError):
async_ex = async_raises(AqualinkServiceException)
with pytest.raises(HomeAssistantError):
await await_or_reraise(async_ex())

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

@ -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,15 +74,14 @@ async def test_api_failure(
) -> None:
"""Test handling of exception from API."""
with pytest.raises(HomeAssistantError):
mock_myuplink_client.async_set_device_points.side_effect = ClientError
with pytest.raises(HomeAssistantError):
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()

View file

@ -86,13 +86,12 @@ 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()

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,16 +57,14 @@ 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": [],
}
)
with pytest.raises(InvalidPrinterState):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
@ -118,16 +116,14 @@ 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": [],
}
)
with pytest.raises(InvalidPrinterState):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,

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,25 +250,25 @@ 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,
@ -277,7 +276,7 @@ async def test_media_lookups(
{
ATTR_ENTITY_ID: media_player_id,
ATTR_MEDIA_CONTENT_TYPE: MediaType.VIDEO,
ATTR_MEDIA_CONTENT_ID: payload,
ATTR_MEDIA_CONTENT_ID: '{"library_name": "Movies", "title": "Not a Movie"}',
},
True,
)
@ -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

@ -197,12 +197,13 @@ 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,
@ -210,7 +211,7 @@ async def test_media_player_playback(
{
ATTR_ENTITY_ID: media_player,
ATTR_MEDIA_CONTENT_TYPE: MediaType.MOVIE,
ATTR_MEDIA_CONTENT_ID: payload,
ATTR_MEDIA_CONTENT_ID: '{"library_name": "Movies", "title": "Movie" }',
},
True,
)

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."""
with pytest.raises(HomeAssistantError, match="Setting off-grid operation to"):
mock_powerwall.set_island_mode.side_effect = PowerwallError("Mock exception")
with pytest.raises(HomeAssistantError, match="Setting off-grid operation to"):
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,

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

@ -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."""
with pytest.raises(exception):
data = {ATTR_ENTITY_ID: VAC_ENTITY_ID, ATTR_ROOMS: room_list}
with pytest.raises(exception):
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,8 +341,9 @@ 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")
with pytest.raises(StreamWorkerError):
run_worker(hass, stream, STREAM_SOURCE)
await hass.async_block_till_done()
av_open.assert_called_once()
@ -768,8 +769,9 @@ 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")
with pytest.raises(StreamWorkerError) as err:
run_worker(hass, stream, stream_url)
await hass.async_block_till_done()
assert (

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()

View file

@ -155,7 +155,10 @@ async def test_invalid_error(hass: HomeAssistant) -> None:
blocking=True,
)
mock_on.assert_called_once()
assert error.from_exception == InvalidCommand
assert (
str(error.value)
== "Teslemetry command failed, The data request or command is unknown."
)
@pytest.mark.parametrize("response", COMMAND_ERRORS)
@ -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

@ -129,4 +129,4 @@ async def test_errors(hass: HomeAssistant) -> None:
blocking=True,
)
mock_set.assert_called_once()
assert error.from_exception == ERROR_UNKNOWN
assert error.value.__cause__ == ERROR_UNKNOWN

View file

@ -95,7 +95,7 @@ async def test_errors(hass: HomeAssistant) -> None:
blocking=True,
)
mock_set.assert_called_once()
assert error.from_exception == ERROR_UNKNOWN
assert error.value.__cause__ == ERROR_UNKNOWN
# Test setting cover open with unknown error
with (
@ -112,4 +112,4 @@ async def test_errors(hass: HomeAssistant) -> None:
blocking=True,
)
mock_set.assert_called_once()
assert str(error) == TEST_RESPONSE_ERROR["reason"]
assert str(error.value) == TEST_RESPONSE_ERROR["reason"]

View file

@ -67,4 +67,4 @@ async def test_errors(hass: HomeAssistant) -> None:
blocking=True,
)
mock_set.assert_called_once()
assert error.from_exception == ERROR_UNKNOWN
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"
await hass.services.async_call(
"notify",
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)
},
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

@ -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

@ -986,7 +986,6 @@ 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(
@ -1010,6 +1009,7 @@ async def test_quirks_v2_metadata_errors(
"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."""
with pytest.raises(vol.Invalid):
integration.manifest["version"] = "lorem_ipsum"
with pytest.raises(vol.Invalid):
CUSTOM_INTEGRATION_MANIFEST_SCHEMA(integration.manifest)
with pytest.raises(vol.Invalid):
integration.manifest["version"] = None
with pytest.raises(vol.Invalid):
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,7 +1104,7 @@ 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",
@ -1115,6 +1115,7 @@ async def test_state_raises(hass: HomeAssistant) -> None:
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,7 +1550,6 @@ 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",
@ -1561,10 +1561,10 @@ async def test_numeric_state_raises(hass: HomeAssistant) -> None:
test = await condition.async_from_config(hass, config)
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",
@ -1575,10 +1575,10 @@ async def test_numeric_state_raises(hass: HomeAssistant) -> None:
test = await condition.async_from_config(hass, config)
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",
@ -1589,18 +1589,18 @@ async def test_numeric_state_raises(hass: HomeAssistant) -> None:
test = await condition.async_from_config(hass, config)
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",
@ -1611,14 +1611,15 @@ async def test_numeric_state_raises(hass: HomeAssistant) -> None:
test = await condition.async_from_config(hass, config)
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"])

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
with pytest.raises(ValueError):
entry = NormalizedNameBaseRegistryEntry(
name="Hello World 2", normalized_name="helloworld2"
)
registry_items["key2"] = entry
with pytest.raises(ValueError):
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
with pytest.raises(asyncio.CancelledError):
task2.cancel()
with pytest.raises(asyncio.CancelledError):
await task2
assert script_obj.is_running
assert script_obj.runs == 2
with pytest.raises(asyncio.CancelledError):
task1.cancel()
with pytest.raises(asyncio.CancelledError):
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
with pytest.raises(TemplateError):
info = render_to_info(hass, "{{ device_attr(56, 'id') }}")
with pytest.raises(TemplateError):
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
with pytest.raises(TemplateError):
info = render_to_info(hass, "{{ is_device_attr(56, 'id', 'test') }}")
with pytest.raises(TemplateError):
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,6 +124,7 @@ async def test_protect_loop_importlib_import_module_non_integration(
),
):
block_async_io.enable()
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,6 +195,7 @@ async def test_protect_loop_importlib_import_module_in_integration(
),
):
block_async_io.enable()
with pytest.raises(ImportError):
importlib.import_module("not_loaded_module")
assert (

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)