Merge multiple context managers in tests (#48146)

This commit is contained in:
Franck Nijhof 2021-03-27 09:17:15 +01:00 committed by GitHub
parent 79af18a8ab
commit ad13a9295e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
33 changed files with 590 additions and 627 deletions

View file

@ -501,8 +501,7 @@ 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):
) as call, pytest.raises(InvalidAuthError):
manager.async_create_access_token(refresh_token, ip)
call.assert_called_with(refresh_token, ip)

View file

@ -933,8 +933,7 @@ 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]:
), 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
@ -1206,11 +1205,10 @@ 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
)
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(

View file

@ -28,8 +28,9 @@ 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):
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()

View file

@ -72,10 +72,13 @@ 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(
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(
), 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

View file

@ -237,8 +237,7 @@ 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_setup_component(1, device_tracker.DOMAIN):
assert await async_setup_component(
hass,
device_tracker.DOMAIN,
@ -458,8 +457,7 @@ 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_setup_component(1, device_tracker.DOMAIN):
assert await async_setup_component(
hass,
device_tracker.DOMAIN,

View file

@ -93,8 +93,7 @@ async def test_light_unavailable(
with patch(
"homeassistant.components.elgato.light.Elgato.light",
side_effect=ElgatoError,
):
with patch(
), patch(
"homeassistant.components.elgato.light.Elgato.state",
side_effect=ElgatoError,
):

View file

@ -13,8 +13,9 @@ 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:
) as json_loader, patch(
"homeassistant.components.emulated_hue.save_json"
) as json_saver:
number = conf.entity_id_to_number("light.test")
assert number == "2"
@ -47,8 +48,9 @@ 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:
) 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
@ -79,8 +81,9 @@ 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:
) 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

View file

@ -73,8 +73,9 @@ 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])):
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"},
@ -90,8 +91,9 @@ 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])):
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"},

View file

@ -116,8 +116,7 @@ async def test_chain_history(hass, values, missing=False):
with patch(
"homeassistant.components.history.state_changes_during_period",
return_value=fake_states,
):
with patch(
), patch(
"homeassistant.components.history.get_last_state_changes",
return_value=fake_states,
):
@ -234,8 +233,7 @@ async def test_history_time(hass):
with patch(
"homeassistant.components.history.state_changes_during_period",
return_value=fake_states,
):
with patch(
), patch(
"homeassistant.components.history.get_last_state_changes",
return_value=fake_states,
):

View file

@ -198,8 +198,7 @@ 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):
) 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()

View file

@ -68,8 +68,9 @@ 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):
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)

View file

@ -220,8 +220,9 @@ 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:
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

View file

@ -13,8 +13,7 @@ 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(
), patch(
"homeassistant.components.hisense_aehw4a1.climate.async_setup_entry",
return_value=True,
) as mock_setup:
@ -25,9 +24,7 @@ async def test_creating_entry_sets_up_climate_discovery(hass):
# Confirmation form
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
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.RESULT_TYPE_CREATE_ENTRY
await hass.async_block_till_done()
@ -40,8 +37,7 @@ async def test_configuring_hisense_w4a1_create_entry(hass):
with patch(
"homeassistant.components.hisense_aehw4a1.config_flow.AehW4a1.check",
return_value=True,
):
with patch(
), patch(
"homeassistant.components.hisense_aehw4a1.async_setup_entry",
return_value=True,
) as mock_setup:
@ -60,8 +56,7 @@ 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(
), patch(
"homeassistant.components.hisense_aehw4a1.async_setup_entry",
return_value=True,
) as mock_setup:

View file

@ -162,8 +162,7 @@ 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):
), patch("homeassistant.components.history.get_state", return_value=None):
sensor1.update()
sensor2.update()
sensor3.update()
@ -246,8 +245,7 @@ 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):
), patch("homeassistant.components.history.get_state", return_value=None):
sensor1.update()
sensor2.update()
sensor3.update()

View file

@ -254,8 +254,9 @@ 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):
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()

View file

@ -90,8 +90,7 @@ async def test_full_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

@ -288,8 +288,7 @@ async def test_update(hass):
"""Test update."""
with patch(
"homeassistant.components.melissa.climate._LOGGER.warning"
) as mocked_warning:
with patch("homeassistant.components.melissa"):
) as mocked_warning, patch("homeassistant.components.melissa"):
api = melissa_mock()
device = (await api.async_fetch_devices())[_SERIAL]
thermostat = MelissaClimate(api, _SERIAL, device)
@ -333,8 +332,7 @@ 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"):
) as mocked_warning, patch("homeassistant.components.melissa"):
api = melissa_mock()
device = (await api.async_fetch_devices())[_SERIAL]
thermostat = MelissaClimate(api, _SERIAL, device)
@ -352,8 +350,7 @@ 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"):
) as mocked_warning, patch("homeassistant.components.melissa"):
api = melissa_mock()
device = (await api.async_fetch_devices())[_SERIAL]
thermostat = MelissaClimate(api, _SERIAL, device)

View file

