Enable Ruff SIM117 (#86783)

This commit is contained in:
Franck Nijhof 2023-01-27 11:52:49 +01:00 committed by GitHub
parent 57cf11f067
commit a79885ceaf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
25 changed files with 441 additions and 453 deletions

View File

@ -21,8 +21,9 @@ def get_cert(
"""Get the certificate for the host and port combination."""
ctx = ssl.create_default_context()
address = (host, port)
with socket.create_connection(address, timeout=TIMEOUT) as sock:
with ctx.wrap_socket(sock, server_hostname=address[0]) as ssock:
with socket.create_connection(address, timeout=TIMEOUT) as sock, ctx.wrap_socket(
sock, server_hostname=address[0]
) as ssock:
cert = ssock.getpeercert()
return cert

View File

@ -661,8 +661,9 @@ def _apply_update( # noqa: C901
),
table,
)
with contextlib.suppress(SQLAlchemyError):
with session_scope(session=session_maker()) as session:
with contextlib.suppress(SQLAlchemyError), session_scope(
session=session_maker()
) as session:
connection = session.connection()
connection.execute(
# Using LOCK=EXCLUSIVE to prevent
@ -804,8 +805,9 @@ def _apply_update( # noqa: C901
if engine.dialect.name == SupportedDialect.MYSQL:
# Ensure the row format is dynamic or the index
# unique will be too large
with contextlib.suppress(SQLAlchemyError):
with session_scope(session=session_maker()) as session:
with contextlib.suppress(SQLAlchemyError), session_scope(
session=session_maker()
) as session:
connection = session.connection()
# This is safe to run multiple times and fast
# since the table is small.

View File

@ -2422,8 +2422,9 @@ def correct_db_schema(
),
"statistics_meta",
)
with contextlib.suppress(SQLAlchemyError):
with session_scope(session=session_maker()) as session:
with contextlib.suppress(SQLAlchemyError), session_scope(
session=session_maker()
) as session:
connection = session.connection()
connection.execute(
# Using LOCK=EXCLUSIVE to prevent the database from corrupting

View File

@ -248,6 +248,7 @@ select = [
"F", # pyflakes/autoflake
"PGH004", # Use specific rule codes when using noqa
"SIM105", # Use contextlib.suppress({exception}) instead of try-except-pass
"SIM117", # Merge with-statements that use the same scope
"T20", # flake8-print
"UP", # pyupgrade
"W", # pycodestyle

View File

@ -24,8 +24,7 @@ from tests.common import MockConfigEntry
async def test_bluetooth_discovery(hass: HomeAssistant):
"""Test discovery via bluetooth with a valid device."""
with patch_async_ble_device_from_address(WAVE_SERVICE_INFO):
with patch_airthings_ble(
with patch_async_ble_device_from_address(WAVE_SERVICE_INFO), patch_airthings_ble(
AirthingsDevice(name="Airthings Wave+", identifier="123456")
):
result = await hass.config_entries.flow.async_init(
@ -66,8 +65,9 @@ async def test_bluetooth_discovery_airthings_ble_update_failed(
"""Test discovery via bluetooth but there's an exception from airthings-ble."""
for loop in [(Exception(), "unknown"), (BleakError(), "cannot_connect")]:
exc, reason = loop
with patch_async_ble_device_from_address(WAVE_SERVICE_INFO):
with patch_airthings_ble(side_effect=exc):
with patch_async_ble_device_from_address(
WAVE_SERVICE_INFO
), patch_airthings_ble(side_effect=exc):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_BLUETOOTH},
@ -99,9 +99,7 @@ async def test_user_setup(hass: HomeAssistant):
with patch(
"homeassistant.components.airthings_ble.config_flow.async_discovered_service_info",
return_value=[WAVE_SERVICE_INFO],
):
with patch_async_ble_device_from_address(WAVE_SERVICE_INFO):
with patch_airthings_ble(
), patch_async_ble_device_from_address(WAVE_SERVICE_INFO), patch_airthings_ble(
AirthingsDevice(name="Airthings Wave+", identifier="123456")
):
result = await hass.config_entries.flow.async_init(
@ -167,9 +165,9 @@ async def test_user_setup_unknown_error(hass: HomeAssistant):
with patch(
"homeassistant.components.airthings_ble.config_flow.async_discovered_service_info",
return_value=[WAVE_SERVICE_INFO],
), patch_async_ble_device_from_address(WAVE_SERVICE_INFO), patch_airthings_ble(
None, Exception()
):
with patch_async_ble_device_from_address(WAVE_SERVICE_INFO):
with patch_airthings_ble(None, Exception()):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
@ -183,9 +181,9 @@ async def test_user_setup_unable_to_connect(hass: HomeAssistant):
with patch(
"homeassistant.components.airthings_ble.config_flow.async_discovered_service_info",
return_value=[WAVE_SERVICE_INFO],
), patch_async_ble_device_from_address(WAVE_SERVICE_INFO), patch_airthings_ble(
side_effect=BleakError("An error")
):
with patch_async_ble_device_from_address(WAVE_SERVICE_INFO):
with patch_airthings_ble(side_effect=BleakError("An error")):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)

View File

@ -85,6 +85,5 @@ async def test_device(hass, config_entry, aioclient_mock_fixture, aioclient_mock
with patch(
"homeassistant.components.flo.device.FloDeviceDataUpdateCoordinator.send_presence_ping",
side_effect=RequestError,
):
with pytest.raises(UpdateFailed):
), pytest.raises(UpdateFailed):
await valve._async_update_data()

View File

@ -629,9 +629,7 @@ async def test_async_start_from_history_and_switch_to_watching_state_changes_sin
with patch(
"homeassistant.components.recorder.history.state_changes_during_period",
_fake_states,
):
with freeze_time(start_time):
), freeze_time(start_time):
await async_setup_component(
hass,
"sensor",
@ -729,9 +727,7 @@ async def test_async_start_from_history_and_switch_to_watching_state_changes_sin
with patch(
"homeassistant.components.recorder.history.state_changes_during_period",
_fake_states,
):
with freeze_time(start_time):
), freeze_time(start_time):
await async_setup_component(
hass,
"sensor",
@ -828,9 +824,7 @@ async def test_async_start_from_history_and_switch_to_watching_state_changes_mul
with patch(
"homeassistant.components.recorder.history.state_changes_during_period",
_fake_states,
):
with freeze_time(start_time):
), freeze_time(start_time):
await async_setup_component(
hass,
"sensor",

View File

@ -140,8 +140,7 @@ async def test_reauthentication_flow(
},
)
with patch("homeassistant.components.lyric.api.ConfigEntryLyricClient"):
with patch(
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"])

View File

@ -997,8 +997,9 @@ async def test_switch_failure(hass: HomeAssistant, exc: Exception) -> None:
"""Tests that the turn on/off service throws HomeAssistantError."""
await init_integration(hass)
with patch("homeassistant.components.nextdns.NextDns.set_setting", side_effect=exc):
with pytest.raises(HomeAssistantError):
with patch(
"homeassistant.components.nextdns.NextDns.set_setting", side_effect=exc
), pytest.raises(HomeAssistantError):
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,

View File

@ -29,8 +29,7 @@ async def test_unload_entry(hass: HomeAssistant) -> None:
outage_count=0,
customers_served=350394,
),
):
with patch(
), patch(
"peco.PecoOutageApi.get_map_alerts",
return_value=AlertResults(
alert_content="Testing 1234", alert_title="Testing 4321"

View File

@ -41,8 +41,7 @@ async def test_sensor_available(
outage_count=456,
customers_served=789,
),
):
with patch(
), patch(
"peco.PecoOutageApi.get_map_alerts",
return_value=AlertResults(
alert_content="Testing 1234", alert_title="Testing 4321"
@ -74,8 +73,7 @@ async def test_sensor_available(
outage_count=456,
customers_served=789,
),
):
with patch(
), patch(
"peco.PecoOutageApi.get_map_alerts",
return_value=AlertResults(
alert_content="Testing 1234", alert_title="Testing 4321"

View File

@ -832,8 +832,7 @@ async def test_client_request_missing(hass):
with patch("plexauth.PlexAuth.initiate_auth"), patch(
"plexauth.PlexAuth.token", return_value=None
):
with pytest.raises(RuntimeError):
), pytest.raises(RuntimeError):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
@ -855,8 +854,9 @@ async def test_client_header_issues(hass, current_request_with_host):
"plexauth.PlexAuth.token", return_value=None
), patch(
"homeassistant.components.http.current_request.get", return_value=MockRequest()
), pytest.raises(
RuntimeError
):
with pytest.raises(RuntimeError):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)

View File

@ -33,8 +33,9 @@ async def test_media_lookups(hass, mock_plex_server, requests_mock, playqueue_cr
},
True,
)
with pytest.raises(MediaNotFound) as excinfo:
with patch("plexapi.server.PlexServer.fetchItem", side_effect=NotFound):
with pytest.raises(MediaNotFound) as excinfo, patch(
"plexapi.server.PlexServer.fetchItem", side_effect=NotFound
):
assert await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_PLAY_MEDIA,

View File

@ -62,8 +62,9 @@ async def test_media_player_playback(
# Test media lookup failure
payload = '{"library_name": "Movies", "title": "Movie 1" }'
with patch("plexapi.library.LibrarySection.search", return_value=None):
with pytest.raises(HomeAssistantError) as excinfo:
with patch(
"plexapi.library.LibrarySection.search", return_value=None
), pytest.raises(HomeAssistantError) as excinfo:
assert await hass.services.async_call(
MP_DOMAIN,
SERVICE_PLAY_MEDIA,

View File

@ -37,8 +37,7 @@ def test_session_scope_not_setup(hass_recorder):
hass = hass_recorder()
with patch.object(
util.get_instance(hass), "get_session", return_value=None
), pytest.raises(RuntimeError):
with util.session_scope(hass=hass):
), pytest.raises(RuntimeError), util.session_scope(hass=hass):
pass
@ -689,9 +688,8 @@ async def test_write_lock_db(
with instance.engine.connect() as connection:
connection.execute(text("DROP TABLE events;"))
with util.write_lock_db_sqlite(instance):
with util.write_lock_db_sqlite(instance), pytest.raises(OperationalError):
# Database should be locked now, try writing SQL command
with pytest.raises(OperationalError):
# This needs to be called in another thread since
# the lock method is BEGIN IMMEDIATE and since we have
# a connection per thread with sqlite now, we cannot do it

View File

@ -92,8 +92,7 @@ async def test_service_set_ac_cancel(
with patch(
"renault_api.renault_vehicle.RenaultVehicle.set_ac_stop",
side_effect=RenaultException("Didn't work"),
) as mock_action:
with pytest.raises(HomeAssistantError, match="Didn't work"):
) as mock_action, pytest.raises(HomeAssistantError, match="Didn't work"):
await hass.services.async_call(
DOMAIN, SERVICE_AC_CANCEL, service_data=data, blocking=True
)

View File

@ -97,8 +97,9 @@ async def test_button_failure(
), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_reset_filter",
return_value={"status": "failure"},
), pytest.raises(
HomeAssistantError
):
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,

View File

@ -168,8 +168,7 @@ async def test_climate_fan(
with patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
):
with pytest.raises(HomeAssistantError):
), pytest.raises(HomeAssistantError):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_FAN_MODE,
@ -235,8 +234,7 @@ async def test_climate_swing(
with patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
):
with pytest.raises(HomeAssistantError):
), pytest.raises(HomeAssistantError):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_SWING_MODE,
@ -353,8 +351,7 @@ async def test_climate_temperatures(
with patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
return_value={"result": {"status": "Success"}},
):
with pytest.raises(MultipleInvalid):
), pytest.raises(MultipleInvalid):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
@ -391,8 +388,7 @@ async def test_climate_temperatures(
with patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
return_value={"result": {"status": "Success"}},
):
with pytest.raises(HomeAssistantError):
), pytest.raises(HomeAssistantError):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
@ -447,8 +443,7 @@ async def test_climate_temperature_is_none(
with patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
):
with pytest.raises(ValueError):
), pytest.raises(ValueError):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
@ -634,8 +629,7 @@ async def test_climate_service_failed(
with patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
return_value={"result": {"status": "Error", "failureReason": "Did not work"}},
):
with pytest.raises(HomeAssistantError):
), pytest.raises(HomeAssistantError):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_TURN_OFF,
@ -752,8 +746,9 @@ async def test_climate_set_timer(
), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_timer",
return_value={"status": "failure"},
), pytest.raises(
MultipleInvalid
):
with pytest.raises(MultipleInvalid):
await hass.services.async_call(
DOMAIN,
SERVICE_ENABLE_TIMER,
@ -770,8 +765,9 @@ async def test_climate_set_timer(
), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_timer",
return_value={"status": "failure"},
), pytest.raises(
HomeAssistantError
):
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
DOMAIN,
SERVICE_ENABLE_TIMER,
@ -853,8 +849,9 @@ async def test_climate_pure_boost(
"homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_pureboost",
), pytest.raises(
MultipleInvalid
):
with pytest.raises(MultipleInvalid):
await hass.services.async_call(
DOMAIN,
SERVICE_ENABLE_PURE_BOOST,
@ -954,8 +951,9 @@ async def test_climate_climate_react(
"homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_climate_react",
), pytest.raises(
MultipleInvalid
):
with pytest.raises(MultipleInvalid):
await hass.services.async_call(
DOMAIN,
SERVICE_ENABLE_PURE_BOOST,
@ -1260,8 +1258,9 @@ async def test_climate_full_ac_state(
"homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_states",
), pytest.raises(
MultipleInvalid
):
with pytest.raises(MultipleInvalid):
await hass.services.async_call(
DOMAIN,
SERVICE_FULL_STATE,

View File

@ -75,8 +75,7 @@ async def test_entity_failed_service_calls(
with patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
side_effect=p_error,
):
with pytest.raises(HomeAssistantError):
), pytest.raises(HomeAssistantError):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_FAN_MODE,

View File

@ -89,8 +89,9 @@ async def test_select_set_option(
), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
return_value={"result": {"status": "failed"}},
), pytest.raises(
HomeAssistantError
):
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
@ -130,8 +131,9 @@ async def test_select_set_option(
), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
return_value={"result": {"status": "Failed", "failureReason": "No connection"}},
), pytest.raises(
HomeAssistantError
):
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,

