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,10 +21,11 @@ def get_cert(
"""Get the certificate for the host and port combination.""" """Get the certificate for the host and port combination."""
ctx = ssl.create_default_context() ctx = ssl.create_default_context()
address = (host, port) address = (host, port)
with socket.create_connection(address, timeout=TIMEOUT) as sock: with socket.create_connection(address, timeout=TIMEOUT) as sock, ctx.wrap_socket(
with ctx.wrap_socket(sock, server_hostname=address[0]) as ssock: sock, server_hostname=address[0]
cert = ssock.getpeercert() ) as ssock:
return cert cert = ssock.getpeercert()
return cert
async def get_cert_expiry_timestamp( async def get_cert_expiry_timestamp(

View file

@ -661,18 +661,19 @@ def _apply_update( # noqa: C901
), ),
table, table,
) )
with contextlib.suppress(SQLAlchemyError): with contextlib.suppress(SQLAlchemyError), session_scope(
with session_scope(session=session_maker()) as session: session=session_maker()
connection = session.connection() ) as session:
connection.execute( connection = session.connection()
# Using LOCK=EXCLUSIVE to prevent connection.execute(
# the database from corrupting # Using LOCK=EXCLUSIVE to prevent
# https://github.com/home-assistant/core/issues/56104 # the database from corrupting
text( # https://github.com/home-assistant/core/issues/56104
f"ALTER TABLE {table} CONVERT TO CHARACTER SET utf8mb4" text(
" COLLATE utf8mb4_unicode_ci, LOCK=EXCLUSIVE" f"ALTER TABLE {table} CONVERT TO CHARACTER SET utf8mb4"
) " COLLATE utf8mb4_unicode_ci, LOCK=EXCLUSIVE"
) )
)
elif new_version == 22: elif new_version == 22:
# Recreate the all statistics tables for Oracle DB with Identity columns # Recreate the all statistics tables for Oracle DB with Identity columns
# #
@ -804,14 +805,15 @@ def _apply_update( # noqa: C901
if engine.dialect.name == SupportedDialect.MYSQL: if engine.dialect.name == SupportedDialect.MYSQL:
# Ensure the row format is dynamic or the index # Ensure the row format is dynamic or the index
# unique will be too large # unique will be too large
with contextlib.suppress(SQLAlchemyError): with contextlib.suppress(SQLAlchemyError), session_scope(
with session_scope(session=session_maker()) as session: session=session_maker()
connection = session.connection() ) as session:
# This is safe to run multiple times and fast connection = session.connection()
# since the table is small. # This is safe to run multiple times and fast
connection.execute( # since the table is small.
text("ALTER TABLE statistics_meta ROW_FORMAT=DYNAMIC") connection.execute(
) text("ALTER TABLE statistics_meta ROW_FORMAT=DYNAMIC")
)
try: try:
_create_index( _create_index(
session_maker, "statistics_meta", "ix_statistics_meta_statistic_id" session_maker, "statistics_meta", "ix_statistics_meta_statistic_id"

View file

@ -2422,17 +2422,18 @@ def correct_db_schema(
), ),
"statistics_meta", "statistics_meta",
) )
with contextlib.suppress(SQLAlchemyError): with contextlib.suppress(SQLAlchemyError), session_scope(
with session_scope(session=session_maker()) as session: session=session_maker()
connection = session.connection() ) as session:
connection.execute( connection = session.connection()
# Using LOCK=EXCLUSIVE to prevent the database from corrupting connection.execute(
# https://github.com/home-assistant/core/issues/56104 # Using LOCK=EXCLUSIVE to prevent the database from corrupting
text( # https://github.com/home-assistant/core/issues/56104
"ALTER TABLE statistics_meta CONVERT TO CHARACTER SET utf8mb4" text(
" COLLATE utf8mb4_unicode_ci, LOCK=EXCLUSIVE" "ALTER TABLE statistics_meta CONVERT TO CHARACTER SET utf8mb4"
) " COLLATE utf8mb4_unicode_ci, LOCK=EXCLUSIVE"
) )
)
tables: tuple[type[Statistics | StatisticsShortTerm], ...] = ( tables: tuple[type[Statistics | StatisticsShortTerm], ...] = (
Statistics, Statistics,

View file

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

View file

@ -24,15 +24,14 @@ from tests.common import MockConfigEntry
async def test_bluetooth_discovery(hass: HomeAssistant): async def test_bluetooth_discovery(hass: HomeAssistant):
"""Test discovery via bluetooth with a valid device.""" """Test discovery via bluetooth with a valid device."""
with patch_async_ble_device_from_address(WAVE_SERVICE_INFO): with patch_async_ble_device_from_address(WAVE_SERVICE_INFO), patch_airthings_ble(
with patch_airthings_ble( AirthingsDevice(name="Airthings Wave+", identifier="123456")
AirthingsDevice(name="Airthings Wave+", identifier="123456") ):
): result = await hass.config_entries.flow.async_init(
result = await hass.config_entries.flow.async_init( DOMAIN,
DOMAIN, context={"source": SOURCE_BLUETOOTH},
context={"source": SOURCE_BLUETOOTH}, data=WAVE_SERVICE_INFO,
data=WAVE_SERVICE_INFO, )
)
assert result["type"] == FlowResultType.FORM assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "bluetooth_confirm" assert result["step_id"] == "bluetooth_confirm"
@ -66,13 +65,14 @@ async def test_bluetooth_discovery_airthings_ble_update_failed(
"""Test discovery via bluetooth but there's an exception from airthings-ble.""" """Test discovery via bluetooth but there's an exception from airthings-ble."""
for loop in [(Exception(), "unknown"), (BleakError(), "cannot_connect")]: for loop in [(Exception(), "unknown"), (BleakError(), "cannot_connect")]:
exc, reason = loop exc, reason = loop
with patch_async_ble_device_from_address(WAVE_SERVICE_INFO): with patch_async_ble_device_from_address(
with patch_airthings_ble(side_effect=exc): WAVE_SERVICE_INFO
result = await hass.config_entries.flow.async_init( ), patch_airthings_ble(side_effect=exc):
DOMAIN, result = await hass.config_entries.flow.async_init(
context={"source": SOURCE_BLUETOOTH}, DOMAIN,
data=WAVE_SERVICE_INFO, context={"source": SOURCE_BLUETOOTH},
) data=WAVE_SERVICE_INFO,
)
assert result["type"] == FlowResultType.ABORT assert result["type"] == FlowResultType.ABORT
assert result["reason"] == reason assert result["reason"] == reason
@ -99,14 +99,12 @@ async def test_user_setup(hass: HomeAssistant):
with patch( with patch(
"homeassistant.components.airthings_ble.config_flow.async_discovered_service_info", "homeassistant.components.airthings_ble.config_flow.async_discovered_service_info",
return_value=[WAVE_SERVICE_INFO], return_value=[WAVE_SERVICE_INFO],
), patch_async_ble_device_from_address(WAVE_SERVICE_INFO), patch_airthings_ble(
AirthingsDevice(name="Airthings Wave+", identifier="123456")
): ):
with patch_async_ble_device_from_address(WAVE_SERVICE_INFO): result = await hass.config_entries.flow.async_init(
with patch_airthings_ble( DOMAIN, context={"source": SOURCE_USER}
AirthingsDevice(name="Airthings Wave+", identifier="123456") )
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == FlowResultType.FORM assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user" assert result["step_id"] == "user"
assert result["errors"] is None assert result["errors"] is None
@ -167,12 +165,12 @@ async def test_user_setup_unknown_error(hass: HomeAssistant):
with patch( with patch(
"homeassistant.components.airthings_ble.config_flow.async_discovered_service_info", "homeassistant.components.airthings_ble.config_flow.async_discovered_service_info",
return_value=[WAVE_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): result = await hass.config_entries.flow.async_init(
with patch_airthings_ble(None, Exception()): DOMAIN, context={"source": SOURCE_USER}
result = await hass.config_entries.flow.async_init( )
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == FlowResultType.ABORT assert result["type"] == FlowResultType.ABORT
assert result["reason"] == "unknown" assert result["reason"] == "unknown"
@ -183,12 +181,12 @@ async def test_user_setup_unable_to_connect(hass: HomeAssistant):
with patch( with patch(
"homeassistant.components.airthings_ble.config_flow.async_discovered_service_info", "homeassistant.components.airthings_ble.config_flow.async_discovered_service_info",
return_value=[WAVE_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): result = await hass.config_entries.flow.async_init(
with patch_airthings_ble(side_effect=BleakError("An error")): DOMAIN, context={"source": SOURCE_USER}
result = await hass.config_entries.flow.async_init( )
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == FlowResultType.ABORT assert result["type"] == FlowResultType.ABORT
assert result["reason"] == "cannot_connect" assert result["reason"] == "cannot_connect"

View file

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

View file

@ -629,30 +629,28 @@ async def test_async_start_from_history_and_switch_to_watching_state_changes_sin
with patch( with patch(
"homeassistant.components.recorder.history.state_changes_during_period", "homeassistant.components.recorder.history.state_changes_during_period",
_fake_states, _fake_states,
): ), freeze_time(start_time):
await async_setup_component(
hass,
"sensor",
{
"sensor": [
{
"platform": "history_stats",
"entity_id": "binary_sensor.state",
"name": "sensor1",
"state": "on",
"start": "{{ utcnow().replace(hour=0, minute=0, second=0) }}",
"duration": {"hours": 2},
"type": "time",
}
]
},
)
await hass.async_block_till_done()
with freeze_time(start_time): await async_update_entity(hass, "sensor.sensor1")
await async_setup_component( await hass.async_block_till_done()
hass,
"sensor",
{
"sensor": [
{
"platform": "history_stats",
"entity_id": "binary_sensor.state",
"name": "sensor1",
"state": "on",
"start": "{{ utcnow().replace(hour=0, minute=0, second=0) }}",
"duration": {"hours": 2},
"type": "time",
}
]
},
)
await hass.async_block_till_done()
await async_update_entity(hass, "sensor.sensor1")
await hass.async_block_till_done()
assert hass.states.get("sensor.sensor1").state == "0.0" assert hass.states.get("sensor.sensor1").state == "0.0"
@ -729,30 +727,28 @@ async def test_async_start_from_history_and_switch_to_watching_state_changes_sin
with patch( with patch(
"homeassistant.components.recorder.history.state_changes_during_period", "homeassistant.components.recorder.history.state_changes_during_period",
_fake_states, _fake_states,
): ), freeze_time(start_time):
await async_setup_component(
hass,
"sensor",
{
"sensor": [
{
"platform": "history_stats",
"entity_id": "binary_sensor.state",
"name": "sensor1",
"state": "on",
"start": "{{ utcnow().replace(hour=0, minute=0, second=0) }}",
"end": "{{ utcnow() }}",
"type": "time",
}
]
},
)
await hass.async_block_till_done()
with freeze_time(start_time): await async_update_entity(hass, "sensor.sensor1")
await async_setup_component( await hass.async_block_till_done()
hass,
"sensor",
{
"sensor": [
{
"platform": "history_stats",
"entity_id": "binary_sensor.state",
"name": "sensor1",
"state": "on",
"start": "{{ utcnow().replace(hour=0, minute=0, second=0) }}",
"end": "{{ utcnow() }}",
"type": "time",
}
]
},
)
await hass.async_block_till_done()
await async_update_entity(hass, "sensor.sensor1")
await hass.async_block_till_done()
assert hass.states.get("sensor.sensor1").state == "0.0" assert hass.states.get("sensor.sensor1").state == "0.0"
@ -828,58 +824,56 @@ async def test_async_start_from_history_and_switch_to_watching_state_changes_mul
with patch( with patch(
"homeassistant.components.recorder.history.state_changes_during_period", "homeassistant.components.recorder.history.state_changes_during_period",
_fake_states, _fake_states,
): ), freeze_time(start_time):
await async_setup_component(
hass,
"sensor",
{
"sensor": [
{
"platform": "history_stats",
"entity_id": "binary_sensor.state",
"name": "sensor1",
"state": "on",
"start": "{{ utcnow().replace(hour=0, minute=0, second=0) }}",
"duration": {"hours": 2},
"type": "time",
},
{
"platform": "history_stats",
"entity_id": "binary_sensor.state",
"name": "sensor2",
"state": "on",
"start": "{{ utcnow().replace(hour=0, minute=0, second=0) }}",
"duration": {"hours": 2},
"type": "time",
},
{
"platform": "history_stats",
"entity_id": "binary_sensor.state",
"name": "sensor3",
"state": "on",
"start": "{{ utcnow().replace(hour=0, minute=0, second=0) }}",
"duration": {"hours": 2},
"type": "count",
},
{
"platform": "history_stats",
"entity_id": "binary_sensor.state",
"name": "sensor4",
"state": "on",
"start": "{{ utcnow().replace(hour=0, minute=0, second=0) }}",
"duration": {"hours": 2},
"type": "ratio",
},
]
},
)
await hass.async_block_till_done()
with freeze_time(start_time): for i in range(1, 5):
await async_setup_component( await async_update_entity(hass, f"sensor.sensor{i}")
hass, await hass.async_block_till_done()
"sensor",
{
"sensor": [
{
"platform": "history_stats",
"entity_id": "binary_sensor.state",
"name": "sensor1",
"state": "on",
"start": "{{ utcnow().replace(hour=0, minute=0, second=0) }}",
"duration": {"hours": 2},
"type": "time",
},
{
"platform": "history_stats",
"entity_id": "binary_sensor.state",
"name": "sensor2",
"state": "on",
"start": "{{ utcnow().replace(hour=0, minute=0, second=0) }}",
"duration": {"hours": 2},
"type": "time",
},
{
"platform": "history_stats",
"entity_id": "binary_sensor.state",
"name": "sensor3",
"state": "on",
"start": "{{ utcnow().replace(hour=0, minute=0, second=0) }}",
"duration": {"hours": 2},
"type": "count",
},
{
"platform": "history_stats",
"entity_id": "binary_sensor.state",
"name": "sensor4",
"state": "on",
"start": "{{ utcnow().replace(hour=0, minute=0, second=0) }}",
"duration": {"hours": 2},
"type": "ratio",
},
]
},
)
await hass.async_block_till_done()
for i in range(1, 5):
await async_update_entity(hass, f"sensor.sensor{i}")
await hass.async_block_till_done()
assert hass.states.get("sensor.sensor1").state == "0.0" assert hass.states.get("sensor.sensor1").state == "0.0"
assert hass.states.get("sensor.sensor2").state == "0.0" assert hass.states.get("sensor.sensor2").state == "0.0"

View file

@ -140,11 +140,10 @@ async def test_reauthentication_flow(
}, },
) )
with patch("homeassistant.components.lyric.api.ConfigEntryLyricClient"): with patch("homeassistant.components.lyric.api.ConfigEntryLyricClient"), patch(
with patch( "homeassistant.components.lyric.async_setup_entry", return_value=True
"homeassistant.components.lyric.async_setup_entry", return_value=True ) as mock_setup:
) as mock_setup: result = await hass.config_entries.flow.async_configure(result["flow_id"])
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == data_entry_flow.FlowResultType.ABORT assert result["type"] == data_entry_flow.FlowResultType.ABORT
assert result["reason"] == "reauth_successful" assert result["reason"] == "reauth_successful"

View file

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

View file

@ -29,15 +29,14 @@ async def test_unload_entry(hass: HomeAssistant) -> None:
outage_count=0, outage_count=0,
customers_served=350394, customers_served=350394,
), ),
), patch(
"peco.PecoOutageApi.get_map_alerts",
return_value=AlertResults(
alert_content="Testing 1234", alert_title="Testing 4321"
),
): ):
with patch( assert await hass.config_entries.async_setup(config_entry.entry_id)
"peco.PecoOutageApi.get_map_alerts", await hass.async_block_till_done()
return_value=AlertResults(
alert_content="Testing 1234", alert_title="Testing 4321"
),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert hass.data[DOMAIN] assert hass.data[DOMAIN]
entries = hass.config_entries.async_entries(DOMAIN) entries = hass.config_entries.async_entries(DOMAIN)

View file

@ -41,15 +41,14 @@ async def test_sensor_available(
outage_count=456, outage_count=456,
customers_served=789, customers_served=789,
), ),
), patch(
"peco.PecoOutageApi.get_map_alerts",
return_value=AlertResults(
alert_content="Testing 1234", alert_title="Testing 4321"
),
): ):
with patch( assert await hass.config_entries.async_setup(config_entry.entry_id)
"peco.PecoOutageApi.get_map_alerts", await hass.async_block_till_done()
return_value=AlertResults(
alert_content="Testing 1234", alert_title="Testing 4321"
),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert hass.data[DOMAIN] assert hass.data[DOMAIN]
entries = hass.config_entries.async_entries(DOMAIN) entries = hass.config_entries.async_entries(DOMAIN)
@ -74,15 +73,14 @@ async def test_sensor_available(
outage_count=456, outage_count=456,
customers_served=789, customers_served=789,
), ),
), patch(
"peco.PecoOutageApi.get_map_alerts",
return_value=AlertResults(
alert_content="Testing 1234", alert_title="Testing 4321"
),
): ):
with patch( assert await hass.config_entries.async_setup(config_entry.entry_id)
"peco.PecoOutageApi.get_map_alerts", await hass.async_block_till_done()
return_value=AlertResults(
alert_content="Testing 1234", alert_title="Testing 4321"
),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
entries = hass.config_entries.async_entries(DOMAIN) entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 2 assert len(entries) == 2

View file

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

View file

@ -33,18 +33,19 @@ async def test_media_lookups(hass, mock_plex_server, requests_mock, playqueue_cr
}, },
True, True,
) )
with pytest.raises(MediaNotFound) as excinfo: with pytest.raises(MediaNotFound) as excinfo, patch(
with patch("plexapi.server.PlexServer.fetchItem", side_effect=NotFound): "plexapi.server.PlexServer.fetchItem", side_effect=NotFound
assert await hass.services.async_call( ):
MEDIA_PLAYER_DOMAIN, assert await hass.services.async_call(
SERVICE_PLAY_MEDIA, MEDIA_PLAYER_DOMAIN,
{ SERVICE_PLAY_MEDIA,
ATTR_ENTITY_ID: media_player_id, {
ATTR_MEDIA_CONTENT_TYPE: DOMAIN, ATTR_ENTITY_ID: media_player_id,
ATTR_MEDIA_CONTENT_ID: 123, ATTR_MEDIA_CONTENT_TYPE: DOMAIN,
}, ATTR_MEDIA_CONTENT_ID: 123,
True, },
) True,
)
assert "Media for key 123 not found" in str(excinfo.value) assert "Media for key 123 not found" in str(excinfo.value)
# TV show searches # TV show searches