@ -103,11 +103,7 @@ 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(
with patch("aiodns.DNSResolver.query", side_effect=aiodns.error.DNSError,), patch(
"mcstatus.server.MinecraftServer.status",
return_value=PingResponse(STATUS_RESPONSE_RAW),
):
@ -163,8 +159,7 @@ 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):
), patch("mcstatus.server.MinecraftServer.status", side_effect=OSError):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT
)
@ -175,11 +170,7 @@ async def test_connection_failed(hass: HomeAssistantType) -> None:
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(
with patch("aiodns.DNSResolver.query", return_value=SRV_RECORDS,), patch(
"mcstatus.server.MinecraftServer.status",
return_value=PingResponse(STATUS_RESPONSE_RAW),
):
@ -195,11 +186,7 @@ async def test_connection_succeeded_with_srv_record(hass: HomeAssistantType) ->
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(
with patch("aiodns.DNSResolver.query", side_effect=aiodns.error.DNSError,), patch(
"mcstatus.server.MinecraftServer.status",
return_value=PingResponse(STATUS_RESPONSE_RAW),
):
@ -215,12 +202,10 @@ async def test_connection_succeeded_with_host(hass: HomeAssistantType) -> None:
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(
with patch("getmac.get_mac_address", return_value="01:23:45:67:89:ab"), patch(
"aiodns.DNSResolver.query",
side_effect=aiodns.error.DNSError,
):
with patch(
), patch(
"mcstatus.server.MinecraftServer.status",
return_value=PingResponse(STATUS_RESPONSE_RAW),
):
@ -236,12 +221,10 @@ async def test_connection_succeeded_with_ip4(hass: HomeAssistantType) -> None:
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(
with patch("getmac.get_mac_address", return_value="01:23:45:67:89:ab"), patch(
"aiodns.DNSResolver.query",
side_effect=aiodns.error.DNSError,
):
with patch(
), patch(
"mcstatus.server.MinecraftServer.status",
return_value=PingResponse(STATUS_RESPONSE_RAW),
):

View file

@ -743,8 +743,7 @@ 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_setup_component(1, light.DOMAIN):
assert await async_setup_component(hass, light.DOMAIN, config)
await hass.async_block_till_done()

View file

@ -298,8 +298,7 @@ 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_setup_component(1, light.DOMAIN):
assert await async_setup_component(
hass,
light.DOMAIN,

View file

@ -64,8 +64,9 @@ 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:
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: {}}
)
@ -78,8 +79,9 @@ async def test_connection_failed_error(mock_error, hass):
@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:
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: {}}
)
@ -134,11 +136,10 @@ 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}

View file

@ -87,8 +87,7 @@ class TestSignalMesssenger(unittest.TestCase):
)
with self.assertLogs(
"homeassistant.components.signal_messenger.notify", level="WARNING"
) as context:
with tempfile.NamedTemporaryFile(
) as context, tempfile.NamedTemporaryFile(
suffix=".png", prefix=os.path.basename(__file__)
) as tf:
data = {"data": {"attachment": tf.name}}
@ -117,8 +116,7 @@ class TestSignalMesssenger(unittest.TestCase):
)
with self.assertLogs(
"homeassistant.components.signal_messenger.notify", level="DEBUG"
) as context:
with tempfile.NamedTemporaryFile(
) as context, tempfile.NamedTemporaryFile(
suffix=".png", prefix=os.path.basename(__file__)
) as tf:
data = {"data": {"attachments": [tf.name]}}

View file

@ -291,8 +291,7 @@ 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))
):
with patch(
), patch(
"traceback.extract_stack",
MagicMock(
return_value=[

View file

@ -415,8 +415,9 @@ 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):
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)

View file

@ -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):
), 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
)
assert ep_channels.async_new_entity.call_args[0][1] == mock.sentinel.entity_cls
def test_discover_probe_single_cluster():

View file

@ -202,9 +202,9 @@ 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:
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()
@ -212,10 +212,7 @@ async def test_zwave_ready_wait(hass, mock_openzwave, zwave_setup):
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 mock_logger.warning.mock_calls[0][1][1] == const.NETWORK_READY_WAIT_SECS
async def test_device_entity(hass, mock_openzwave):
@ -341,9 +338,9 @@ 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:
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()

View file

@ -99,8 +99,9 @@ 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):
with patch.dict(
config_entries.HANDLERS, {TEST_DOMAIN: TestFlowHandler}
), pytest.raises(TypeError):
TestFlowHandler()

View file

@ -377,8 +377,7 @@ async def test_get_cloud_url(hass: HomeAssistant):
hass.components.cloud,
"async_remote_ui_url",
side_effect=cloud.CloudNotAvailable,
):
with pytest.raises(NoURLAvailableError):
), pytest.raises(NoURLAvailableError):
_get_cloud_url(hass)

View file

@ -561,8 +561,7 @@ 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(
with pytest.raises(exceptions.Unauthorized) as err, patch(
"homeassistant.auth.AuthManager.async_get_user",
return_value=Mock(permissions=PolicyPermissions({}, None)),
):

View file

@ -1221,8 +1221,7 @@ async def test_init_custom_integration(hass):
None,
{"name": "Hue", "dependencies": [], "requirements": [], "domain": "hue"},
)
with pytest.raises(data_entry_flow.UnknownHandler):
with patch(
with pytest.raises(data_entry_flow.UnknownHandler), patch(
"homeassistant.loader.async_get_integration",
return_value=integration,
):

View file

@ -84,8 +84,7 @@ 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):
) as mock_inst, pytest.raises(RequirementsNotFound):
await async_process_requirements(hass, "test_component", ["hello==1.0.0"])
assert len(mock_inst.mock_calls) == 1

View file

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

View file

@ -65,8 +65,7 @@ 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:
with pytest.raises(HomeAssistantError), io.StringIO(conf) as file:
yaml_loader.yaml.load(file, Loader=yaml_loader.SafeLineLoader)