View File

@ -195,8 +195,9 @@ async def test_switch_command_failure(
), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_timer",
return_value={"status": "failure"},
), pytest.raises(
HomeAssistantError
):
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
@ -212,8 +213,9 @@ async def test_switch_command_failure(
), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_del_timer",
return_value={"status": "failure"},
), pytest.raises(
HomeAssistantError
):
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,

View File

@ -72,8 +72,7 @@ def test_send_message_to_api_with_bad_data_throws_error(
signal_requests_mock = signal_requests_mock_factory(False)
with caplog.at_level(
logging.DEBUG, logger="homeassistant.components.signal_messenger.notify"
):
with pytest.raises(SignalCliRestApiError) as exc:
), pytest.raises(SignalCliRestApiError) as exc:
signal_notification_service.send_message(MESSAGE)
assert "Sending signal message" in caplog.text
@ -90,8 +89,7 @@ def test_send_message_with_bad_data_throws_vol_error(
"""Test sending a message with bad data throws an error."""
with caplog.at_level(
logging.DEBUG, logger="homeassistant.components.signal_messenger.notify"
):
with pytest.raises(vol.Invalid) as exc:
), pytest.raises(vol.Invalid) as exc:
data = {"test": "test"}
signal_notification_service.send_message(MESSAGE, **{"data": data})
@ -108,8 +106,7 @@ def test_send_message_with_attachment(
signal_requests_mock = signal_requests_mock_factory()
with caplog.at_level(
logging.DEBUG, logger="homeassistant.components.signal_messenger.notify"
):
with tempfile.NamedTemporaryFile(
), tempfile.NamedTemporaryFile(
mode="w", suffix=".png", prefix=os.path.basename(__file__)
) as temp_file:
temp_file.write("attachment_data")

View File

@ -125,8 +125,7 @@ async def test_discovery(hass, pywemo_registry):
# Setup the component and start discovery.
with patch(
"pywemo.discover_devices", return_value=pywemo_devices
) as mock_discovery:
with patch(
) as mock_discovery, patch(
"homeassistant.components.wemo.WemoDiscovery.discover_statics"
) as mock_discover_statics:
assert await async_setup_component(

View File

@ -192,8 +192,7 @@ async def test_reauthentication(
},
)
with patch("homeassistant.components.yolink.api.ConfigEntryAuth"):
with patch(
with patch("homeassistant.components.yolink.api.ConfigEntryAuth"), patch(
"homeassistant.components.yolink.async_setup_entry", return_value=True
) as mock_setup:
result = await hass.config_entries.flow.async_configure(result["flow_id"])

View File

@ -256,8 +256,7 @@ async def test_gateway_initialize_failure(hass, device_light_1, coordinator):
with patch(
"bellows.zigbee.application.ControllerApplication.new",
side_effect=[asyncio.TimeoutError(), FileNotFoundError(), RuntimeError()],
) as mock_new:
with pytest.raises(RuntimeError):
) as mock_new, pytest.raises(RuntimeError):
await zha_gateway.async_initialize()
assert mock_new.call_count == 3
@ -272,8 +271,7 @@ async def test_gateway_initialize_failure_transient(hass, device_light_1, coordi
with patch(
"bellows.zigbee.application.ControllerApplication.new",
side_effect=[RuntimeError(), zigpy.exceptions.TransientConnectionError()],
) as mock_new:
with pytest.raises(ConfigEntryNotReady):
) as mock_new, pytest.raises(ConfigEntryNotReady):
await zha_gateway.async_initialize()
# Initialization immediately stops and is retried after TransientConnectionError