View file

@ -62,19 +62,20 @@ async def test_media_player_playback(
# Test media lookup failure # Test media lookup failure
payload = '{"library_name": "Movies", "title": "Movie 1" }' payload = '{"library_name": "Movies", "title": "Movie 1" }'
with patch("plexapi.library.LibrarySection.search", return_value=None): with patch(
with pytest.raises(HomeAssistantError) as excinfo: "plexapi.library.LibrarySection.search", return_value=None
assert await hass.services.async_call( ), pytest.raises(HomeAssistantError) as excinfo:
MP_DOMAIN, assert await hass.services.async_call(
SERVICE_PLAY_MEDIA, MP_DOMAIN,
{ SERVICE_PLAY_MEDIA,
ATTR_ENTITY_ID: media_player, {
ATTR_MEDIA_CONTENT_TYPE: MediaType.MOVIE, ATTR_ENTITY_ID: media_player,
ATTR_MEDIA_CONTENT_ID: payload, ATTR_MEDIA_CONTENT_TYPE: MediaType.MOVIE,
}, ATTR_MEDIA_CONTENT_ID: payload,
True, },
) True,
assert not playmedia_mock.called )
assert not playmedia_mock.called
assert f"No {MediaType.MOVIE} results in 'Movies' for" in str(excinfo.value) assert f"No {MediaType.MOVIE} results in 'Movies' for" in str(excinfo.value)
movie1 = MockPlexMedia("Movie", "movie") movie1 = MockPlexMedia("Movie", "movie")

View file

@ -37,9 +37,8 @@ def test_session_scope_not_setup(hass_recorder):
hass = hass_recorder() hass = hass_recorder()
with patch.object( with patch.object(
util.get_instance(hass), "get_session", return_value=None util.get_instance(hass), "get_session", return_value=None
), pytest.raises(RuntimeError): ), pytest.raises(RuntimeError), util.session_scope(hass=hass):
with util.session_scope(hass=hass): pass
pass
def test_recorder_bad_commit(hass_recorder, recorder_db_url): def test_recorder_bad_commit(hass_recorder, recorder_db_url):
@ -689,16 +688,15 @@ async def test_write_lock_db(
with instance.engine.connect() as connection: with instance.engine.connect() as connection:
connection.execute(text("DROP TABLE events;")) 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 # Database should be locked now, try writing SQL command
with pytest.raises(OperationalError): # This needs to be called in another thread since
# This needs to be called in another thread since # the lock method is BEGIN IMMEDIATE and since we have
# the lock method is BEGIN IMMEDIATE and since we have # a connection per thread with sqlite now, we cannot do it
# a connection per thread with sqlite now, we cannot do it # in the same thread as the one holding the lock since it
# in the same thread as the one holding the lock since it # would be allowed to proceed as the goal is to prevent
# would be allowed to proceed as the goal is to prevent # all the other threads from accessing the database
# all the other threads from accessing the database await hass.async_add_executor_job(_drop_table)
await hass.async_add_executor_job(_drop_table)
def test_is_second_sunday(): def test_is_second_sunday():

View file

@ -92,11 +92,10 @@ async def test_service_set_ac_cancel(
with patch( with patch(
"renault_api.renault_vehicle.RenaultVehicle.set_ac_stop", "renault_api.renault_vehicle.RenaultVehicle.set_ac_stop",
side_effect=RenaultException("Didn't work"), side_effect=RenaultException("Didn't work"),
) as mock_action: ) as mock_action, pytest.raises(HomeAssistantError, match="Didn't work"):
with pytest.raises(HomeAssistantError, match="Didn't work"): await hass.services.async_call(
await hass.services.async_call( DOMAIN, SERVICE_AC_CANCEL, service_data=data, blocking=True
DOMAIN, SERVICE_AC_CANCEL, service_data=data, blocking=True )
)
assert len(mock_action.mock_calls) == 1 assert len(mock_action.mock_calls) == 1
assert mock_action.mock_calls[0][1] == () assert mock_action.mock_calls[0][1] == ()

View file

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

View file

@ -168,14 +168,13 @@ async def test_climate_fan(
with patch( with patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property", "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
): ), pytest.raises(HomeAssistantError):
with pytest.raises(HomeAssistantError): await hass.services.async_call(
await hass.services.async_call( CLIMATE_DOMAIN,
CLIMATE_DOMAIN, SERVICE_SET_FAN_MODE,
SERVICE_SET_FAN_MODE, {ATTR_ENTITY_ID: state1.entity_id, ATTR_FAN_MODE: "low"},
{ATTR_ENTITY_ID: state1.entity_id, ATTR_FAN_MODE: "low"}, blocking=True,
blocking=True, )
)
await hass.async_block_till_done() await hass.async_block_till_done()
state3 = hass.states.get("climate.hallway") state3 = hass.states.get("climate.hallway")
@ -235,14 +234,13 @@ async def test_climate_swing(
with patch( with patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property", "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
): ), pytest.raises(HomeAssistantError):
with pytest.raises(HomeAssistantError): await hass.services.async_call(
await hass.services.async_call( CLIMATE_DOMAIN,
CLIMATE_DOMAIN, SERVICE_SET_SWING_MODE,
SERVICE_SET_SWING_MODE, {ATTR_ENTITY_ID: state1.entity_id, ATTR_SWING_MODE: "fixedtop"},
{ATTR_ENTITY_ID: state1.entity_id, ATTR_SWING_MODE: "fixedtop"}, blocking=True,
blocking=True, )
)
await hass.async_block_till_done() await hass.async_block_till_done()
state3 = hass.states.get("climate.hallway") state3 = hass.states.get("climate.hallway")
@ -353,14 +351,13 @@ async def test_climate_temperatures(
with patch( with patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property", "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
return_value={"result": {"status": "Success"}}, return_value={"result": {"status": "Success"}},
): ), pytest.raises(MultipleInvalid):
with pytest.raises(MultipleInvalid): await hass.services.async_call(
await hass.services.async_call( CLIMATE_DOMAIN,
CLIMATE_DOMAIN, SERVICE_SET_TEMPERATURE,
SERVICE_SET_TEMPERATURE, {ATTR_ENTITY_ID: state1.entity_id},
{ATTR_ENTITY_ID: state1.entity_id}, blocking=True,
blocking=True, )
)
await hass.async_block_till_done() await hass.async_block_till_done()
state2 = hass.states.get("climate.hallway") state2 = hass.states.get("climate.hallway")
@ -391,14 +388,13 @@ async def test_climate_temperatures(
with patch( with patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property", "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
return_value={"result": {"status": "Success"}}, return_value={"result": {"status": "Success"}},
): ), pytest.raises(HomeAssistantError):
with pytest.raises(HomeAssistantError): await hass.services.async_call(
await hass.services.async_call( CLIMATE_DOMAIN,
CLIMATE_DOMAIN, SERVICE_SET_TEMPERATURE,
SERVICE_SET_TEMPERATURE, {ATTR_ENTITY_ID: state1.entity_id, ATTR_TEMPERATURE: 20},
{ATTR_ENTITY_ID: state1.entity_id, ATTR_TEMPERATURE: 20}, blocking=True,
blocking=True, )
)
await hass.async_block_till_done() await hass.async_block_till_done()
state2 = hass.states.get("climate.hallway") state2 = hass.states.get("climate.hallway")
@ -447,18 +443,17 @@ async def test_climate_temperature_is_none(
with patch( with patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property", "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
): ), pytest.raises(ValueError):
with pytest.raises(ValueError): await hass.services.async_call(
await hass.services.async_call( CLIMATE_DOMAIN,
CLIMATE_DOMAIN, SERVICE_SET_TEMPERATURE,
SERVICE_SET_TEMPERATURE, {
{ ATTR_ENTITY_ID: state1.entity_id,
ATTR_ENTITY_ID: state1.entity_id, ATTR_TARGET_TEMP_HIGH: 30,
ATTR_TARGET_TEMP_HIGH: 30, ATTR_TARGET_TEMP_LOW: 20,
ATTR_TARGET_TEMP_LOW: 20, },
}, blocking=True,
blocking=True, )
)
await hass.async_block_till_done() await hass.async_block_till_done()
state2 = hass.states.get("climate.hallway") state2 = hass.states.get("climate.hallway")
@ -634,14 +629,13 @@ async def test_climate_service_failed(
with patch( with patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property", "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
return_value={"result": {"status": "Error", "failureReason": "Did not work"}}, return_value={"result": {"status": "Error", "failureReason": "Did not work"}},
): ), pytest.raises(HomeAssistantError):
with pytest.raises(HomeAssistantError): await hass.services.async_call(
await hass.services.async_call( CLIMATE_DOMAIN,
CLIMATE_DOMAIN, SERVICE_TURN_OFF,
SERVICE_TURN_OFF, {ATTR_ENTITY_ID: state1.entity_id},
{ATTR_ENTITY_ID: state1.entity_id}, blocking=True,
blocking=True, )
)
await hass.async_block_till_done() await hass.async_block_till_done()
state2 = hass.states.get("climate.hallway") state2 = hass.states.get("climate.hallway")
@ -752,16 +746,17 @@ async def test_climate_set_timer(
), patch( ), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_timer", "homeassistant.components.sensibo.util.SensiboClient.async_set_timer",
return_value={"status": "failure"}, return_value={"status": "failure"},
), pytest.raises(
MultipleInvalid
): ):
with pytest.raises(MultipleInvalid): await hass.services.async_call(
await hass.services.async_call( DOMAIN,
DOMAIN, SERVICE_ENABLE_TIMER,
SERVICE_ENABLE_TIMER, {
{ ATTR_ENTITY_ID: state_climate.entity_id,
ATTR_ENTITY_ID: state_climate.entity_id, },
}, blocking=True,
blocking=True, )
)
await hass.async_block_till_done() await hass.async_block_till_done()
with patch( with patch(
@ -770,17 +765,18 @@ async def test_climate_set_timer(
), patch( ), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_timer", "homeassistant.components.sensibo.util.SensiboClient.async_set_timer",
return_value={"status": "failure"}, return_value={"status": "failure"},
), pytest.raises(
HomeAssistantError
): ):
with pytest.raises(HomeAssistantError): await hass.services.async_call(
await hass.services.async_call( DOMAIN,
DOMAIN, SERVICE_ENABLE_TIMER,
SERVICE_ENABLE_TIMER, {
{ ATTR_ENTITY_ID: state_climate.entity_id,
ATTR_ENTITY_ID: state_climate.entity_id, ATTR_MINUTES: 30,
ATTR_MINUTES: 30, },
}, blocking=True,
blocking=True, )
)
await hass.async_block_till_done() await hass.async_block_till_done()
with patch( with patch(
@ -853,19 +849,20 @@ async def test_climate_pure_boost(
"homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data", "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
), patch( ), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_pureboost", "homeassistant.components.sensibo.util.SensiboClient.async_set_pureboost",
), pytest.raises(
MultipleInvalid
): ):
with pytest.raises(MultipleInvalid): await hass.services.async_call(
await hass.services.async_call( DOMAIN,
DOMAIN, SERVICE_ENABLE_PURE_BOOST,
SERVICE_ENABLE_PURE_BOOST, {
{ ATTR_ENTITY_ID: state_climate.entity_id,
ATTR_ENTITY_ID: state_climate.entity_id, ATTR_INDOOR_INTEGRATION: True,
ATTR_INDOOR_INTEGRATION: True, ATTR_OUTDOOR_INTEGRATION: True,
ATTR_OUTDOOR_INTEGRATION: True, ATTR_SENSITIVITY: "Sensitive",
ATTR_SENSITIVITY: "Sensitive", },
}, blocking=True,
blocking=True, )
)
await hass.async_block_till_done() await hass.async_block_till_done()
with patch( with patch(
@ -954,19 +951,20 @@ async def test_climate_climate_react(
"homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data", "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
), patch( ), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_climate_react", "homeassistant.components.sensibo.util.SensiboClient.async_set_climate_react",
), pytest.raises(
MultipleInvalid
): ):
with pytest.raises(MultipleInvalid): await hass.services.async_call(
await hass.services.async_call( DOMAIN,
DOMAIN, SERVICE_ENABLE_PURE_BOOST,
SERVICE_ENABLE_PURE_BOOST, {
{ ATTR_ENTITY_ID: state_climate.entity_id,
ATTR_ENTITY_ID: state_climate.entity_id, ATTR_LOW_TEMPERATURE_THRESHOLD: 0.2,
ATTR_LOW_TEMPERATURE_THRESHOLD: 0.2, ATTR_HIGH_TEMPERATURE_THRESHOLD: 30.3,
ATTR_HIGH_TEMPERATURE_THRESHOLD: 30.3, ATTR_SMART_TYPE: "temperature",
ATTR_SMART_TYPE: "temperature", },
}, blocking=True,
blocking=True, )
)
await hass.async_block_till_done() await hass.async_block_till_done()
with patch( with patch(
@ -1260,17 +1258,18 @@ async def test_climate_full_ac_state(
"homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data", "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
), patch( ), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_states", "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_states",
), pytest.raises(
MultipleInvalid
): ):
with pytest.raises(MultipleInvalid): await hass.services.async_call(
await hass.services.async_call( DOMAIN,
DOMAIN, SERVICE_FULL_STATE,
SERVICE_FULL_STATE, {
{ ATTR_ENTITY_ID: state_climate.entity_id,
ATTR_ENTITY_ID: state_climate.entity_id, ATTR_TARGET_TEMPERATURE: 22,
ATTR_TARGET_TEMPERATURE: 22, },
}, blocking=True,
blocking=True, )
)
await hass.async_block_till_done() await hass.async_block_till_done()
with patch( with patch(

View file

@ -75,14 +75,13 @@ async def test_entity_failed_service_calls(
with patch( with patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property", "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
side_effect=p_error, side_effect=p_error,
): ), pytest.raises(HomeAssistantError):
with pytest.raises(HomeAssistantError): await hass.services.async_call(
await hass.services.async_call( CLIMATE_DOMAIN,
CLIMATE_DOMAIN, SERVICE_SET_FAN_MODE,
SERVICE_SET_FAN_MODE, {ATTR_ENTITY_ID: state.entity_id, ATTR_FAN_MODE: "low"},
{ATTR_ENTITY_ID: state.entity_id, ATTR_FAN_MODE: "low"}, blocking=True,
blocking=True, )
)
state = hass.states.get("climate.hallway") state = hass.states.get("climate.hallway")
assert state.attributes["fan_mode"] == "low" assert state.attributes["fan_mode"] == "low"

View file

@ -89,14 +89,15 @@ async def test_select_set_option(
), patch( ), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property", "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
return_value={"result": {"status": "failed"}}, return_value={"result": {"status": "failed"}},
), pytest.raises(
HomeAssistantError
): ):
with pytest.raises(HomeAssistantError): await hass.services.async_call(
await hass.services.async_call( SELECT_DOMAIN,
SELECT_DOMAIN, SERVICE_SELECT_OPTION,
SERVICE_SELECT_OPTION, {ATTR_ENTITY_ID: state1.entity_id, ATTR_OPTION: "fixedleft"},
{ATTR_ENTITY_ID: state1.entity_id, ATTR_OPTION: "fixedleft"}, blocking=True,
blocking=True, )
)
await hass.async_block_till_done() await hass.async_block_till_done()
state2 = hass.states.get("select.hallway_horizontal_swing") state2 = hass.states.get("select.hallway_horizontal_swing")
@ -130,14 +131,15 @@ async def test_select_set_option(
), patch( ), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property", "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
return_value={"result": {"status": "Failed", "failureReason": "No connection"}}, return_value={"result": {"status": "Failed", "failureReason": "No connection"}},
), pytest.raises(
HomeAssistantError
): ):
with pytest.raises(HomeAssistantError): await hass.services.async_call(
await hass.services.async_call( SELECT_DOMAIN,
SELECT_DOMAIN, SERVICE_SELECT_OPTION,
SERVICE_SELECT_OPTION, {ATTR_ENTITY_ID: state1.entity_id, ATTR_OPTION: "fixedleft"},
{ATTR_ENTITY_ID: state1.entity_id, ATTR_OPTION: "fixedleft"}, blocking=True,
blocking=True, )
)
await hass.async_block_till_done() await hass.async_block_till_done()
state2 = hass.states.get("select.hallway_horizontal_swing") state2 = hass.states.get("select.hallway_horizontal_swing")

