From ad13a9295e61dcb475605b3fdc880069d423295c Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Sat, 27 Mar 2021 09:17:15 +0100 Subject: [PATCH] Merge multiple context managers in tests (#48146) --- tests/auth/test_init.py | 5 +- .../components/androidtv/test_media_player.py | 34 ++-- tests/components/apprise/test_notify.py | 13 +- tests/components/bond/common.py | 31 ++-- tests/components/device_tracker/test_init.py | 50 +++--- tests/components/elgato/test_light.py | 25 ++- tests/components/emulated_hue/test_init.py | 105 ++++++------ tests/components/enocean/test_config_flow.py | 30 ++-- tests/components/filter/test_sensor.py | 48 +++--- .../geo_json_events/test_geo_location.py | 91 +++++----- .../components/geo_rss_events/test_sensor.py | 85 ++++----- tests/components/graphite/test_init.py | 17 +- tests/components/hisense_aehw4a1/test_init.py | 69 ++++---- tests/components/history_stats/test_sensor.py | 22 ++- tests/components/influxdb/test_init.py | 15 +- tests/components/lyric/test_config_flow.py | 9 +- tests/components/melissa/test_climate.py | 75 ++++---- .../minecraft_server/test_config_flow.py | 161 ++++++++---------- tests/components/mqtt/test_light.py | 7 +- tests/components/mqtt/test_light_template.py | 65 ++++--- tests/components/pilight/test_init.py | 69 ++++---- .../signal_messenger/test_notify.py | 22 ++- tests/components/system_log/test_init.py | 25 ++- tests/components/zha/test_channels.py | 9 +- tests/components/zha/test_discover.py | 19 +-- tests/components/zwave/test_init.py | 45 +++-- .../helpers/test_config_entry_oauth2_flow.py | 7 +- tests/helpers/test_network.py | 5 +- tests/helpers/test_service.py | 31 ++-- tests/test_config_entries.py | 11 +- tests/test_requirements.py | 5 +- tests/util/test_async.py | 7 +- tests/util/yaml/test_init.py | 5 +- 33 files changed, 590 insertions(+), 627 deletions(-) diff --git a/tests/auth/test_init.py b/tests/auth/test_init.py index 4f34ce1d595..255fcac7694 100644 --- a/tests/auth/test_init.py +++ b/tests/auth/test_init.py @@ -501,9 +501,8 @@ async def test_refresh_token_provider_validation(mock_hass): with patch( "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", side_effect=InvalidAuthError("Invalid access"), - ) as call: - with pytest.raises(InvalidAuthError): - manager.async_create_access_token(refresh_token, ip) + ) as call, pytest.raises(InvalidAuthError): + manager.async_create_access_token(refresh_token, ip) call.assert_called_with(refresh_token, ip) diff --git a/tests/components/androidtv/test_media_player.py b/tests/components/androidtv/test_media_player.py index a9a803741b1..d72cf36438b 100644 --- a/tests/components/androidtv/test_media_player.py +++ b/tests/components/androidtv/test_media_player.py @@ -933,12 +933,11 @@ async def test_update_lock_not_acquired(hass): with patch( "androidtv.androidtv.androidtv_async.AndroidTVAsync.update", side_effect=LockNotAcquiredException, - ): - with patchers.patch_shell(SHELL_RESPONSE_STANDBY)[patch_key]: - await hass.helpers.entity_component.async_update_entity(entity_id) - state = hass.states.get(entity_id) - assert state is not None - assert state.state == STATE_OFF + ), patchers.patch_shell(SHELL_RESPONSE_STANDBY)[patch_key]: + await hass.helpers.entity_component.async_update_entity(entity_id) + state = hass.states.get(entity_id) + assert state is not None + assert state.state == STATE_OFF with patchers.patch_shell(SHELL_RESPONSE_STANDBY)[patch_key]: await hass.helpers.entity_component.async_update_entity(entity_id) @@ -1206,19 +1205,18 @@ async def test_connection_closed_on_ha_stop(hass): """Test that the ADB socket connection is closed when HA stops.""" patch_key, entity_id = _setup(CONFIG_ANDROIDTV_ADB_SERVER) - with patchers.PATCH_ADB_DEVICE_TCP, patchers.patch_connect(True)[patch_key]: - with patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key]: - assert await async_setup_component( - hass, DOMAIN, CONFIG_ANDROIDTV_ADB_SERVER - ) - await hass.async_block_till_done() + with patchers.PATCH_ADB_DEVICE_TCP, patchers.patch_connect(True)[ + patch_key + ], patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key]: + assert await async_setup_component(hass, DOMAIN, CONFIG_ANDROIDTV_ADB_SERVER) + await hass.async_block_till_done() - with patch( - "androidtv.androidtv.androidtv_async.AndroidTVAsync.adb_close" - ) as adb_close: - hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) - await hass.async_block_till_done() - assert adb_close.called + with patch( + "androidtv.androidtv.androidtv_async.AndroidTVAsync.adb_close" + ) as adb_close: + hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) + await hass.async_block_till_done() + assert adb_close.called async def test_exception(hass): diff --git a/tests/components/apprise/test_notify.py b/tests/components/apprise/test_notify.py index 8135f4e8e2c..3e539e73516 100644 --- a/tests/components/apprise/test_notify.py +++ b/tests/components/apprise/test_notify.py @@ -28,13 +28,14 @@ async def test_apprise_config_load_fail02(hass): BASE_COMPONENT: {"name": "test", "platform": "apprise", "config": "/path/"} } - with patch("apprise.Apprise.add", return_value=False): - with patch("apprise.AppriseConfig.add", return_value=True): - assert await async_setup_component(hass, BASE_COMPONENT, config) - await hass.async_block_till_done() + with patch("apprise.Apprise.add", return_value=False), patch( + "apprise.AppriseConfig.add", return_value=True + ): + assert await async_setup_component(hass, BASE_COMPONENT, config) + await hass.async_block_till_done() - # Test that our service failed to load - assert not hass.services.has_service(BASE_COMPONENT, "test") + # Test that our service failed to load + assert not hass.services.has_service(BASE_COMPONENT, "test") async def test_apprise_config_load_okay(hass, tmp_path): diff --git a/tests/components/bond/common.py b/tests/components/bond/common.py index d8adf134293..0791d002fed 100644 --- a/tests/components/bond/common.py +++ b/tests/components/bond/common.py @@ -72,20 +72,23 @@ async def setup_platform( ) mock_entry.add_to_hass(hass) - with patch("homeassistant.components.bond.PLATFORMS", [platform]): - with patch_bond_version(return_value=bond_version), patch_bond_bridge( - return_value=bridge - ), patch_bond_token(return_value=token), patch_bond_device_ids( - return_value=[bond_device_id] - ), patch_start_bpup(), patch_bond_device( - return_value=discovered_device - ), patch_bond_device_properties( - return_value=props - ), patch_bond_device_state( - return_value=state - ): - assert await async_setup_component(hass, BOND_DOMAIN, {}) - await hass.async_block_till_done() + with patch( + "homeassistant.components.bond.PLATFORMS", [platform] + ), patch_bond_version(return_value=bond_version), patch_bond_bridge( + return_value=bridge + ), patch_bond_token( + return_value=token + ), patch_bond_device_ids( + return_value=[bond_device_id] + ), patch_start_bpup(), patch_bond_device( + return_value=discovered_device + ), patch_bond_device_properties( + return_value=props + ), patch_bond_device_state( + return_value=state + ): + assert await async_setup_component(hass, BOND_DOMAIN, {}) + await hass.async_block_till_done() return mock_entry diff --git a/tests/components/device_tracker/test_init.py b/tests/components/device_tracker/test_init.py index d62e46255d7..af0c7658ac7 100644 --- a/tests/components/device_tracker/test_init.py +++ b/tests/components/device_tracker/test_init.py @@ -237,19 +237,18 @@ async def test_update_stale(hass, mock_device_tracker_conf): with patch( "homeassistant.components.device_tracker.legacy.dt_util.utcnow", return_value=register_time, - ): - with assert_setup_component(1, device_tracker.DOMAIN): - assert await async_setup_component( - hass, - device_tracker.DOMAIN, - { - device_tracker.DOMAIN: { - CONF_PLATFORM: "test", - device_tracker.CONF_CONSIDER_HOME: 59, - } - }, - ) - await hass.async_block_till_done() + ), assert_setup_component(1, device_tracker.DOMAIN): + assert await async_setup_component( + hass, + device_tracker.DOMAIN, + { + device_tracker.DOMAIN: { + CONF_PLATFORM: "test", + device_tracker.CONF_CONSIDER_HOME: 59, + } + }, + ) + await hass.async_block_till_done() assert hass.states.get("device_tracker.dev1").state == STATE_HOME @@ -458,19 +457,18 @@ async def test_see_passive_zone_state(hass, mock_device_tracker_conf): with patch( "homeassistant.components.device_tracker.legacy.dt_util.utcnow", return_value=register_time, - ): - with assert_setup_component(1, device_tracker.DOMAIN): - assert await async_setup_component( - hass, - device_tracker.DOMAIN, - { - device_tracker.DOMAIN: { - CONF_PLATFORM: "test", - device_tracker.CONF_CONSIDER_HOME: 59, - } - }, - ) - await hass.async_block_till_done() + ), assert_setup_component(1, device_tracker.DOMAIN): + assert await async_setup_component( + hass, + device_tracker.DOMAIN, + { + device_tracker.DOMAIN: { + CONF_PLATFORM: "test", + device_tracker.CONF_CONSIDER_HOME: 59, + } + }, + ) + await hass.async_block_till_done() state = hass.states.get("device_tracker.dev1") attrs = state.attributes diff --git a/tests/components/elgato/test_light.py b/tests/components/elgato/test_light.py index 48e6bd24625..6c4de76719f 100644 --- a/tests/components/elgato/test_light.py +++ b/tests/components/elgato/test_light.py @@ -93,17 +93,16 @@ async def test_light_unavailable( with patch( "homeassistant.components.elgato.light.Elgato.light", side_effect=ElgatoError, + ), patch( + "homeassistant.components.elgato.light.Elgato.state", + side_effect=ElgatoError, ): - with patch( - "homeassistant.components.elgato.light.Elgato.state", - side_effect=ElgatoError, - ): - await hass.services.async_call( - LIGHT_DOMAIN, - SERVICE_TURN_OFF, - {ATTR_ENTITY_ID: "light.frenck"}, - blocking=True, - ) - await hass.async_block_till_done() - state = hass.states.get("light.frenck") - assert state.state == STATE_UNAVAILABLE + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_OFF, + {ATTR_ENTITY_ID: "light.frenck"}, + blocking=True, + ) + await hass.async_block_till_done() + state = hass.states.get("light.frenck") + assert state.state == STATE_UNAVAILABLE diff --git a/tests/components/emulated_hue/test_init.py b/tests/components/emulated_hue/test_init.py index 6fa6d969539..8e8c0f41249 100644 --- a/tests/components/emulated_hue/test_init.py +++ b/tests/components/emulated_hue/test_init.py @@ -13,29 +13,30 @@ def test_config_google_home_entity_id_to_number(): with patch( "homeassistant.components.emulated_hue.load_json", return_value={"1": "light.test2"}, - ) as json_loader: - with patch("homeassistant.components.emulated_hue.save_json") as json_saver: - number = conf.entity_id_to_number("light.test") - assert number == "2" + ) as json_loader, patch( + "homeassistant.components.emulated_hue.save_json" + ) as json_saver: + number = conf.entity_id_to_number("light.test") + assert number == "2" - assert json_saver.mock_calls[0][1][1] == { - "1": "light.test2", - "2": "light.test", - } + assert json_saver.mock_calls[0][1][1] == { + "1": "light.test2", + "2": "light.test", + } - assert json_saver.call_count == 1 - assert json_loader.call_count == 1 + assert json_saver.call_count == 1 + assert json_loader.call_count == 1 - number = conf.entity_id_to_number("light.test") - assert number == "2" - assert json_saver.call_count == 1 + number = conf.entity_id_to_number("light.test") + assert number == "2" + assert json_saver.call_count == 1 - number = conf.entity_id_to_number("light.test2") - assert number == "1" - assert json_saver.call_count == 1 + number = conf.entity_id_to_number("light.test2") + assert number == "1" + assert json_saver.call_count == 1 - entity_id = conf.number_to_entity_id("1") - assert entity_id == "light.test2" + entity_id = conf.number_to_entity_id("1") + assert entity_id == "light.test2" def test_config_google_home_entity_id_to_number_altered(): @@ -47,28 +48,29 @@ def test_config_google_home_entity_id_to_number_altered(): with patch( "homeassistant.components.emulated_hue.load_json", return_value={"21": "light.test2"}, - ) as json_loader: - with patch("homeassistant.components.emulated_hue.save_json") as json_saver: - number = conf.entity_id_to_number("light.test") - assert number == "22" - assert json_saver.call_count == 1 - assert json_loader.call_count == 1 + ) as json_loader, patch( + "homeassistant.components.emulated_hue.save_json" + ) as json_saver: + number = conf.entity_id_to_number("light.test") + assert number == "22" + assert json_saver.call_count == 1 + assert json_loader.call_count == 1 - assert json_saver.mock_calls[0][1][1] == { - "21": "light.test2", - "22": "light.test", - } + assert json_saver.mock_calls[0][1][1] == { + "21": "light.test2", + "22": "light.test", + } - number = conf.entity_id_to_number("light.test") - assert number == "22" - assert json_saver.call_count == 1 + number = conf.entity_id_to_number("light.test") + assert number == "22" + assert json_saver.call_count == 1 - number = conf.entity_id_to_number("light.test2") - assert number == "21" - assert json_saver.call_count == 1 + number = conf.entity_id_to_number("light.test2") + assert number == "21" + assert json_saver.call_count == 1 - entity_id = conf.number_to_entity_id("21") - assert entity_id == "light.test2" + entity_id = conf.number_to_entity_id("21") + assert entity_id == "light.test2" def test_config_google_home_entity_id_to_number_empty(): @@ -79,25 +81,26 @@ def test_config_google_home_entity_id_to_number_empty(): with patch( "homeassistant.components.emulated_hue.load_json", return_value={} - ) as json_loader: - with patch("homeassistant.components.emulated_hue.save_json") as json_saver: - number = conf.entity_id_to_number("light.test") - assert number == "1" - assert json_saver.call_count == 1 - assert json_loader.call_count == 1 + ) as json_loader, patch( + "homeassistant.components.emulated_hue.save_json" + ) as json_saver: + number = conf.entity_id_to_number("light.test") + assert number == "1" + assert json_saver.call_count == 1 + assert json_loader.call_count == 1 - assert json_saver.mock_calls[0][1][1] == {"1": "light.test"} + assert json_saver.mock_calls[0][1][1] == {"1": "light.test"} - number = conf.entity_id_to_number("light.test") - assert number == "1" - assert json_saver.call_count == 1 + number = conf.entity_id_to_number("light.test") + assert number == "1" + assert json_saver.call_count == 1 - number = conf.entity_id_to_number("light.test2") - assert number == "2" - assert json_saver.call_count == 2 + number = conf.entity_id_to_number("light.test2") + assert number == "2" + assert json_saver.call_count == 2 - entity_id = conf.number_to_entity_id("2") - assert entity_id == "light.test2" + entity_id = conf.number_to_entity_id("2") + assert entity_id == "light.test2" def test_config_alexa_entity_id_to_number(): diff --git a/tests/components/enocean/test_config_flow.py b/tests/components/enocean/test_config_flow.py index 4cea2a4fb9b..60a20af5eae 100644 --- a/tests/components/enocean/test_config_flow.py +++ b/tests/components/enocean/test_config_flow.py @@ -73,13 +73,14 @@ async def test_detection_flow_with_custom_path(hass): USER_PROVIDED_PATH = EnOceanFlowHandler.MANUAL_PATH_VALUE FAKE_DONGLE_PATH = "/fake/dongle" - with patch(DONGLE_VALIDATE_PATH_METHOD, Mock(return_value=True)): - with patch(DONGLE_DETECT_METHOD, Mock(return_value=[FAKE_DONGLE_PATH])): - result = await hass.config_entries.flow.async_init( - DOMAIN, - context={"source": "detect"}, - data={CONF_DEVICE: USER_PROVIDED_PATH}, - ) + with patch(DONGLE_VALIDATE_PATH_METHOD, Mock(return_value=True)), patch( + DONGLE_DETECT_METHOD, Mock(return_value=[FAKE_DONGLE_PATH]) + ): + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": "detect"}, + data={CONF_DEVICE: USER_PROVIDED_PATH}, + ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "manual" @@ -90,13 +91,14 @@ async def test_detection_flow_with_invalid_path(hass): USER_PROVIDED_PATH = "/invalid/path" FAKE_DONGLE_PATH = "/fake/dongle" - with patch(DONGLE_VALIDATE_PATH_METHOD, Mock(return_value=False)): - with patch(DONGLE_DETECT_METHOD, Mock(return_value=[FAKE_DONGLE_PATH])): - result = await hass.config_entries.flow.async_init( - DOMAIN, - context={"source": "detect"}, - data={CONF_DEVICE: USER_PROVIDED_PATH}, - ) + with patch(DONGLE_VALIDATE_PATH_METHOD, Mock(return_value=False)), patch( + DONGLE_DETECT_METHOD, Mock(return_value=[FAKE_DONGLE_PATH]) + ): + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": "detect"}, + data={CONF_DEVICE: USER_PROVIDED_PATH}, + ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "detect" diff --git a/tests/components/filter/test_sensor.py b/tests/components/filter/test_sensor.py index b787fc0235c..b8cdaf3c88a 100644 --- a/tests/components/filter/test_sensor.py +++ b/tests/components/filter/test_sensor.py @@ -116,24 +116,23 @@ async def test_chain_history(hass, values, missing=False): with patch( "homeassistant.components.history.state_changes_during_period", return_value=fake_states, + ), patch( + "homeassistant.components.history.get_last_state_changes", + return_value=fake_states, ): - with patch( - "homeassistant.components.history.get_last_state_changes", - return_value=fake_states, - ): - with assert_setup_component(1, "sensor"): - assert await async_setup_component(hass, "sensor", config) - await hass.async_block_till_done() + with assert_setup_component(1, "sensor"): + assert await async_setup_component(hass, "sensor", config) + await hass.async_block_till_done() - for value in values: - hass.states.async_set(config["sensor"]["entity_id"], value.state) - await hass.async_block_till_done() + for value in values: + hass.states.async_set(config["sensor"]["entity_id"], value.state) + await hass.async_block_till_done() - state = hass.states.get("sensor.test") - if missing: - assert state.state == "18.05" - else: - assert state.state == "17.05" + state = hass.states.get("sensor.test") + if missing: + assert state.state == "18.05" + else: + assert state.state == "17.05" async def test_source_state_none(hass, values): @@ -234,18 +233,17 @@ async def test_history_time(hass): with patch( "homeassistant.components.history.state_changes_during_period", return_value=fake_states, + ), patch( + "homeassistant.components.history.get_last_state_changes", + return_value=fake_states, ): - with patch( - "homeassistant.components.history.get_last_state_changes", - return_value=fake_states, - ): - with assert_setup_component(1, "sensor"): - assert await async_setup_component(hass, "sensor", config) - await hass.async_block_till_done() - + with assert_setup_component(1, "sensor"): + assert await async_setup_component(hass, "sensor", config) await hass.async_block_till_done() - state = hass.states.get("sensor.test") - assert state.state == "18.0" + + await hass.async_block_till_done() + state = hass.states.get("sensor.test") + assert state.state == "18.0" async def test_setup(hass): diff --git a/tests/components/geo_json_events/test_geo_location.py b/tests/components/geo_json_events/test_geo_location.py index 75f41bb93c0..9d68e3d4973 100644 --- a/tests/components/geo_json_events/test_geo_location.py +++ b/tests/components/geo_json_events/test_geo_location.py @@ -198,60 +198,59 @@ async def test_setup_race_condition(hass, legacy_patchable_time): utcnow = dt_util.utcnow() with patch("homeassistant.util.dt.utcnow", return_value=utcnow), patch( "geojson_client.generic_feed.GenericFeed" - ) as mock_feed: - with assert_setup_component(1, geo_location.DOMAIN): - assert await async_setup_component(hass, geo_location.DOMAIN, CONFIG) - await hass.async_block_till_done() + ) as mock_feed, assert_setup_component(1, geo_location.DOMAIN): + assert await async_setup_component(hass, geo_location.DOMAIN, CONFIG) + await hass.async_block_till_done() - mock_feed.return_value.update.return_value = "OK", [mock_entry_1] + mock_feed.return_value.update.return_value = "OK", [mock_entry_1] - # Artificially trigger update. - hass.bus.async_fire(EVENT_HOMEASSISTANT_START) - # Collect events. - await hass.async_block_till_done() + # Artificially trigger update. + hass.bus.async_fire(EVENT_HOMEASSISTANT_START) + # Collect events. + await hass.async_block_till_done() - all_states = hass.states.async_all() - assert len(all_states) == 1 - assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 1 - assert len(hass.data[DATA_DISPATCHER][update_signal]) == 1 + all_states = hass.states.async_all() + assert len(all_states) == 1 + assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 1 + assert len(hass.data[DATA_DISPATCHER][update_signal]) == 1 - # Simulate an update - empty data, removes all entities - mock_feed.return_value.update.return_value = "ERROR", None - async_fire_time_changed(hass, utcnow + SCAN_INTERVAL) - await hass.async_block_till_done() + # Simulate an update - empty data, removes all entities + mock_feed.return_value.update.return_value = "ERROR", None + async_fire_time_changed(hass, utcnow + SCAN_INTERVAL) + await hass.async_block_till_done() - all_states = hass.states.async_all() - assert len(all_states) == 0 - assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 0 - assert len(hass.data[DATA_DISPATCHER][update_signal]) == 0 + all_states = hass.states.async_all() + assert len(all_states) == 0 + assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 0 + assert len(hass.data[DATA_DISPATCHER][update_signal]) == 0 - # Simulate an update - 1 entry - mock_feed.return_value.update.return_value = "OK", [mock_entry_1] - async_fire_time_changed(hass, utcnow + 2 * SCAN_INTERVAL) - await hass.async_block_till_done() + # Simulate an update - 1 entry + mock_feed.return_value.update.return_value = "OK", [mock_entry_1] + async_fire_time_changed(hass, utcnow + 2 * SCAN_INTERVAL) + await hass.async_block_till_done() - all_states = hass.states.async_all() - assert len(all_states) == 1 - assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 1 - assert len(hass.data[DATA_DISPATCHER][update_signal]) == 1 + all_states = hass.states.async_all() + assert len(all_states) == 1 + assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 1 + assert len(hass.data[DATA_DISPATCHER][update_signal]) == 1 - # Simulate an update - 1 entry - mock_feed.return_value.update.return_value = "OK", [mock_entry_1] - async_fire_time_changed(hass, utcnow + 3 * SCAN_INTERVAL) - await hass.async_block_till_done() + # Simulate an update - 1 entry + mock_feed.return_value.update.return_value = "OK", [mock_entry_1] + async_fire_time_changed(hass, utcnow + 3 * SCAN_INTERVAL) + await hass.async_block_till_done() - all_states = hass.states.async_all() - assert len(all_states) == 1 - assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 1 - assert len(hass.data[DATA_DISPATCHER][update_signal]) == 1 + all_states = hass.states.async_all() + assert len(all_states) == 1 + assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 1 + assert len(hass.data[DATA_DISPATCHER][update_signal]) == 1 - # Simulate an update - empty data, removes all entities - mock_feed.return_value.update.return_value = "ERROR", None - async_fire_time_changed(hass, utcnow + 4 * SCAN_INTERVAL) - await hass.async_block_till_done() + # Simulate an update - empty data, removes all entities + mock_feed.return_value.update.return_value = "ERROR", None + async_fire_time_changed(hass, utcnow + 4 * SCAN_INTERVAL) + await hass.async_block_till_done() - all_states = hass.states.async_all() - assert len(all_states) == 0 - # Ensure that delete and update signal targets are now empty. - assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 0 - assert len(hass.data[DATA_DISPATCHER][update_signal]) == 0 + all_states = hass.states.async_all() + assert len(all_states) == 0 + # Ensure that delete and update signal targets are now empty. + assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 0 + assert len(hass.data[DATA_DISPATCHER][update_signal]) == 0 diff --git a/tests/components/geo_rss_events/test_sensor.py b/tests/components/geo_rss_events/test_sensor.py index ead81e5c5a8..95fb89301a9 100644 --- a/tests/components/geo_rss_events/test_sensor.py +++ b/tests/components/geo_rss_events/test_sensor.py @@ -68,54 +68,55 @@ async def test_setup(hass, mock_feed): utcnow = dt_util.utcnow() # Patching 'utcnow' to gain more control over the timed update. - with patch("homeassistant.util.dt.utcnow", return_value=utcnow): - with assert_setup_component(1, sensor.DOMAIN): - assert await async_setup_component(hass, sensor.DOMAIN, VALID_CONFIG) - # Artificially trigger update. - hass.bus.fire(EVENT_HOMEASSISTANT_START) - # Collect events. - await hass.async_block_till_done() + with patch( + "homeassistant.util.dt.utcnow", return_value=utcnow + ), assert_setup_component(1, sensor.DOMAIN): + assert await async_setup_component(hass, sensor.DOMAIN, VALID_CONFIG) + # Artificially trigger update. + hass.bus.fire(EVENT_HOMEASSISTANT_START) + # Collect events. + await hass.async_block_till_done() - all_states = hass.states.async_all() - assert len(all_states) == 1 + all_states = hass.states.async_all() + assert len(all_states) == 1 - state = hass.states.get("sensor.event_service_any") - assert state is not None - assert state.name == "Event Service Any" - assert int(state.state) == 2 - assert state.attributes == { - ATTR_FRIENDLY_NAME: "Event Service Any", - ATTR_UNIT_OF_MEASUREMENT: "Events", - ATTR_ICON: "mdi:alert", - "Title 1": "16km", - "Title 2": "20km", - } + state = hass.states.get("sensor.event_service_any") + assert state is not None + assert state.name == "Event Service Any" + assert int(state.state) == 2 + assert state.attributes == { + ATTR_FRIENDLY_NAME: "Event Service Any", + ATTR_UNIT_OF_MEASUREMENT: "Events", + ATTR_ICON: "mdi:alert", + "Title 1": "16km", + "Title 2": "20km", + } - # Simulate an update - empty data, but successful update, - # so no changes to entities. - mock_feed.return_value.update.return_value = "OK_NO_DATA", None - async_fire_time_changed(hass, utcnow + geo_rss_events.SCAN_INTERVAL) - await hass.async_block_till_done() + # Simulate an update - empty data, but successful update, + # so no changes to entities. + mock_feed.return_value.update.return_value = "OK_NO_DATA", None + async_fire_time_changed(hass, utcnow + geo_rss_events.SCAN_INTERVAL) + await hass.async_block_till_done() - all_states = hass.states.async_all() - assert len(all_states) == 1 - state = hass.states.get("sensor.event_service_any") - assert int(state.state) == 2 + all_states = hass.states.async_all() + assert len(all_states) == 1 + state = hass.states.get("sensor.event_service_any") + assert int(state.state) == 2 - # Simulate an update - empty data, removes all entities - mock_feed.return_value.update.return_value = "ERROR", None - async_fire_time_changed(hass, utcnow + 2 * geo_rss_events.SCAN_INTERVAL) - await hass.async_block_till_done() + # Simulate an update - empty data, removes all entities + mock_feed.return_value.update.return_value = "ERROR", None + async_fire_time_changed(hass, utcnow + 2 * geo_rss_events.SCAN_INTERVAL) + await hass.async_block_till_done() - all_states = hass.states.async_all() - assert len(all_states) == 1 - state = hass.states.get("sensor.event_service_any") - assert int(state.state) == 0 - assert state.attributes == { - ATTR_FRIENDLY_NAME: "Event Service Any", - ATTR_UNIT_OF_MEASUREMENT: "Events", - ATTR_ICON: "mdi:alert", - } + all_states = hass.states.async_all() + assert len(all_states) == 1 + state = hass.states.get("sensor.event_service_any") + assert int(state.state) == 0 + assert state.attributes == { + ATTR_FRIENDLY_NAME: "Event Service Any", + ATTR_UNIT_OF_MEASUREMENT: "Events", + ATTR_ICON: "mdi:alert", + } async def test_setup_with_categories(hass, mock_feed): diff --git a/tests/components/graphite/test_init.py b/tests/components/graphite/test_init.py index b7f5071813e..23a25b1623e 100644 --- a/tests/components/graphite/test_init.py +++ b/tests/components/graphite/test_init.py @@ -220,11 +220,12 @@ class TestGraphite(unittest.TestCase): runs.append(1) return event - with mock.patch.object(self.gf, "_queue") as mock_queue: - with mock.patch.object(self.gf, "_report_attributes") as mock_r: - mock_queue.get.side_effect = fake_get - self.gf.run() - # Twice for two events, once for the stop - assert mock_queue.task_done.call_count == 3 - assert mock_r.call_count == 1 - assert mock_r.call_args == mock.call("entity", event.data["new_state"]) + with mock.patch.object(self.gf, "_queue") as mock_queue, mock.patch.object( + self.gf, "_report_attributes" + ) as mock_r: + mock_queue.get.side_effect = fake_get + self.gf.run() + # Twice for two events, once for the stop + assert mock_queue.task_done.call_count == 3 + assert mock_r.call_count == 1 + assert mock_r.call_args == mock.call("entity", event.data["new_state"]) diff --git a/tests/components/hisense_aehw4a1/test_init.py b/tests/components/hisense_aehw4a1/test_init.py index 4add153ee94..ef99c3d1c96 100644 --- a/tests/components/hisense_aehw4a1/test_init.py +++ b/tests/components/hisense_aehw4a1/test_init.py @@ -13,24 +13,21 @@ async def test_creating_entry_sets_up_climate_discovery(hass): with patch( "homeassistant.components.hisense_aehw4a1.config_flow.AehW4a1.discovery", return_value=["1.2.3.4"], - ): - with patch( - "homeassistant.components.hisense_aehw4a1.climate.async_setup_entry", - return_value=True, - ) as mock_setup: - result = await hass.config_entries.flow.async_init( - hisense_aehw4a1.DOMAIN, context={"source": config_entries.SOURCE_USER} - ) + ), patch( + "homeassistant.components.hisense_aehw4a1.climate.async_setup_entry", + return_value=True, + ) as mock_setup: + result = await hass.config_entries.flow.async_init( + hisense_aehw4a1.DOMAIN, context={"source": config_entries.SOURCE_USER} + ) - # Confirmation form - assert result["type"] == data_entry_flow.RESULT_TYPE_FORM + # Confirmation form + assert result["type"] == data_entry_flow.RESULT_TYPE_FORM - result = await hass.config_entries.flow.async_configure( - result["flow_id"], {} - ) - assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY + result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) + assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY - await hass.async_block_till_done() + await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 @@ -40,17 +37,16 @@ async def test_configuring_hisense_w4a1_create_entry(hass): with patch( "homeassistant.components.hisense_aehw4a1.config_flow.AehW4a1.check", return_value=True, - ): - with patch( - "homeassistant.components.hisense_aehw4a1.async_setup_entry", - return_value=True, - ) as mock_setup: - await async_setup_component( - hass, - hisense_aehw4a1.DOMAIN, - {"hisense_aehw4a1": {"ip_address": ["1.2.3.4"]}}, - ) - await hass.async_block_till_done() + ), patch( + "homeassistant.components.hisense_aehw4a1.async_setup_entry", + return_value=True, + ) as mock_setup: + await async_setup_component( + hass, + hisense_aehw4a1.DOMAIN, + {"hisense_aehw4a1": {"ip_address": ["1.2.3.4"]}}, + ) + await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 @@ -60,17 +56,16 @@ async def test_configuring_hisense_w4a1_not_creates_entry_for_device_not_found(h with patch( "homeassistant.components.hisense_aehw4a1.config_flow.AehW4a1.check", side_effect=exceptions.ConnectionError, - ): - with patch( - "homeassistant.components.hisense_aehw4a1.async_setup_entry", - return_value=True, - ) as mock_setup: - await async_setup_component( - hass, - hisense_aehw4a1.DOMAIN, - {"hisense_aehw4a1": {"ip_address": ["1.2.3.4"]}}, - ) - await hass.async_block_till_done() + ), patch( + "homeassistant.components.hisense_aehw4a1.async_setup_entry", + return_value=True, + ) as mock_setup: + await async_setup_component( + hass, + hisense_aehw4a1.DOMAIN, + {"hisense_aehw4a1": {"ip_address": ["1.2.3.4"]}}, + ) + await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 0 diff --git a/tests/components/history_stats/test_sensor.py b/tests/components/history_stats/test_sensor.py index 62e3959f4ad..f074003ab86 100644 --- a/tests/components/history_stats/test_sensor.py +++ b/tests/components/history_stats/test_sensor.py @@ -162,12 +162,11 @@ class TestHistoryStatsSensor(unittest.TestCase): with patch( "homeassistant.components.history.state_changes_during_period", return_value=fake_states, - ): - with patch("homeassistant.components.history.get_state", return_value=None): - sensor1.update() - sensor2.update() - sensor3.update() - sensor4.update() + ), patch("homeassistant.components.history.get_state", return_value=None): + sensor1.update() + sensor2.update() + sensor3.update() + sensor4.update() assert sensor1.state == 0.5 assert sensor2.state is None @@ -246,12 +245,11 @@ class TestHistoryStatsSensor(unittest.TestCase): with patch( "homeassistant.components.history.state_changes_during_period", return_value=fake_states, - ): - with patch("homeassistant.components.history.get_state", return_value=None): - sensor1.update() - sensor2.update() - sensor3.update() - sensor4.update() + ), patch("homeassistant.components.history.get_state", return_value=None): + sensor1.update() + sensor2.update() + sensor3.update() + sensor4.update() assert sensor1.state == 0.5 assert sensor2.state is None diff --git a/tests/components/influxdb/test_init.py b/tests/components/influxdb/test_init.py index 6c560eec5e7..e589a42e99a 100644 --- a/tests/components/influxdb/test_init.py +++ b/tests/components/influxdb/test_init.py @@ -254,14 +254,15 @@ async def test_setup_config_ssl( config = {"influxdb": config_base.copy()} config["influxdb"].update(config_ext) - with patch("os.access", return_value=True): - with patch("os.path.isfile", return_value=True): - assert await async_setup_component(hass, influxdb.DOMAIN, config) - await hass.async_block_till_done() + with patch("os.access", return_value=True), patch( + "os.path.isfile", return_value=True + ): + assert await async_setup_component(hass, influxdb.DOMAIN, config) + await hass.async_block_till_done() - assert hass.bus.listen.called - assert hass.bus.listen.call_args_list[0][0][0] == EVENT_STATE_CHANGED - assert expected_client_args.items() <= mock_client.call_args.kwargs.items() + assert hass.bus.listen.called + assert hass.bus.listen.call_args_list[0][0][0] == EVENT_STATE_CHANGED + assert expected_client_args.items() <= mock_client.call_args.kwargs.items() @pytest.mark.parametrize( diff --git a/tests/components/lyric/test_config_flow.py b/tests/components/lyric/test_config_flow.py index 78fd9013466..bfdd45f0f8e 100644 --- a/tests/components/lyric/test_config_flow.py +++ b/tests/components/lyric/test_config_flow.py @@ -90,11 +90,10 @@ async def test_full_flow( }, ) - with patch("homeassistant.components.lyric.api.ConfigEntryLyricClient"): - with patch( - "homeassistant.components.lyric.async_setup_entry", return_value=True - ) as mock_setup: - result = await hass.config_entries.flow.async_configure(result["flow_id"]) + with patch("homeassistant.components.lyric.api.ConfigEntryLyricClient"), patch( + "homeassistant.components.lyric.async_setup_entry", return_value=True + ) as mock_setup: + result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result["data"]["auth_implementation"] == DOMAIN diff --git a/tests/components/melissa/test_climate.py b/tests/components/melissa/test_climate.py index 1b53e2f8334..590c5149f9e 100644 --- a/tests/components/melissa/test_climate.py +++ b/tests/components/melissa/test_climate.py @@ -288,19 +288,18 @@ async def test_update(hass): """Test update.""" with patch( "homeassistant.components.melissa.climate._LOGGER.warning" - ) as mocked_warning: - with patch("homeassistant.components.melissa"): - api = melissa_mock() - device = (await api.async_fetch_devices())[_SERIAL] - thermostat = MelissaClimate(api, _SERIAL, device) - await thermostat.async_update() - assert thermostat.fan_mode == SPEED_LOW - assert thermostat.state == HVAC_MODE_HEAT - api.async_status = AsyncMock(side_effect=KeyError("boom")) - await thermostat.async_update() - mocked_warning.assert_called_once_with( - "Unable to update entity %s", thermostat.entity_id - ) + ) as mocked_warning, patch("homeassistant.components.melissa"): + api = melissa_mock() + device = (await api.async_fetch_devices())[_SERIAL] + thermostat = MelissaClimate(api, _SERIAL, device) + await thermostat.async_update() + assert thermostat.fan_mode == SPEED_LOW + assert thermostat.state == HVAC_MODE_HEAT + api.async_status = AsyncMock(side_effect=KeyError("boom")) + await thermostat.async_update() + mocked_warning.assert_called_once_with( + "Unable to update entity %s", thermostat.entity_id + ) async def test_melissa_op_to_hass(hass): @@ -333,35 +332,33 @@ async def test_hass_mode_to_melissa(hass): """Test for hass operations to melssa.""" with patch( "homeassistant.components.melissa.climate._LOGGER.warning" - ) as mocked_warning: - with patch("homeassistant.components.melissa"): - api = melissa_mock() - device = (await api.async_fetch_devices())[_SERIAL] - thermostat = MelissaClimate(api, _SERIAL, device) - assert thermostat.hass_mode_to_melissa(HVAC_MODE_FAN_ONLY) == 1 - assert thermostat.hass_mode_to_melissa(HVAC_MODE_HEAT) == 2 - assert thermostat.hass_mode_to_melissa(HVAC_MODE_COOL) == 3 - assert thermostat.hass_mode_to_melissa(HVAC_MODE_DRY) == 4 - thermostat.hass_mode_to_melissa("test") - mocked_warning.assert_called_once_with( - "Melissa have no setting for %s mode", "test" - ) + ) as mocked_warning, patch("homeassistant.components.melissa"): + api = melissa_mock() + device = (await api.async_fetch_devices())[_SERIAL] + thermostat = MelissaClimate(api, _SERIAL, device) + assert thermostat.hass_mode_to_melissa(HVAC_MODE_FAN_ONLY) == 1 + assert thermostat.hass_mode_to_melissa(HVAC_MODE_HEAT) == 2 + assert thermostat.hass_mode_to_melissa(HVAC_MODE_COOL) == 3 + assert thermostat.hass_mode_to_melissa(HVAC_MODE_DRY) == 4 + thermostat.hass_mode_to_melissa("test") + mocked_warning.assert_called_once_with( + "Melissa have no setting for %s mode", "test" + ) async def test_hass_fan_to_melissa(hass): """Test for translate melissa states to hass.""" with patch( "homeassistant.components.melissa.climate._LOGGER.warning" - ) as mocked_warning: - with patch("homeassistant.components.melissa"): - api = melissa_mock() - device = (await api.async_fetch_devices())[_SERIAL] - thermostat = MelissaClimate(api, _SERIAL, device) - assert thermostat.hass_fan_to_melissa("auto") == 0 - assert thermostat.hass_fan_to_melissa(SPEED_LOW) == 1 - assert thermostat.hass_fan_to_melissa(SPEED_MEDIUM) == 2 - assert thermostat.hass_fan_to_melissa(SPEED_HIGH) == 3 - thermostat.hass_fan_to_melissa("test") - mocked_warning.assert_called_once_with( - "Melissa have no setting for %s fan mode", "test" - ) + ) as mocked_warning, patch("homeassistant.components.melissa"): + api = melissa_mock() + device = (await api.async_fetch_devices())[_SERIAL] + thermostat = MelissaClimate(api, _SERIAL, device) + assert thermostat.hass_fan_to_melissa("auto") == 0 + assert thermostat.hass_fan_to_melissa(SPEED_LOW) == 1 + assert thermostat.hass_fan_to_melissa(SPEED_MEDIUM) == 2 + assert thermostat.hass_fan_to_melissa(SPEED_HIGH) == 3 + thermostat.hass_fan_to_melissa("test") + mocked_warning.assert_called_once_with( + "Melissa have no setting for %s fan mode", "test" + ) diff --git a/tests/components/minecraft_server/test_config_flow.py b/tests/components/minecraft_server/test_config_flow.py index 2f3b7781ecf..9fcea3261ee 100644 --- a/tests/components/minecraft_server/test_config_flow.py +++ b/tests/components/minecraft_server/test_config_flow.py @@ -103,31 +103,27 @@ async def test_invalid_ip(hass: HomeAssistantType) -> None: async def test_same_host(hass: HomeAssistantType) -> None: """Test abort in case of same host name.""" - with patch( - "aiodns.DNSResolver.query", - side_effect=aiodns.error.DNSError, + with patch("aiodns.DNSResolver.query", side_effect=aiodns.error.DNSError,), patch( + "mcstatus.server.MinecraftServer.status", + return_value=PingResponse(STATUS_RESPONSE_RAW), ): - with patch( - "mcstatus.server.MinecraftServer.status", - return_value=PingResponse(STATUS_RESPONSE_RAW), - ): - unique_id = "mc.dummyserver.com-25565" - config_data = { - CONF_NAME: DEFAULT_NAME, - CONF_HOST: "mc.dummyserver.com", - CONF_PORT: DEFAULT_PORT, - } - mock_config_entry = MockConfigEntry( - domain=DOMAIN, unique_id=unique_id, data=config_data - ) - mock_config_entry.add_to_hass(hass) + unique_id = "mc.dummyserver.com-25565" + config_data = { + CONF_NAME: DEFAULT_NAME, + CONF_HOST: "mc.dummyserver.com", + CONF_PORT: DEFAULT_PORT, + } + mock_config_entry = MockConfigEntry( + domain=DOMAIN, unique_id=unique_id, data=config_data + ) + mock_config_entry.add_to_hass(hass) - result = await hass.config_entries.flow.async_init( - DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT - ) + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT + ) - assert result["type"] == RESULT_TYPE_ABORT - assert result["reason"] == "already_configured" + assert result["type"] == RESULT_TYPE_ABORT + assert result["reason"] == "already_configured" async def test_port_too_small(hass: HomeAssistantType) -> None: @@ -163,93 +159,80 @@ async def test_connection_failed(hass: HomeAssistantType) -> None: with patch( "aiodns.DNSResolver.query", side_effect=aiodns.error.DNSError, - ): - with patch("mcstatus.server.MinecraftServer.status", side_effect=OSError): - result = await hass.config_entries.flow.async_init( - DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT - ) + ), patch("mcstatus.server.MinecraftServer.status", side_effect=OSError): + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT + ) - assert result["type"] == RESULT_TYPE_FORM - assert result["errors"] == {"base": "cannot_connect"} + assert result["type"] == RESULT_TYPE_FORM + assert result["errors"] == {"base": "cannot_connect"} async def test_connection_succeeded_with_srv_record(hass: HomeAssistantType) -> None: """Test config entry in case of a successful connection with a SRV record.""" - with patch( - "aiodns.DNSResolver.query", - return_value=SRV_RECORDS, + with patch("aiodns.DNSResolver.query", return_value=SRV_RECORDS,), patch( + "mcstatus.server.MinecraftServer.status", + return_value=PingResponse(STATUS_RESPONSE_RAW), ): - with patch( - "mcstatus.server.MinecraftServer.status", - return_value=PingResponse(STATUS_RESPONSE_RAW), - ): - result = await hass.config_entries.flow.async_init( - DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT_SRV - ) + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT_SRV + ) - assert result["type"] == RESULT_TYPE_CREATE_ENTRY - assert result["title"] == USER_INPUT_SRV[CONF_HOST] - assert result["data"][CONF_NAME] == USER_INPUT_SRV[CONF_NAME] - assert result["data"][CONF_HOST] == USER_INPUT_SRV[CONF_HOST] + assert result["type"] == RESULT_TYPE_CREATE_ENTRY + assert result["title"] == USER_INPUT_SRV[CONF_HOST] + assert result["data"][CONF_NAME] == USER_INPUT_SRV[CONF_NAME] + assert result["data"][CONF_HOST] == USER_INPUT_SRV[CONF_HOST] async def test_connection_succeeded_with_host(hass: HomeAssistantType) -> None: """Test config entry in case of a successful connection with a host name.""" - with patch( - "aiodns.DNSResolver.query", - side_effect=aiodns.error.DNSError, + with patch("aiodns.DNSResolver.query", side_effect=aiodns.error.DNSError,), patch( + "mcstatus.server.MinecraftServer.status", + return_value=PingResponse(STATUS_RESPONSE_RAW), ): - with patch( - "mcstatus.server.MinecraftServer.status", - return_value=PingResponse(STATUS_RESPONSE_RAW), - ): - result = await hass.config_entries.flow.async_init( - DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT - ) + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT + ) - assert result["type"] == RESULT_TYPE_CREATE_ENTRY - assert result["title"] == USER_INPUT[CONF_HOST] - assert result["data"][CONF_NAME] == USER_INPUT[CONF_NAME] - assert result["data"][CONF_HOST] == "mc.dummyserver.com" + assert result["type"] == RESULT_TYPE_CREATE_ENTRY + assert result["title"] == USER_INPUT[CONF_HOST] + assert result["data"][CONF_NAME] == USER_INPUT[CONF_NAME] + assert result["data"][CONF_HOST] == "mc.dummyserver.com" async def test_connection_succeeded_with_ip4(hass: HomeAssistantType) -> None: """Test config entry in case of a successful connection with an IPv4 address.""" - with patch("getmac.get_mac_address", return_value="01:23:45:67:89:ab"): - with patch( - "aiodns.DNSResolver.query", - side_effect=aiodns.error.DNSError, - ): - with patch( - "mcstatus.server.MinecraftServer.status", - return_value=PingResponse(STATUS_RESPONSE_RAW), - ): - result = await hass.config_entries.flow.async_init( - DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT_IPV4 - ) + with patch("getmac.get_mac_address", return_value="01:23:45:67:89:ab"), patch( + "aiodns.DNSResolver.query", + side_effect=aiodns.error.DNSError, + ), patch( + "mcstatus.server.MinecraftServer.status", + return_value=PingResponse(STATUS_RESPONSE_RAW), + ): + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT_IPV4 + ) - assert result["type"] == RESULT_TYPE_CREATE_ENTRY - assert result["title"] == USER_INPUT_IPV4[CONF_HOST] - assert result["data"][CONF_NAME] == USER_INPUT_IPV4[CONF_NAME] - assert result["data"][CONF_HOST] == "1.1.1.1" + assert result["type"] == RESULT_TYPE_CREATE_ENTRY + assert result["title"] == USER_INPUT_IPV4[CONF_HOST] + assert result["data"][CONF_NAME] == USER_INPUT_IPV4[CONF_NAME] + assert result["data"][CONF_HOST] == "1.1.1.1" async def test_connection_succeeded_with_ip6(hass: HomeAssistantType) -> None: """Test config entry in case of a successful connection with an IPv6 address.""" - with patch("getmac.get_mac_address", return_value="01:23:45:67:89:ab"): - with patch( - "aiodns.DNSResolver.query", - side_effect=aiodns.error.DNSError, - ): - with patch( - "mcstatus.server.MinecraftServer.status", - return_value=PingResponse(STATUS_RESPONSE_RAW), - ): - result = await hass.config_entries.flow.async_init( - DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT_IPV6 - ) + with patch("getmac.get_mac_address", return_value="01:23:45:67:89:ab"), patch( + "aiodns.DNSResolver.query", + side_effect=aiodns.error.DNSError, + ), patch( + "mcstatus.server.MinecraftServer.status", + return_value=PingResponse(STATUS_RESPONSE_RAW), + ): + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT_IPV6 + ) - assert result["type"] == RESULT_TYPE_CREATE_ENTRY - assert result["title"] == USER_INPUT_IPV6[CONF_HOST] - assert result["data"][CONF_NAME] == USER_INPUT_IPV6[CONF_NAME] - assert result["data"][CONF_HOST] == "::ffff:0101:0101" + assert result["type"] == RESULT_TYPE_CREATE_ENTRY + assert result["title"] == USER_INPUT_IPV6[CONF_HOST] + assert result["data"][CONF_NAME] == USER_INPUT_IPV6[CONF_NAME] + assert result["data"][CONF_HOST] == "::ffff:0101:0101" diff --git a/tests/components/mqtt/test_light.py b/tests/components/mqtt/test_light.py index 933f49ff823..00ff8b28b77 100644 --- a/tests/components/mqtt/test_light.py +++ b/tests/components/mqtt/test_light.py @@ -743,10 +743,9 @@ async def test_sending_mqtt_commands_and_optimistic(hass, mqtt_mock): with patch( "homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state", return_value=fake_state, - ): - with assert_setup_component(1, light.DOMAIN): - assert await async_setup_component(hass, light.DOMAIN, config) - await hass.async_block_till_done() + ), assert_setup_component(1, light.DOMAIN): + assert await async_setup_component(hass, light.DOMAIN, config) + await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_ON diff --git a/tests/components/mqtt/test_light_template.py b/tests/components/mqtt/test_light_template.py index 7b5d34edd69..3bbf14ca668 100644 --- a/tests/components/mqtt/test_light_template.py +++ b/tests/components/mqtt/test_light_template.py @@ -298,39 +298,38 @@ async def test_sending_mqtt_commands_and_optimistic(hass, mqtt_mock): with patch( "homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state", return_value=fake_state, - ): - with assert_setup_component(1, light.DOMAIN): - assert await async_setup_component( - hass, - light.DOMAIN, - { - light.DOMAIN: { - "platform": "mqtt", - "schema": "template", - "name": "test", - "command_topic": "test_light_rgb/set", - "command_on_template": "on," - "{{ brightness|d }}," - "{{ color_temp|d }}," - "{{ white_value|d }}," - "{{ red|d }}-" - "{{ green|d }}-" - "{{ blue|d }}", - "command_off_template": "off", - "effect_list": ["colorloop", "random"], - "optimistic": True, - "state_template": '{{ value.split(",")[0] }}', - "color_temp_template": '{{ value.split(",")[2] }}', - "white_value_template": '{{ value.split(",")[3] }}', - "red_template": '{{ value.split(",")[4].' 'split("-")[0] }}', - "green_template": '{{ value.split(",")[4].' 'split("-")[1] }}', - "blue_template": '{{ value.split(",")[4].' 'split("-")[2] }}', - "effect_template": '{{ value.split(",")[5] }}', - "qos": 2, - } - }, - ) - await hass.async_block_till_done() + ), assert_setup_component(1, light.DOMAIN): + assert await async_setup_component( + hass, + light.DOMAIN, + { + light.DOMAIN: { + "platform": "mqtt", + "schema": "template", + "name": "test", + "command_topic": "test_light_rgb/set", + "command_on_template": "on," + "{{ brightness|d }}," + "{{ color_temp|d }}," + "{{ white_value|d }}," + "{{ red|d }}-" + "{{ green|d }}-" + "{{ blue|d }}", + "command_off_template": "off", + "effect_list": ["colorloop", "random"], + "optimistic": True, + "state_template": '{{ value.split(",")[0] }}', + "color_temp_template": '{{ value.split(",")[2] }}', + "white_value_template": '{{ value.split(",")[3] }}', + "red_template": '{{ value.split(",")[4].' 'split("-")[0] }}', + "green_template": '{{ value.split(",")[4].' 'split("-")[1] }}', + "blue_template": '{{ value.split(",")[4].' 'split("-")[2] }}', + "effect_template": '{{ value.split(",")[5] }}', + "qos": 2, + } + }, + ) + await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_ON diff --git a/tests/components/pilight/test_init.py b/tests/components/pilight/test_init.py index 4b8b017f7fd..f3512a72ee3 100644 --- a/tests/components/pilight/test_init.py +++ b/tests/components/pilight/test_init.py @@ -64,29 +64,31 @@ class PilightDaemonSim: @patch("homeassistant.components.pilight._LOGGER.error") async def test_connection_failed_error(mock_error, hass): """Try to connect at 127.0.0.1:5001 with socket error.""" - with assert_setup_component(4): - with patch("pilight.pilight.Client", side_effect=socket.error) as mock_client: - assert not await async_setup_component( - hass, pilight.DOMAIN, {pilight.DOMAIN: {}} - ) - mock_client.assert_called_once_with( - host=pilight.DEFAULT_HOST, port=pilight.DEFAULT_PORT - ) - assert mock_error.call_count == 1 + with assert_setup_component(4), patch( + "pilight.pilight.Client", side_effect=socket.error + ) as mock_client: + assert not await async_setup_component( + hass, pilight.DOMAIN, {pilight.DOMAIN: {}} + ) + mock_client.assert_called_once_with( + host=pilight.DEFAULT_HOST, port=pilight.DEFAULT_PORT + ) + assert mock_error.call_count == 1 @patch("homeassistant.components.pilight._LOGGER.error") async def test_connection_timeout_error(mock_error, hass): """Try to connect at 127.0.0.1:5001 with socket timeout.""" - with assert_setup_component(4): - with patch("pilight.pilight.Client", side_effect=socket.timeout) as mock_client: - assert not await async_setup_component( - hass, pilight.DOMAIN, {pilight.DOMAIN: {}} - ) - mock_client.assert_called_once_with( - host=pilight.DEFAULT_HOST, port=pilight.DEFAULT_PORT - ) - assert mock_error.call_count == 1 + with assert_setup_component(4), patch( + "pilight.pilight.Client", side_effect=socket.timeout + ) as mock_client: + assert not await async_setup_component( + hass, pilight.DOMAIN, {pilight.DOMAIN: {}} + ) + mock_client.assert_called_once_with( + host=pilight.DEFAULT_HOST, port=pilight.DEFAULT_PORT + ) + assert mock_error.call_count == 1 @patch("pilight.pilight.Client", PilightDaemonSim) @@ -134,23 +136,22 @@ async def test_send_code(mock_pilight_error, hass): @patch("homeassistant.components.pilight._LOGGER.error") async def test_send_code_fail(mock_pilight_error, hass): """Check IOError exception error message.""" - with assert_setup_component(4): - with patch("pilight.pilight.Client.send_code", side_effect=IOError): - assert await async_setup_component( - hass, pilight.DOMAIN, {pilight.DOMAIN: {}} - ) + with assert_setup_component(4), patch( + "pilight.pilight.Client.send_code", side_effect=IOError + ): + assert await async_setup_component(hass, pilight.DOMAIN, {pilight.DOMAIN: {}}) - # Call with protocol info, should not give error - service_data = {"protocol": "test", "value": 42} - await hass.services.async_call( - pilight.DOMAIN, - pilight.SERVICE_NAME, - service_data=service_data, - blocking=True, - ) - await hass.async_block_till_done() - error_log_call = mock_pilight_error.call_args_list[-1] - assert "Pilight send failed" in str(error_log_call) + # Call with protocol info, should not give error + service_data = {"protocol": "test", "value": 42} + await hass.services.async_call( + pilight.DOMAIN, + pilight.SERVICE_NAME, + service_data=service_data, + blocking=True, + ) + await hass.async_block_till_done() + error_log_call = mock_pilight_error.call_args_list[-1] + assert "Pilight send failed" in str(error_log_call) @patch("homeassistant.components.pilight._LOGGER.error") diff --git a/tests/components/signal_messenger/test_notify.py b/tests/components/signal_messenger/test_notify.py index 4bb6cbdd197..d2dc93fea2e 100644 --- a/tests/components/signal_messenger/test_notify.py +++ b/tests/components/signal_messenger/test_notify.py @@ -87,12 +87,11 @@ class TestSignalMesssenger(unittest.TestCase): ) with self.assertLogs( "homeassistant.components.signal_messenger.notify", level="WARNING" - ) as context: - with tempfile.NamedTemporaryFile( - suffix=".png", prefix=os.path.basename(__file__) - ) as tf: - data = {"data": {"attachment": tf.name}} - self._signalmessenger.send_message(message, **data) + ) as context, tempfile.NamedTemporaryFile( + suffix=".png", prefix=os.path.basename(__file__) + ) as tf: + data = {"data": {"attachment": tf.name}} + self._signalmessenger.send_message(message, **data) self.assertIn( "The 'attachment' option is deprecated, please replace it with 'attachments'. This option will become invalid in version 0.108", context.output[0], @@ -117,12 +116,11 @@ class TestSignalMesssenger(unittest.TestCase): ) with self.assertLogs( "homeassistant.components.signal_messenger.notify", level="DEBUG" - ) as context: - with tempfile.NamedTemporaryFile( - suffix=".png", prefix=os.path.basename(__file__) - ) as tf: - data = {"data": {"attachments": [tf.name]}} - self._signalmessenger.send_message(message, **data) + ) as context, tempfile.NamedTemporaryFile( + suffix=".png", prefix=os.path.basename(__file__) + ) as tf: + data = {"data": {"attachments": [tf.name]}} + self._signalmessenger.send_message(message, **data) self.assertIn("Sending signal message", context.output[0]) self.assertTrue(mock.called) self.assertEqual(mock.call_count, 2) diff --git a/tests/components/system_log/test_init.py b/tests/components/system_log/test_init.py index 287e7139aff..ef54788d910 100644 --- a/tests/components/system_log/test_init.py +++ b/tests/components/system_log/test_init.py @@ -291,20 +291,19 @@ async def async_log_error_from_test_path(hass, path, sq): call_path = "internal_path.py" with patch.object( _LOGGER, "findCaller", MagicMock(return_value=(call_path, 0, None, None)) + ), patch( + "traceback.extract_stack", + MagicMock( + return_value=[ + get_frame("main_path/main.py"), + get_frame(path), + get_frame(call_path), + get_frame("venv_path/logging/log.py"), + ] + ), ): - with patch( - "traceback.extract_stack", - MagicMock( - return_value=[ - get_frame("main_path/main.py"), - get_frame(path), - get_frame(call_path), - get_frame("venv_path/logging/log.py"), - ] - ), - ): - _LOGGER.error("error message") - await _async_block_until_queue_empty(hass, sq) + _LOGGER.error("error message") + await _async_block_until_queue_empty(hass, sq) async def test_homeassistant_path(hass, simple_queue, hass_client): diff --git a/tests/components/zha/test_channels.py b/tests/components/zha/test_channels.py index 8a2ca1f05c3..ec5128fdb5e 100644 --- a/tests/components/zha/test_channels.py +++ b/tests/components/zha/test_channels.py @@ -415,10 +415,11 @@ async def test_ep_channels_configure(channel): claimed = {ch_1.id: ch_1, ch_2.id: ch_2, ch_3.id: ch_3} client_chans = {ch_4.id: ch_4, ch_5.id: ch_5} - with mock.patch.dict(ep_channels.claimed_channels, claimed, clear=True): - with mock.patch.dict(ep_channels.client_channels, client_chans, clear=True): - await ep_channels.async_configure() - await ep_channels.async_initialize(mock.sentinel.from_cache) + with mock.patch.dict( + ep_channels.claimed_channels, claimed, clear=True + ), mock.patch.dict(ep_channels.client_channels, client_chans, clear=True): + await ep_channels.async_configure() + await ep_channels.async_initialize(mock.sentinel.from_cache) for ch in [*claimed.values(), *client_chans.values()]: assert ch.async_initialize.call_count == 1 diff --git a/tests/components/zha/test_discover.py b/tests/components/zha/test_discover.py index c84c22e3251..cd0e75a7237 100644 --- a/tests/components/zha/test_discover.py +++ b/tests/components/zha/test_discover.py @@ -212,17 +212,14 @@ def test_discover_by_device_type_override(): with mock.patch( "homeassistant.components.zha.core.registries.ZHA_ENTITIES.get_entity", get_entity_mock, - ): - with mock.patch.dict(disc.PROBE._device_configs, overrides, clear=True): - disc.PROBE.discover_by_device_type(ep_channels) - assert get_entity_mock.call_count == 1 - assert ep_channels.claim_channels.call_count == 1 - assert ep_channels.claim_channels.call_args[0][0] is mock.sentinel.claimed - assert ep_channels.async_new_entity.call_count == 1 - assert ep_channels.async_new_entity.call_args[0][0] == zha_const.SWITCH - assert ( - ep_channels.async_new_entity.call_args[0][1] == mock.sentinel.entity_cls - ) + ), mock.patch.dict(disc.PROBE._device_configs, overrides, clear=True): + disc.PROBE.discover_by_device_type(ep_channels) + assert get_entity_mock.call_count == 1 + assert ep_channels.claim_channels.call_count == 1 + assert ep_channels.claim_channels.call_args[0][0] is mock.sentinel.claimed + assert ep_channels.async_new_entity.call_count == 1 + assert ep_channels.async_new_entity.call_args[0][0] == zha_const.SWITCH + assert ep_channels.async_new_entity.call_args[0][1] == mock.sentinel.entity_cls def test_discover_probe_single_cluster(): diff --git a/tests/components/zwave/test_init.py b/tests/components/zwave/test_init.py index e857675c545..6b1a6fe4f98 100644 --- a/tests/components/zwave/test_init.py +++ b/tests/components/zwave/test_init.py @@ -202,20 +202,17 @@ async def test_zwave_ready_wait(hass, mock_openzwave, zwave_setup): sleeps.append(duration) await asyncio_sleep(0) - with patch("homeassistant.components.zwave.dt_util.utcnow", new=utcnow): - with patch("asyncio.sleep", new=sleep): - with patch.object(zwave, "_LOGGER") as mock_logger: - hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED + with patch("homeassistant.components.zwave.dt_util.utcnow", new=utcnow), patch( + "asyncio.sleep", new=sleep + ), patch.object(zwave, "_LOGGER") as mock_logger: + hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED - await hass.async_start() + await hass.async_start() - assert len(sleeps) == const.NETWORK_READY_WAIT_SECS - assert mock_logger.warning.called - assert len(mock_logger.warning.mock_calls) == 1 - assert ( - mock_logger.warning.mock_calls[0][1][1] - == const.NETWORK_READY_WAIT_SECS - ) + assert len(sleeps) == const.NETWORK_READY_WAIT_SECS + assert mock_logger.warning.called + assert len(mock_logger.warning.mock_calls) == 1 + assert mock_logger.warning.mock_calls[0][1][1] == const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): @@ -341,19 +338,19 @@ async def test_unparsed_node_discovery(hass, mock_openzwave): sleeps.append(duration) await asyncio_sleep(0) - with patch("homeassistant.components.zwave.dt_util.utcnow", new=utcnow): - with patch("asyncio.sleep", new=sleep): - with patch.object(zwave, "_LOGGER") as mock_logger: - await hass.async_add_executor_job(mock_receivers[0], node) - await hass.async_block_till_done() + with patch("homeassistant.components.zwave.dt_util.utcnow", new=utcnow), patch( + "asyncio.sleep", new=sleep + ), patch.object(zwave, "_LOGGER") as mock_logger: + await hass.async_add_executor_job(mock_receivers[0], node) + await hass.async_block_till_done() - assert len(sleeps) == const.NODE_READY_WAIT_SECS - assert mock_logger.warning.called - assert len(mock_logger.warning.mock_calls) == 1 - assert mock_logger.warning.mock_calls[0][1][1:] == ( - 14, - const.NODE_READY_WAIT_SECS, - ) + assert len(sleeps) == const.NODE_READY_WAIT_SECS + assert mock_logger.warning.called + assert len(mock_logger.warning.mock_calls) == 1 + assert mock_logger.warning.mock_calls[0][1][1:] == ( + 14, + const.NODE_READY_WAIT_SECS, + ) assert hass.states.get("zwave.unknown_node_14").state == "unknown" diff --git a/tests/helpers/test_config_entry_oauth2_flow.py b/tests/helpers/test_config_entry_oauth2_flow.py index 3fad758b34b..b5257e635af 100644 --- a/tests/helpers/test_config_entry_oauth2_flow.py +++ b/tests/helpers/test_config_entry_oauth2_flow.py @@ -99,9 +99,10 @@ def test_inherit_enforces_domain_set(): """Return logger.""" return logging.getLogger(__name__) - with patch.dict(config_entries.HANDLERS, {TEST_DOMAIN: TestFlowHandler}): - with pytest.raises(TypeError): - TestFlowHandler() + with patch.dict( + config_entries.HANDLERS, {TEST_DOMAIN: TestFlowHandler} + ), pytest.raises(TypeError): + TestFlowHandler() async def test_abort_if_no_implementation(hass, flow_handler): diff --git a/tests/helpers/test_network.py b/tests/helpers/test_network.py index aad37e2fd49..05c72f10db5 100644 --- a/tests/helpers/test_network.py +++ b/tests/helpers/test_network.py @@ -377,9 +377,8 @@ async def test_get_cloud_url(hass: HomeAssistant): hass.components.cloud, "async_remote_ui_url", side_effect=cloud.CloudNotAvailable, - ): - with pytest.raises(NoURLAvailableError): - _get_cloud_url(hass) + ), pytest.raises(NoURLAvailableError): + _get_cloud_url(hass) async def test_get_external_url_cloud_fallback(hass: HomeAssistant): diff --git a/tests/helpers/test_service.py b/tests/helpers/test_service.py index 7a084fed9dd..d168c8b9cfc 100644 --- a/tests/helpers/test_service.py +++ b/tests/helpers/test_service.py @@ -561,22 +561,21 @@ async def test_call_context_target_specific_no_auth( hass, mock_handle_entity_call, mock_entities ): """Check targeting specific entities without auth.""" - with pytest.raises(exceptions.Unauthorized) as err: - with patch( - "homeassistant.auth.AuthManager.async_get_user", - return_value=Mock(permissions=PolicyPermissions({}, None)), - ): - await service.entity_service_call( - hass, - [Mock(entities=mock_entities)], - Mock(), - ha.ServiceCall( - "test_domain", - "test_service", - {"entity_id": "light.kitchen"}, - context=ha.Context(user_id="mock-id"), - ), - ) + with pytest.raises(exceptions.Unauthorized) as err, patch( + "homeassistant.auth.AuthManager.async_get_user", + return_value=Mock(permissions=PolicyPermissions({}, None)), + ): + await service.entity_service_call( + hass, + [Mock(entities=mock_entities)], + Mock(), + ha.ServiceCall( + "test_domain", + "test_service", + {"entity_id": "light.kitchen"}, + context=ha.Context(user_id="mock-id"), + ), + ) assert err.value.context.user_id == "mock-id" assert err.value.entity_id == "light.kitchen" diff --git a/tests/test_config_entries.py b/tests/test_config_entries.py index fbcc9d1bf14..b12601220c3 100644 --- a/tests/test_config_entries.py +++ b/tests/test_config_entries.py @@ -1221,12 +1221,11 @@ async def test_init_custom_integration(hass): None, {"name": "Hue", "dependencies": [], "requirements": [], "domain": "hue"}, ) - with pytest.raises(data_entry_flow.UnknownHandler): - with patch( - "homeassistant.loader.async_get_integration", - return_value=integration, - ): - await hass.config_entries.flow.async_init("bla") + with pytest.raises(data_entry_flow.UnknownHandler), patch( + "homeassistant.loader.async_get_integration", + return_value=integration, + ): + await hass.config_entries.flow.async_init("bla") async def test_support_entry_unload(hass): diff --git a/tests/test_requirements.py b/tests/test_requirements.py index 5f74e504de8..2c5b529467d 100644 --- a/tests/test_requirements.py +++ b/tests/test_requirements.py @@ -84,9 +84,8 @@ async def test_install_missing_package(hass): """Test an install attempt on an existing package.""" with patch( "homeassistant.util.package.install_package", return_value=False - ) as mock_inst: - with pytest.raises(RequirementsNotFound): - await async_process_requirements(hass, "test_component", ["hello==1.0.0"]) + ) as mock_inst, pytest.raises(RequirementsNotFound): + await async_process_requirements(hass, "test_component", ["hello==1.0.0"]) assert len(mock_inst.mock_calls) == 1 diff --git a/tests/util/test_async.py b/tests/util/test_async.py index d5564a90d0e..19413c57aaa 100644 --- a/tests/util/test_async.py +++ b/tests/util/test_async.py @@ -206,8 +206,9 @@ async def test_callback_is_always_scheduled(hass): callback = MagicMock() hasync.shutdown_run_callback_threadsafe(hass.loop) - with patch.object(hass.loop, "call_soon_threadsafe") as mock_call_soon_threadsafe: - with pytest.raises(RuntimeError): - hasync.run_callback_threadsafe(hass.loop, callback) + with patch.object( + hass.loop, "call_soon_threadsafe" + ) as mock_call_soon_threadsafe, pytest.raises(RuntimeError): + hasync.run_callback_threadsafe(hass.loop, callback) mock_call_soon_threadsafe.assert_called_once() diff --git a/tests/util/yaml/test_init.py b/tests/util/yaml/test_init.py index daa0275b7aa..2b86b3c50e9 100644 --- a/tests/util/yaml/test_init.py +++ b/tests/util/yaml/test_init.py @@ -65,9 +65,8 @@ def test_environment_variable_default(): def test_invalid_environment_variable(): """Test config file with no environment variable sat.""" conf = "password: !env_var PASSWORD" - with pytest.raises(HomeAssistantError): - with io.StringIO(conf) as file: - yaml_loader.yaml.load(file, Loader=yaml_loader.SafeLineLoader) + with pytest.raises(HomeAssistantError), io.StringIO(conf) as file: + yaml_loader.yaml.load(file, Loader=yaml_loader.SafeLineLoader) def test_include_yaml():