diff --git a/pyproject.toml b/pyproject.toml index 23ebd376469..da08e9cee84 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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. diff --git a/tests/components/advantage_air/test_climate.py b/tests/components/advantage_air/test_climate.py index 66f8f869ae1..fc9aaade634 100644 --- a/tests/components/advantage_air/test_climate.py +++ b/tests/components/advantage_air/test_climate.py @@ -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() diff --git a/tests/components/alexa/test_smart_home.py b/tests/components/alexa/test_smart_home.py index fa8d7a2c9fb..43d92f1a533 100644 --- a/tests/components/alexa/test_smart_home.py +++ b/tests/components/alexa/test_smart_home.py @@ -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: diff --git a/tests/components/august/test_lock.py b/tests/components/august/test_lock.py index a0912e48378..a79ee7ffbf1 100644 --- a/tests/components/august/test_lock.py +++ b/tests/components/august/test_lock.py @@ -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: diff --git a/tests/components/blue_current/test_init.py b/tests/components/blue_current/test_init.py index 723dd993006..b740e6c91f9 100644 --- a/tests/components/blue_current/test_init.py +++ b/tests/components/blue_current/test_init.py @@ -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) diff --git a/tests/components/bond/test_fan.py b/tests/components/bond/test_fan.py index 6a0160fbec9..6a7ec6d1615 100644 --- a/tests/components/bond/test_fan.py +++ b/tests/components/bond/test_fan.py @@ -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: diff --git a/tests/components/bond/test_light.py b/tests/components/bond/test_light.py index 37cd82fc321..ce245c838ba 100644 --- a/tests/components/bond/test_light.py +++ b/tests/components/bond/test_light.py @@ -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: diff --git a/tests/components/bond/test_switch.py b/tests/components/bond/test_switch.py index 3d3ad663656..3155ec0b167 100644 --- a/tests/components/bond/test_switch.py +++ b/tests/components/bond/test_switch.py @@ -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: diff --git a/tests/components/cloudflare/test_init.py b/tests/components/cloudflare/test_init.py index 9d96b437733..3b2a6803566 100644 --- a/tests/components/cloudflare/test_init.py +++ b/tests/components/cloudflare/test_init.py @@ -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() diff --git a/tests/components/color_extractor/test_service.py b/tests/components/color_extractor/test_service.py index 6ad4830c2c4..941a0710067 100644 --- a/tests/components/color_extractor/test_service.py +++ b/tests/components/color_extractor/test_service.py @@ -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) diff --git a/tests/components/deconz/test_services.py b/tests/components/deconz/test_services.py index 6ce3081e3c4..9c5c21bc0ff 100644 --- a/tests/components/deconz/test_services.py +++ b/tests/components/deconz/test_services.py @@ -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( diff --git a/tests/components/demo/test_camera.py b/tests/components/demo/test_camera.py index ea115e72f72..ecbd3fecee3 100644 --- a/tests/components/demo/test_camera.py +++ b/tests/components/demo/test_camera.py @@ -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: diff --git a/tests/components/demo/test_fan.py b/tests/components/demo/test_fan.py index bd42ae3a953..bf6b8479a12 100644 --- a/tests/components/demo/test_fan.py +++ b/tests/components/demo/test_fan.py @@ -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" diff --git a/tests/components/devolo_home_network/test_button.py b/tests/components/devolo_home_network/test_button.py index 1097c0271cb..b2d410b03f9 100644 --- a/tests/components/devolo_home_network/test_button.py +++ b/tests/components/devolo_home_network/test_button.py @@ -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) diff --git a/tests/components/enphase_envoy/test_config_flow.py b/tests/components/enphase_envoy/test_config_flow.py index 667c769fbbb..7e1808ffa52 100644 --- a/tests/components/enphase_envoy/test_config_flow.py +++ b/tests/components/enphase_envoy/test_config_flow.py @@ -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( diff --git a/tests/components/esphome/test_voice_assistant.py b/tests/components/esphome/test_voice_assistant.py index 701ce76a207..bcd49f91c03 100644 --- a/tests/components/esphome/test_voice_assistant.py +++ b/tests/components/esphome/test_voice_assistant.py @@ -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( diff --git a/tests/components/fan/test_init.py b/tests/components/fan/test_init.py index e6bcc5542bd..2f1b583d7f2 100644 --- a/tests/components/fan/test_init.py +++ b/tests/components/fan/test_init.py @@ -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") diff --git a/tests/components/flo/test_services.py b/tests/components/flo/test_services.py index c65aa7937ee..d8837d9c6b6 100644 --- a/tests/components/flo/test_services.py +++ b/tests/components/flo/test_services.py @@ -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 diff --git a/tests/components/google_assistant/test_button.py b/tests/components/google_assistant/test_button.py index 11ca77bf733..6fdb94a5610 100644 --- a/tests/components/google_assistant/test_button.py +++ b/tests/components/google_assistant/test_button.py @@ -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", diff --git a/tests/components/google_assistant/test_trait.py b/tests/components/google_assistant/test_trait.py index de0b8b3da4e..4d5f438831a 100644 --- a/tests/components/google_assistant/test_trait.py +++ b/tests/components/google_assistant/test_trait.py @@ -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}, {} ) diff --git a/tests/components/google_generative_ai_conversation/test_init.py b/tests/components/google_generative_ai_conversation/test_init.py index a3926338b20..7afa9b4a31e 100644 --- a/tests/components/google_generative_ai_conversation/test_init.py +++ b/tests/components/google_generative_ai_conversation/test_init.py @@ -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( diff --git a/tests/components/heos/test_init.py b/tests/components/heos/test_init.py index fd453c70ebf..9341c8fbace 100644 --- a/tests/components/heos/test_init.py +++ b/tests/components/heos/test_init.py @@ -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() diff --git a/tests/components/home_connect/test_init.py b/tests/components/home_connect/test_init.py index 6c12f5b6738..10e7d8ca911 100644 --- a/tests/components/home_connect/test_init.py +++ b/tests/components/home_connect/test_init.py @@ -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 diff --git a/tests/components/homeassistant/test_init.py b/tests/components/homeassistant/test_init.py index 84319df2888..d090da280a0 100644 --- a/tests/components/homeassistant/test_init.py +++ b/tests/components/homeassistant/test_init.py @@ -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() diff --git a/tests/components/homeassistant/test_scene.py b/tests/components/homeassistant/test_scene.py index a1a532db162..3055f6b21b1 100644 --- a/tests/components/homeassistant/test_scene.py +++ b/tests/components/homeassistant/test_scene.py @@ -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 diff --git a/tests/components/homekit/test_type_media_players.py b/tests/components/homekit/test_type_media_players.py index b17f16231af..fb7233e5262 100644 --- a/tests/components/homekit/test_type_media_players.py +++ b/tests/components/homekit/test_type_media_players.py @@ -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() diff --git a/tests/components/homekit/test_type_remote.py b/tests/components/homekit/test_type_remote.py index 988950c64a8..bd4ead58a7b 100644 --- a/tests/components/homekit/test_type_remote.py +++ b/tests/components/homekit/test_type_remote.py @@ -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() diff --git a/tests/components/iaqualink/test_utils.py b/tests/components/iaqualink/test_utils.py index b9aba93523c..7a7b213f1a7 100644 --- a/tests/components/iaqualink/test_utils.py +++ b/tests/components/iaqualink/test_utils.py @@ -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()) diff --git a/tests/components/knx/test_services.py b/tests/components/knx/test_services.py index b95ab985093..7f748af5ceb 100644 --- a/tests/components/knx/test_services.py +++ b/tests/components/knx/test_services.py @@ -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" diff --git a/tests/components/lametric/test_button.py b/tests/components/lametric/test_button.py index e755329b93d..a6cdca5b426 100644 --- a/tests/components/lametric/test_button.py +++ b/tests/components/lametric/test_button.py @@ -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 diff --git a/tests/components/lametric/test_number.py b/tests/components/lametric/test_number.py index d5466abbd41..681abf850d2 100644 --- a/tests/components/lametric/test_number.py +++ b/tests/components/lametric/test_number.py @@ -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 diff --git a/tests/components/lametric/test_select.py b/tests/components/lametric/test_select.py index bd7bc775714..6b3fa291e9c 100644 --- a/tests/components/lametric/test_select.py +++ b/tests/components/lametric/test_select.py @@ -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 diff --git a/tests/components/lametric/test_switch.py b/tests/components/lametric/test_switch.py index b81428bb402..367d5605e06 100644 --- a/tests/components/lametric/test_switch.py +++ b/tests/components/lametric/test_switch.py @@ -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 diff --git a/tests/components/matter/test_door_lock.py b/tests/components/matter/test_door_lock.py index a44b5929f65..7f6abeff62b 100644 --- a/tests/components/matter/test_door_lock.py +++ b/tests/components/matter/test_door_lock.py @@ -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", diff --git a/tests/components/maxcube/test_maxcube_climate.py b/tests/components/maxcube/test_maxcube_climate.py index e1e7dc57c47..48e616f8fd2 100644 --- a/tests/components/maxcube/test_maxcube_climate.py +++ b/tests/components/maxcube/test_maxcube_climate.py @@ -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( diff --git a/tests/components/media_player/test_intent.py b/tests/components/media_player/test_intent.py index df47296d90c..9ddf50d04f4 100644 --- a/tests/components/media_player/test_intent.py +++ b/tests/components/media_player/test_intent.py @@ -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) diff --git a/tests/components/motioneye/test_camera.py b/tests/components/motioneye/test_camera.py index 048ae19217a..0f3a7d6f904 100644 --- a/tests/components/motioneye/test_camera.py +++ b/tests/components/motioneye/test_camera.py @@ -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: diff --git a/tests/components/mqtt/test_alarm_control_panel.py b/tests/components/mqtt/test_alarm_control_panel.py index df226de7002..a90e71cebe5 100644 --- a/tests/components/mqtt/test_alarm_control_panel.py +++ b/tests/components/mqtt/test_alarm_control_panel.py @@ -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 diff --git a/tests/components/mqtt/test_climate.py b/tests/components/mqtt/test_climate.py index ba5c15bd4ff..2bf78e59e42 100644 --- a/tests/components/mqtt/test_climate.py +++ b/tests/components/mqtt/test_climate.py @@ -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( diff --git a/tests/components/myuplink/test_number.py b/tests/components/myuplink/test_number.py index 899b2302b3c..273c35ab749 100644 --- a/tests/components/myuplink/test_number.py +++ b/tests/components/myuplink/test_number.py @@ -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( diff --git a/tests/components/myuplink/test_switch.py b/tests/components/myuplink/test_switch.py index efbc2c88371..5e309e7152e 100644 --- a/tests/components/myuplink/test_switch.py +++ b/tests/components/myuplink/test_switch.py @@ -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( diff --git a/tests/components/nest/test_climate.py b/tests/components/nest/test_climate.py index 05ce5ad80f1..88847759a16 100644 --- a/tests/components/nest/test_climate.py +++ b/tests/components/nest/test_climate.py @@ -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) diff --git a/tests/components/netatmo/test_climate.py b/tests/components/netatmo/test_climate.py index b25f78b5e2f..4b908580346 100644 --- a/tests/components/netatmo/test_climate.py +++ b/tests/components/netatmo/test_climate.py @@ -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( diff --git a/tests/components/nibe_heatpump/test_climate.py b/tests/components/nibe_heatpump/test_climate.py index e40b197f58c..073e142f7ff 100644 --- a/tests/components/nibe_heatpump/test_climate.py +++ b/tests/components/nibe_heatpump/test_climate.py @@ -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 == [] diff --git a/tests/components/notify/test_legacy.py b/tests/components/notify/test_legacy.py index 71424beeda9..cc2192461ae 100644 --- a/tests/components/notify/test_legacy.py +++ b/tests/components/notify/test_legacy.py @@ -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']" diff --git a/tests/components/numato/test_init.py b/tests/components/numato/test_init.py index 1e84813df94..35dd102ec9e 100644 --- a/tests/components/numato/test_init.py +++ b/tests/components/numato/test_init.py @@ -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) diff --git a/tests/components/octoprint/test_button.py b/tests/components/octoprint/test_button.py index 7f272f9927e..cf9008d8b58 100644 --- a/tests/components/octoprint/test_button.py +++ b/tests/components/octoprint/test_button.py @@ -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: diff --git a/tests/components/peco/test_config_flow.py b/tests/components/peco/test_config_flow.py index 112d160fa81..16a193139b4 100644 --- a/tests/components/peco/test_config_flow.py +++ b/tests/components/peco/test_config_flow.py @@ -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: diff --git a/tests/components/pilight/test_init.py b/tests/components/pilight/test_init.py index 621d002bb62..7c7c39d5616 100644 --- a/tests/components/pilight/test_init.py +++ b/tests/components/pilight/test_init.py @@ -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) diff --git a/tests/components/plex/test_media_search.py b/tests/components/plex/test_media_search.py index 5578ecd2550..8219cbe27b6 100644 --- a/tests/components/plex/test_media_search.py +++ b/tests/components/plex/test_media_search.py @@ -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, ) diff --git a/tests/components/plex/test_playback.py b/tests/components/plex/test_playback.py index 33c8b130749..183a779c940 100644 --- a/tests/components/plex/test_playback.py +++ b/tests/components/plex/test_playback.py @@ -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 diff --git a/tests/components/powerwall/test_switch.py b/tests/components/powerwall/test_switch.py index fdcdd5150ed..b01f60210a6 100644 --- a/tests/components/powerwall/test_switch.py +++ b/tests/components/powerwall/test_switch.py @@ -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, diff --git a/tests/components/prosegur/test_camera.py b/tests/components/prosegur/test_camera.py index ed503d676ff..9cce5d484d4 100644 --- a/tests/components/prosegur/test_camera.py +++ b/tests/components/prosegur/test_camera.py @@ -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( diff --git a/tests/components/rainbird/test_switch.py b/tests/components/rainbird/test_switch.py index 1352a4a633d..c2f8fa29ca3 100644 --- a/tests/components/rainbird/test_switch.py +++ b/tests/components/rainbird/test_switch.py @@ -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( diff --git a/tests/components/recorder/test_backup.py b/tests/components/recorder/test_backup.py index d181c449bbf..08fbef01bdd 100644 --- a/tests/components/recorder/test_backup.py +++ b/tests/components/recorder/test_backup.py @@ -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 diff --git a/tests/components/recorder/test_init.py b/tests/components/recorder/test_init.py index c8cd2807c2e..bb449cf279a 100644 --- a/tests/components/recorder/test_init.py +++ b/tests/components/recorder/test_init.py @@ -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() diff --git a/tests/components/ring/test_siren.py b/tests/components/ring/test_siren.py index 7d3f673b61f..695b54c3971 100644 --- a/tests/components/ring/test_siren.py +++ b/tests/components/ring/test_siren.py @@ -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( diff --git a/tests/components/sharkiq/test_vacuum.py b/tests/components/sharkiq/test_vacuum.py index edf27101d6e..e5154008f56 100644 --- a/tests/components/sharkiq/test_vacuum.py +++ b/tests/components/sharkiq/test_vacuum.py @@ -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) diff --git a/tests/components/shelly/test_update.py b/tests/components/shelly/test_update.py index 2b233170254..9b779da093e 100644 --- a/tests/components/shelly/test_update.py +++ b/tests/components/shelly/test_update.py @@ -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") diff --git a/tests/components/signal_messenger/test_notify.py b/tests/components/signal_messenger/test_notify.py index e2f76d54c87..012de07df0e 100644 --- a/tests/components/signal_messenger/test_notify.py +++ b/tests/components/signal_messenger/test_notify.py @@ -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 diff --git a/tests/components/smtp/test_notify.py b/tests/components/smtp/test_notify.py index 15be7b66d27..901d7e547fe 100644 --- a/tests/components/smtp/test_notify.py +++ b/tests/components/smtp/test_notify.py @@ -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 ( diff --git a/tests/components/stream/test_worker.py b/tests/components/stream/test_worker.py index 0d47a63a000..c8f3f22196f 100644 --- a/tests/components/stream/test_worker.py +++ b/tests/components/stream/test_worker.py @@ -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}" diff --git a/tests/components/subaru/test_lock.py b/tests/components/subaru/test_lock.py index 34bbd7da9e2..c954634cf63 100644 --- a/tests/components/subaru/test_lock.py +++ b/tests/components/subaru/test_lock.py @@ -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() diff --git a/tests/components/tado/test_service.py b/tests/components/tado/test_service.py index 759470cb5ea..994f135199f 100644 --- a/tests/components/tado/test_service.py +++ b/tests/components/tado/test_service.py @@ -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) diff --git a/tests/components/teslemetry/test_climate.py b/tests/components/teslemetry/test_climate.py index edb10872139..0e21533083c 100644 --- a/tests/components/teslemetry/test_climate.py +++ b/tests/components/teslemetry/test_climate.py @@ -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() diff --git a/tests/components/tessie/common.py b/tests/components/tessie/common.py index 7182e28837a..d4fc002ba25 100644 --- a/tests/components/tessie/common.py +++ b/tests/components/tessie/common.py @@ -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/" diff --git a/tests/components/tessie/test_climate.py b/tests/components/tessie/test_climate.py index df86f0b2986..bc688e1ca70 100644 --- a/tests/components/tessie/test_climate.py +++ b/tests/components/tessie/test_climate.py @@ -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 diff --git a/tests/components/tessie/test_cover.py b/tests/components/tessie/test_cover.py index ebf4c503110..b0e3d770ced 100644 --- a/tests/components/tessie/test_cover.py +++ b/tests/components/tessie/test_cover.py @@ -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"] diff --git a/tests/components/tessie/test_select.py b/tests/components/tessie/test_select.py index 7f79dbe3297..f9526bf0a47 100644 --- a/tests/components/tessie/test_select.py +++ b/tests/components/tessie/test_select.py @@ -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 diff --git a/tests/components/tibber/test_notify.py b/tests/components/tibber/test_notify.py index 2e157e9415a..69af92c4d5d 100644 --- a/tests/components/tibber/test_notify.py +++ b/tests/components/tibber/test_notify.py @@ -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, + ) diff --git a/tests/components/timer/test_init.py b/tests/components/timer/test_init.py index 854ba10fe9f..95baa07eaa9 100644 --- a/tests/components/timer/test_init.py +++ b/tests/components/timer/test_init.py @@ -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, diff --git a/tests/components/totalconnect/test_button.py b/tests/components/totalconnect/test_button.py index 03b08316be2..80de004be1d 100644 --- a/tests/components/totalconnect/test_button.py +++ b/tests/components/totalconnect/test_button.py @@ -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( diff --git a/tests/components/wilight/test_switch.py b/tests/components/wilight/test_switch.py index 8b3f2225c4b..7140a0780ef 100644 --- a/tests/components/wilight/test_switch.py +++ b/tests/components/wilight/test_switch.py @@ -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" diff --git a/tests/components/wled/test_button.py b/tests/components/wled/test_button.py index ef662fb4ded..b3061e6594a 100644 --- a/tests/components/wled/test_button.py +++ b/tests/components/wled/test_button.py @@ -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")) diff --git a/tests/components/zha/test_climate.py b/tests/components/zha/test_climate.py index 16563f62e06..cac5ef66937 100644 --- a/tests/components/zha/test_climate.py +++ b/tests/components/zha/test_climate.py @@ -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: diff --git a/tests/components/zha/test_discover.py b/tests/components/zha/test_discover.py index 242dfe564ca..de30bc44b87 100644 --- a/tests/components/zha/test_discover.py +++ b/tests/components/zha/test_discover.py @@ -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 diff --git a/tests/hassfest/test_version.py b/tests/hassfest/test_version.py index 9cc1bbb11e5..bfe15018fe2 100644 --- a/tests/hassfest/test_version.py +++ b/tests/hassfest/test_version.py @@ -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" diff --git a/tests/helpers/test_area_registry.py b/tests/helpers/test_area_registry.py index 3824442c86e..e6d637d1a99 100644 --- a/tests/helpers/test_area_registry.py +++ b/tests/helpers/test_area_registry.py @@ -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" diff --git a/tests/helpers/test_condition.py b/tests/helpers/test_condition.py index 7f090f5e63b..ce114058453 100644 --- a/tests/helpers/test_condition.py +++ b/tests/helpers/test_condition.py @@ -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) diff --git a/tests/helpers/test_config_validation.py b/tests/helpers/test_config_validation.py index a22fcfcd3a6..f7c6a9bc99a 100644 --- a/tests/helpers/test_config_validation.py +++ b/tests/helpers/test_config_validation.py @@ -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: diff --git a/tests/helpers/test_entity_component.py b/tests/helpers/test_entity_component.py index e04e24018ee..39cb48eed0e 100644 --- a/tests/helpers/test_entity_component.py +++ b/tests/helpers/test_entity_component.py @@ -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 diff --git a/tests/helpers/test_entity_platform.py b/tests/helpers/test_entity_platform.py index fda66734431..55b5d98fd30 100644 --- a/tests/helpers/test_entity_platform.py +++ b/tests/helpers/test_entity_platform.py @@ -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 diff --git a/tests/helpers/test_normalized_name_base_registry.py b/tests/helpers/test_normalized_name_base_registry.py index 495d147340f..71f5c94285a 100644 --- a/tests/helpers/test_normalized_name_base_registry.py +++ b/tests/helpers/test_normalized_name_base_registry.py @@ -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 diff --git a/tests/helpers/test_script.py b/tests/helpers/test_script.py index 47221a77cee..08c196a04d3 100644 --- a/tests/helpers/test_script.py +++ b/tests/helpers/test_script.py @@ -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 diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 3d8dad1d23e..fd19ef019c2 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -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) diff --git a/tests/test_block_async_io.py b/tests/test_block_async_io.py index b7ecb034981..5a1e38d78cd 100644 --- a/tests/test_block_async_io.py +++ b/tests/test_block_async_io.py @@ -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 " diff --git a/tests/test_core.py b/tests/test_core.py index 6848d209d02..f8e96640fd1 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -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( diff --git a/tests/test_requirements.py b/tests/test_requirements.py index 73f3f54c3c4..161214160aa 100644 --- a/tests/test_requirements.py +++ b/tests/test_requirements.py @@ -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) == [ diff --git a/tests/util/test_timeout.py b/tests/util/test_timeout.py index d49008d608b..797c849db3c 100644 --- a/tests/util/test_timeout.py +++ b/tests/util/test_timeout.py @@ -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"): diff --git a/tests/util/yaml/test_init.py b/tests/util/yaml/test_init.py index ed6226693c2..b900bd9dbce 100644 --- a/tests/util/yaml/test_init.py +++ b/tests/util/yaml/test_init.py @@ -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)