View file

@ -195,16 +195,17 @@ async def test_switch_command_failure(
), patch( ), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_set_timer", "homeassistant.components.sensibo.util.SensiboClient.async_set_timer",
return_value={"status": "failure"}, return_value={"status": "failure"},
), pytest.raises(
HomeAssistantError
): ):
with pytest.raises(HomeAssistantError): await hass.services.async_call(
await hass.services.async_call( SWITCH_DOMAIN,
SWITCH_DOMAIN, SERVICE_TURN_ON,
SERVICE_TURN_ON, {
{ ATTR_ENTITY_ID: state1.entity_id,
ATTR_ENTITY_ID: state1.entity_id, },
}, blocking=True,
blocking=True, )
)
with patch( with patch(
"homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data", "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
@ -212,16 +213,17 @@ async def test_switch_command_failure(
), patch( ), patch(
"homeassistant.components.sensibo.util.SensiboClient.async_del_timer", "homeassistant.components.sensibo.util.SensiboClient.async_del_timer",
return_value={"status": "failure"}, return_value={"status": "failure"},
), pytest.raises(
HomeAssistantError
): ):
with pytest.raises(HomeAssistantError): await hass.services.async_call(
await hass.services.async_call( SWITCH_DOMAIN,
SWITCH_DOMAIN, SERVICE_TURN_OFF,
SERVICE_TURN_OFF, {
{ ATTR_ENTITY_ID: state1.entity_id,
ATTR_ENTITY_ID: state1.entity_id, },
}, blocking=True,
blocking=True, )
)
async def test_switch_climate_react( async def test_switch_climate_react(

View file

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

View file

@ -125,27 +125,26 @@ async def test_discovery(hass, pywemo_registry):
# Setup the component and start discovery. # Setup the component and start discovery.
with patch( with patch(
"pywemo.discover_devices", return_value=pywemo_devices "pywemo.discover_devices", return_value=pywemo_devices
) as mock_discovery: ) as mock_discovery, patch(
with patch( "homeassistant.components.wemo.WemoDiscovery.discover_statics"
"homeassistant.components.wemo.WemoDiscovery.discover_statics" ) as mock_discover_statics:
) as mock_discover_statics: assert await async_setup_component(
assert await async_setup_component( hass, DOMAIN, {DOMAIN: {CONF_DISCOVERY: True}}
hass, DOMAIN, {DOMAIN: {CONF_DISCOVERY: True}} )
) await pywemo_registry.semaphore.acquire() # Returns after platform setup.
await pywemo_registry.semaphore.acquire() # Returns after platform setup. mock_discovery.assert_called()
mock_discovery.assert_called() mock_discover_statics.assert_called()
mock_discover_statics.assert_called() pywemo_devices.append(create_device(2))
pywemo_devices.append(create_device(2))
# Test that discovery runs periodically and the async_dispatcher_send code works. # Test that discovery runs periodically and the async_dispatcher_send code works.
async_fire_time_changed( async_fire_time_changed(
hass, hass,
dt.utcnow() dt.utcnow()
+ timedelta(seconds=WemoDiscovery.ADDITIONAL_SECONDS_BETWEEN_SCANS + 1), + timedelta(seconds=WemoDiscovery.ADDITIONAL_SECONDS_BETWEEN_SCANS + 1),
) )
await hass.async_block_till_done() await hass.async_block_till_done()
# Test that discover_statics runs during discovery # Test that discover_statics runs during discovery
assert mock_discover_statics.call_count == 3 assert mock_discover_statics.call_count == 3
# Verify that the expected number of devices were setup. # Verify that the expected number of devices were setup.
entity_reg = er.async_get(hass) entity_reg = er.async_get(hass)

View file

@ -192,11 +192,10 @@ async def test_reauthentication(
}, },
) )
with patch("homeassistant.components.yolink.api.ConfigEntryAuth"): with patch("homeassistant.components.yolink.api.ConfigEntryAuth"), patch(
with patch( "homeassistant.components.yolink.async_setup_entry", return_value=True
"homeassistant.components.yolink.async_setup_entry", return_value=True ) as mock_setup:
) as mock_setup: result = await hass.config_entries.flow.async_configure(result["flow_id"])
result = await hass.config_entries.flow.async_configure(result["flow_id"])
token_data = old_entry.data["token"] token_data = old_entry.data["token"]
assert token_data["access_token"] == "mock-access-token" assert token_data["access_token"] == "mock-access-token"
assert token_data["refresh_token"] == "mock-refresh-token" assert token_data["refresh_token"] == "mock-refresh-token"

View file

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